ZhengyangZhang commited on
Commit
8aaa6a8
·
verified ·
1 Parent(s): 08ec41e

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. lib/python3.12/site-packages/transformers/models/__pycache__/__init__.cpython-312.pyc +0 -0
  2. lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__init__.py +28 -0
  3. lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/__init__.cpython-312.pyc +0 -0
  4. lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/configuration_audio_spectrogram_transformer.cpython-312.pyc +0 -0
  5. lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/feature_extraction_audio_spectrogram_transformer.cpython-312.pyc +0 -0
  6. lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/modeling_audio_spectrogram_transformer.cpython-312.pyc +0 -0
  7. lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/configuration_audio_spectrogram_transformer.py +131 -0
  8. lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.py +239 -0
  9. lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py +650 -0
  10. lib/python3.12/site-packages/transformers/models/bart/__init__.py +31 -0
  11. lib/python3.12/site-packages/transformers/models/bart/__pycache__/__init__.cpython-312.pyc +0 -0
  12. lib/python3.12/site-packages/transformers/models/bart/__pycache__/configuration_bart.cpython-312.pyc +0 -0
  13. lib/python3.12/site-packages/transformers/models/bart/__pycache__/modeling_flax_bart.cpython-312.pyc +0 -0
  14. lib/python3.12/site-packages/transformers/models/bart/__pycache__/modeling_tf_bart.cpython-312.pyc +0 -0
  15. lib/python3.12/site-packages/transformers/models/bart/__pycache__/tokenization_bart.cpython-312.pyc +0 -0
  16. lib/python3.12/site-packages/transformers/models/bart/__pycache__/tokenization_bart_fast.cpython-312.pyc +0 -0
  17. lib/python3.12/site-packages/transformers/models/bart/configuration_bart.py +405 -0
  18. lib/python3.12/site-packages/transformers/models/bart/modeling_bart.py +0 -0
  19. lib/python3.12/site-packages/transformers/models/bart/modeling_flax_bart.py +2006 -0
  20. lib/python3.12/site-packages/transformers/models/bart/modeling_tf_bart.py +1714 -0
  21. lib/python3.12/site-packages/transformers/models/bart/tokenization_bart.py +393 -0
  22. lib/python3.12/site-packages/transformers/models/bart/tokenization_bart_fast.py +271 -0
  23. lib/python3.12/site-packages/transformers/models/big_bird/__init__.py +30 -0
  24. lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/__init__.cpython-312.pyc +0 -0
  25. lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/configuration_big_bird.cpython-312.pyc +0 -0
  26. lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/tokenization_big_bird.cpython-312.pyc +0 -0
  27. lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/tokenization_big_bird_fast.cpython-312.pyc +0 -0
  28. lib/python3.12/site-packages/transformers/models/big_bird/configuration_big_bird.py +176 -0
  29. lib/python3.12/site-packages/transformers/models/big_bird/modeling_big_bird.py +0 -0
  30. lib/python3.12/site-packages/transformers/models/big_bird/modeling_flax_big_bird.py +0 -0
  31. lib/python3.12/site-packages/transformers/models/big_bird/tokenization_big_bird.py +324 -0
  32. lib/python3.12/site-packages/transformers/models/big_bird/tokenization_big_bird_fast.py +232 -0
  33. lib/python3.12/site-packages/transformers/models/blip/__init__.py +31 -0
  34. lib/python3.12/site-packages/transformers/models/blip/__pycache__/__init__.cpython-312.pyc +0 -0
  35. lib/python3.12/site-packages/transformers/models/blip/__pycache__/configuration_blip.cpython-312.pyc +0 -0
  36. lib/python3.12/site-packages/transformers/models/blip/__pycache__/image_processing_blip.cpython-312.pyc +0 -0
  37. lib/python3.12/site-packages/transformers/models/blip/__pycache__/image_processing_blip_fast.cpython-312.pyc +0 -0
  38. lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_blip.cpython-312.pyc +0 -0
  39. lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_blip_text.cpython-312.pyc +0 -0
  40. lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip.cpython-312.pyc +0 -0
  41. lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip_text.cpython-312.pyc +0 -0
  42. lib/python3.12/site-packages/transformers/models/blip/__pycache__/processing_blip.cpython-312.pyc +0 -0
  43. lib/python3.12/site-packages/transformers/models/blip/configuration_blip.py +329 -0
  44. lib/python3.12/site-packages/transformers/models/blip/image_processing_blip.py +296 -0
  45. lib/python3.12/site-packages/transformers/models/blip/image_processing_blip_fast.py +39 -0
  46. lib/python3.12/site-packages/transformers/models/blip/modeling_blip.py +1605 -0
  47. lib/python3.12/site-packages/transformers/models/blip/modeling_blip_text.py +958 -0
  48. lib/python3.12/site-packages/transformers/models/blip/modeling_tf_blip.py +1709 -0
  49. lib/python3.12/site-packages/transformers/models/blip/modeling_tf_blip_text.py +1122 -0
  50. lib/python3.12/site-packages/transformers/models/blip/processing_blip.py +139 -0
lib/python3.12/site-packages/transformers/models/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (6.88 kB). View file
 
lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__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_audio_spectrogram_transformer import *
22
+ from .feature_extraction_audio_spectrogram_transformer import *
23
+ from .modeling_audio_spectrogram_transformer 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__)
lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (799 Bytes). View file
 
lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/configuration_audio_spectrogram_transformer.cpython-312.pyc ADDED
Binary file (5.44 kB). View file
 
lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/feature_extraction_audio_spectrogram_transformer.cpython-312.pyc ADDED
Binary file (10.6 kB). View file
 
lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/modeling_audio_spectrogram_transformer.cpython-312.pyc ADDED
Binary file (34.3 kB). View file
 
lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/configuration_audio_spectrogram_transformer.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 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
+ """Audio Spectogram Transformer (AST) model configuration"""
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 ASTConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`ASTModel`]. It is used to instantiate an AST
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 AST
31
+ [MIT/ast-finetuned-audioset-10-10-0.4593](https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593)
32
+ 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
+ Args:
38
+ hidden_size (`int`, *optional*, defaults to 768):
39
+ Dimensionality of the encoder layers and the pooler layer.
40
+ num_hidden_layers (`int`, *optional*, defaults to 12):
41
+ Number of hidden layers in the Transformer encoder.
42
+ num_attention_heads (`int`, *optional*, defaults to 12):
43
+ Number of attention heads for each attention layer in the Transformer encoder.
44
+ intermediate_size (`int`, *optional*, defaults to 3072):
45
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
46
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
47
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
48
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
49
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
50
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
51
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
52
+ The dropout ratio for the attention probabilities.
53
+ initializer_range (`float`, *optional*, defaults to 0.02):
54
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
55
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
56
+ The epsilon used by the layer normalization layers.
57
+ patch_size (`int`, *optional*, defaults to 16):
58
+ The size (resolution) of each patch.
59
+ qkv_bias (`bool`, *optional*, defaults to `True`):
60
+ Whether to add a bias to the queries, keys and values.
61
+ frequency_stride (`int`, *optional*, defaults to 10):
62
+ Frequency stride to use when patchifying the spectrograms.
63
+ time_stride (`int`, *optional*, defaults to 10):
64
+ Temporal stride to use when patchifying the spectrograms.
65
+ max_length (`int`, *optional*, defaults to 1024):
66
+ Temporal dimension of the spectrograms.
67
+ num_mel_bins (`int`, *optional*, defaults to 128):
68
+ Frequency dimension of the spectrograms (number of Mel-frequency bins).
69
+
70
+ Example:
71
+
72
+ ```python
73
+ >>> from transformers import ASTConfig, ASTModel
74
+
75
+ >>> # Initializing a AST MIT/ast-finetuned-audioset-10-10-0.4593 style configuration
76
+ >>> configuration = ASTConfig()
77
+
78
+ >>> # Initializing a model (with random weights) from the MIT/ast-finetuned-audioset-10-10-0.4593 style configuration
79
+ >>> model = ASTModel(configuration)
80
+
81
+ >>> # Accessing the model configuration
82
+ >>> configuration = model.config
83
+ ```"""
84
+
85
+ model_type = "audio-spectrogram-transformer"
86
+
87
+ def __init__(
88
+ self,
89
+ hidden_size=768,
90
+ num_hidden_layers=12,
91
+ num_attention_heads=12,
92
+ intermediate_size=3072,
93
+ hidden_act="gelu",
94
+ hidden_dropout_prob=0.0,
95
+ attention_probs_dropout_prob=0.0,
96
+ initializer_range=0.02,
97
+ layer_norm_eps=1e-12,
98
+ patch_size=16,
99
+ qkv_bias=True,
100
+ frequency_stride=10,
101
+ time_stride=10,
102
+ max_length=1024,
103
+ num_mel_bins=128,
104
+ **kwargs,
105
+ ):
106
+ super().__init__(**kwargs)
107
+
108
+ self.hidden_size = hidden_size
109
+ self.num_hidden_layers = num_hidden_layers
110
+ self.num_attention_heads = num_attention_heads
111
+ self.intermediate_size = intermediate_size
112
+ self.hidden_act = hidden_act
113
+ self.hidden_dropout_prob = hidden_dropout_prob
114
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
115
+ self.initializer_range = initializer_range
116
+ self.layer_norm_eps = layer_norm_eps
117
+ self.patch_size = patch_size
118
+ self.qkv_bias = qkv_bias
119
+ self.frequency_stride = frequency_stride
120
+ self.time_stride = time_stride
121
+ self.max_length = max_length
122
+ self.num_mel_bins = num_mel_bins
123
+
124
+ # Overwritten from the parent class: AST is not compatible with `generate`, but has a config parameter sharing the
125
+ # same name (`max_length`). Sharing the same name triggers checks regarding the config -> generation_config
126
+ # generative parameters deprecation cycle, overwriting this function prevents this from happening.
127
+ def _get_non_default_generation_parameters(self) -> Dict[str, Any]:
128
+ return {}
129
+
130
+
131
+ __all__ = ["ASTConfig"]
lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Feature extractor class for Audio Spectrogram Transformer.
17
+ """
18
+
19
+ from typing import List, Optional, Union
20
+
21
+ import numpy as np
22
+
23
+ from ...audio_utils import mel_filter_bank, spectrogram, window_function
24
+ from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
25
+ from ...feature_extraction_utils import BatchFeature
26
+ from ...utils import TensorType, is_speech_available, is_torch_available, logging
27
+
28
+
29
+ if is_speech_available():
30
+ import torchaudio.compliance.kaldi as ta_kaldi
31
+
32
+ if is_torch_available():
33
+ import torch
34
+
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+
39
+ class ASTFeatureExtractor(SequenceFeatureExtractor):
40
+ r"""
41
+ Constructs a Audio Spectrogram Transformer (AST) feature extractor.
42
+
43
+ This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
44
+ most of the main methods. Users should refer to this superclass for more information regarding those methods.
45
+
46
+ This class extracts mel-filter bank features from raw speech using TorchAudio if installed or using numpy
47
+ otherwise, pads/truncates them to a fixed length and normalizes them using a mean and standard deviation.
48
+
49
+ Args:
50
+ feature_size (`int`, *optional*, defaults to 1):
51
+ The feature dimension of the extracted features.
52
+ sampling_rate (`int`, *optional*, defaults to 16000):
53
+ The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
54
+ num_mel_bins (`int`, *optional*, defaults to 128):
55
+ Number of Mel-frequency bins.
56
+ max_length (`int`, *optional*, defaults to 1024):
57
+ Maximum length to which to pad/truncate the extracted features.
58
+ do_normalize (`bool`, *optional*, defaults to `True`):
59
+ Whether or not to normalize the log-Mel features using `mean` and `std`.
60
+ mean (`float`, *optional*, defaults to -4.2677393):
61
+ The mean value used to normalize the log-Mel features. Uses the AudioSet mean by default.
62
+ std (`float`, *optional*, defaults to 4.5689974):
63
+ The standard deviation value used to normalize the log-Mel features. Uses the AudioSet standard deviation
64
+ by default.
65
+ return_attention_mask (`bool`, *optional*, defaults to `False`):
66
+ Whether or not [`~ASTFeatureExtractor.__call__`] should return `attention_mask`.
67
+ """
68
+
69
+ model_input_names = ["input_values", "attention_mask"]
70
+
71
+ def __init__(
72
+ self,
73
+ feature_size=1,
74
+ sampling_rate=16000,
75
+ num_mel_bins=128,
76
+ max_length=1024,
77
+ padding_value=0.0,
78
+ do_normalize=True,
79
+ mean=-4.2677393,
80
+ std=4.5689974,
81
+ return_attention_mask=False,
82
+ **kwargs,
83
+ ):
84
+ super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs)
85
+ self.num_mel_bins = num_mel_bins
86
+ self.max_length = max_length
87
+ self.do_normalize = do_normalize
88
+ self.mean = mean
89
+ self.std = std
90
+ self.return_attention_mask = return_attention_mask
91
+
92
+ if not is_speech_available():
93
+ mel_filters = mel_filter_bank(
94
+ num_frequency_bins=257,
95
+ num_mel_filters=self.num_mel_bins,
96
+ min_frequency=20,
97
+ max_frequency=sampling_rate // 2,
98
+ sampling_rate=sampling_rate,
99
+ norm=None,
100
+ mel_scale="kaldi",
101
+ triangularize_in_mel_space=True,
102
+ )
103
+
104
+ self.mel_filters = mel_filters
105
+ self.window = window_function(400, "hann", periodic=False)
106
+
107
+ def _extract_fbank_features(
108
+ self,
109
+ waveform: np.ndarray,
110
+ max_length: int,
111
+ ) -> np.ndarray:
112
+ """
113
+ Get mel-filter bank features using TorchAudio. Note that TorchAudio requires 16-bit signed integers as inputs
114
+ and hence the waveform should not be normalized before feature extraction.
115
+ """
116
+ # waveform = waveform * (2**15) # Kaldi compliance: 16-bit signed integers
117
+ if is_speech_available():
118
+ waveform = torch.from_numpy(waveform).unsqueeze(0)
119
+ fbank = ta_kaldi.fbank(
120
+ waveform,
121
+ sample_frequency=self.sampling_rate,
122
+ window_type="hanning",
123
+ num_mel_bins=self.num_mel_bins,
124
+ )
125
+ else:
126
+ waveform = np.squeeze(waveform)
127
+ fbank = spectrogram(
128
+ waveform,
129
+ self.window,
130
+ frame_length=400,
131
+ hop_length=160,
132
+ fft_length=512,
133
+ power=2.0,
134
+ center=False,
135
+ preemphasis=0.97,
136
+ mel_filters=self.mel_filters,
137
+ log_mel="log",
138
+ mel_floor=1.192092955078125e-07,
139
+ remove_dc_offset=True,
140
+ ).T
141
+
142
+ fbank = torch.from_numpy(fbank)
143
+
144
+ n_frames = fbank.shape[0]
145
+ difference = max_length - n_frames
146
+
147
+ # pad or truncate, depending on difference
148
+ if difference > 0:
149
+ pad_module = torch.nn.ZeroPad2d((0, 0, 0, difference))
150
+ fbank = pad_module(fbank)
151
+ elif difference < 0:
152
+ fbank = fbank[0:max_length, :]
153
+
154
+ fbank = fbank.numpy()
155
+
156
+ return fbank
157
+
158
+ def normalize(self, input_values: np.ndarray) -> np.ndarray:
159
+ return (input_values - (self.mean)) / (self.std * 2)
160
+
161
+ def __call__(
162
+ self,
163
+ raw_speech: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]],
164
+ sampling_rate: Optional[int] = None,
165
+ return_tensors: Optional[Union[str, TensorType]] = None,
166
+ **kwargs,
167
+ ) -> BatchFeature:
168
+ """
169
+ Main method to featurize and prepare for the model one or several sequence(s).
170
+
171
+ Args:
172
+ raw_speech (`np.ndarray`, `List[float]`, `List[np.ndarray]`, `List[List[float]]`):
173
+ The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
174
+ values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
175
+ stereo, i.e. single float per timestep.
176
+ sampling_rate (`int`, *optional*):
177
+ The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
178
+ `sampling_rate` at the forward call to prevent silent errors.
179
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
180
+ If set, will return tensors instead of list of python integers. Acceptable values are:
181
+
182
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
183
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
184
+ - `'np'`: Return Numpy `np.ndarray` objects.
185
+ """
186
+
187
+ if sampling_rate is not None:
188
+ if sampling_rate != self.sampling_rate:
189
+ raise ValueError(
190
+ f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
191
+ f" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"
192
+ f" {self.sampling_rate} and not {sampling_rate}."
193
+ )
194
+ else:
195
+ logger.warning(
196
+ f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
197
+ "Failing to do so can result in silent errors that might be hard to debug."
198
+ )
199
+
200
+ is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
201
+ if is_batched_numpy and len(raw_speech.shape) > 2:
202
+ raise ValueError(f"Only mono-channel audio is supported for input to {self}")
203
+ is_batched = is_batched_numpy or (
204
+ isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list)))
205
+ )
206
+
207
+ if is_batched:
208
+ raw_speech = [np.asarray(speech, dtype=np.float32) for speech in raw_speech]
209
+ elif not is_batched and not isinstance(raw_speech, np.ndarray):
210
+ raw_speech = np.asarray(raw_speech, dtype=np.float32)
211
+ elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
212
+ raw_speech = raw_speech.astype(np.float32)
213
+
214
+ # always return batch
215
+ if not is_batched:
216
+ raw_speech = [raw_speech]
217
+
218
+ # extract fbank features and pad/truncate to max_length
219
+ features = [self._extract_fbank_features(waveform, max_length=self.max_length) for waveform in raw_speech]
220
+
221
+ # convert into BatchFeature
222
+ padded_inputs = BatchFeature({"input_values": features})
223
+
224
+ # make sure list is in array format
225
+ input_values = padded_inputs.get("input_values")
226
+ if isinstance(input_values[0], list):
227
+ padded_inputs["input_values"] = [np.asarray(feature, dtype=np.float32) for feature in input_values]
228
+
229
+ # normalization
230
+ if self.do_normalize:
231
+ padded_inputs["input_values"] = [self.normalize(feature) for feature in input_values]
232
+
233
+ if return_tensors is not None:
234
+ padded_inputs = padded_inputs.convert_to_tensors(return_tensors)
235
+
236
+ return padded_inputs
237
+
238
+
239
+ __all__ = ["ASTFeatureExtractor"]
lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py ADDED
@@ -0,0 +1,650 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 MIT 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 Audio Spectrogram Transformer (AST) model."""
16
+
17
+ from typing import Callable, Dict, List, Optional, Set, Tuple, Union
18
+
19
+ import torch
20
+ import torch.utils.checkpoint
21
+ from torch import nn
22
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
23
+
24
+ from ...activations import ACT2FN
25
+ from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, SequenceClassifierOutput
26
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
27
+ from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
28
+ from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
29
+ from .configuration_audio_spectrogram_transformer import ASTConfig
30
+
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+ # General docstring
35
+ _CONFIG_FOR_DOC = "ASTConfig"
36
+
37
+ # Base docstring
38
+ _CHECKPOINT_FOR_DOC = "MIT/ast-finetuned-audioset-10-10-0.4593"
39
+ _EXPECTED_OUTPUT_SHAPE = [1, 1214, 768]
40
+
41
+ # Audio classification docstring
42
+ _SEQ_CLASS_CHECKPOINT = "MIT/ast-finetuned-audioset-10-10-0.4593"
43
+ _SEQ_CLASS_EXPECTED_OUTPUT = "'Speech'"
44
+ _SEQ_CLASS_EXPECTED_LOSS = 0.17
45
+
46
+
47
+ class ASTEmbeddings(nn.Module):
48
+ """
49
+ Construct the CLS token, position and patch embeddings.
50
+ """
51
+
52
+ def __init__(self, config: ASTConfig) -> None:
53
+ super().__init__()
54
+
55
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
56
+ self.distillation_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
57
+ self.patch_embeddings = ASTPatchEmbeddings(config)
58
+
59
+ frequency_out_dimension, time_out_dimension = self.get_shape(config)
60
+ num_patches = frequency_out_dimension * time_out_dimension
61
+ self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 2, config.hidden_size))
62
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
63
+ self.config = config
64
+
65
+ def get_shape(self, config):
66
+ # see Karpathy's cs231n blog on how to calculate the output dimensions
67
+ # https://cs231n.github.io/convolutional-networks/#conv
68
+ frequency_out_dimension = (config.num_mel_bins - config.patch_size) // config.frequency_stride + 1
69
+ time_out_dimension = (config.max_length - config.patch_size) // config.time_stride + 1
70
+
71
+ return frequency_out_dimension, time_out_dimension
72
+
73
+ def forward(self, input_values: torch.Tensor) -> torch.Tensor:
74
+ batch_size = input_values.shape[0]
75
+ embeddings = self.patch_embeddings(input_values)
76
+
77
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1)
78
+ distillation_tokens = self.distillation_token.expand(batch_size, -1, -1)
79
+ embeddings = torch.cat((cls_tokens, distillation_tokens, embeddings), dim=1)
80
+ embeddings = embeddings + self.position_embeddings
81
+ embeddings = self.dropout(embeddings)
82
+
83
+ return embeddings
84
+
85
+
86
+ class ASTPatchEmbeddings(nn.Module):
87
+ """
88
+ This class turns `input_values` into the initial `hidden_states` (patch embeddings) of shape `(batch_size,
89
+ seq_length, hidden_size)` to be consumed by a Transformer.
90
+ """
91
+
92
+ def __init__(self, config):
93
+ super().__init__()
94
+
95
+ patch_size = config.patch_size
96
+ frequency_stride = config.frequency_stride
97
+ time_stride = config.time_stride
98
+
99
+ self.projection = nn.Conv2d(
100
+ 1, config.hidden_size, kernel_size=(patch_size, patch_size), stride=(frequency_stride, time_stride)
101
+ )
102
+
103
+ def forward(self, input_values: torch.Tensor) -> torch.Tensor:
104
+ input_values = input_values.unsqueeze(1)
105
+ input_values = input_values.transpose(2, 3)
106
+ embeddings = self.projection(input_values).flatten(2).transpose(1, 2)
107
+ return embeddings
108
+
109
+
110
+ # Copied from transformers.models.vit.modeling_vit.eager_attention_forward
111
+ def eager_attention_forward(
112
+ module: nn.Module,
113
+ query: torch.Tensor,
114
+ key: torch.Tensor,
115
+ value: torch.Tensor,
116
+ attention_mask: Optional[torch.Tensor],
117
+ scaling: float,
118
+ dropout: float = 0.0,
119
+ **kwargs,
120
+ ):
121
+ # Take the dot product between "query" and "key" to get the raw attention scores.
122
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
123
+
124
+ # Normalize the attention scores to probabilities.
125
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
126
+
127
+ # This is actually dropping out entire tokens to attend to, which might
128
+ # seem a bit unusual, but is taken from the original Transformer paper.
129
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
130
+
131
+ # Mask heads if we want to
132
+ if attention_mask is not None:
133
+ attn_weights = attn_weights * attention_mask
134
+
135
+ attn_output = torch.matmul(attn_weights, value)
136
+ attn_output = attn_output.transpose(1, 2).contiguous()
137
+
138
+ return attn_output, attn_weights
139
+
140
+
141
+ # Copied from transformers.models.vit.modeling_vit.ViTSelfAttention with ViT->AST
142
+ class ASTSelfAttention(nn.Module):
143
+ def __init__(self, config: ASTConfig) -> None:
144
+ super().__init__()
145
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
146
+ raise ValueError(
147
+ f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
148
+ f"heads {config.num_attention_heads}."
149
+ )
150
+
151
+ self.config = config
152
+ self.num_attention_heads = config.num_attention_heads
153
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
154
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
155
+ self.dropout_prob = config.attention_probs_dropout_prob
156
+ self.scaling = self.attention_head_size**-0.5
157
+ self.is_causal = False
158
+
159
+ self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
160
+ self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
161
+ self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
162
+
163
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
164
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
165
+ x = x.view(new_x_shape)
166
+ return x.permute(0, 2, 1, 3)
167
+
168
+ def forward(
169
+ self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
170
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
171
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
172
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
173
+ query_layer = self.transpose_for_scores(self.query(hidden_states))
174
+
175
+ attention_interface: Callable = eager_attention_forward
176
+ if self.config._attn_implementation != "eager":
177
+ if self.config._attn_implementation == "sdpa" and output_attentions:
178
+ logger.warning_once(
179
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
180
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
181
+ )
182
+ else:
183
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
184
+
185
+ context_layer, attention_probs = attention_interface(
186
+ self,
187
+ query_layer,
188
+ key_layer,
189
+ value_layer,
190
+ head_mask,
191
+ is_causal=self.is_causal,
192
+ scaling=self.scaling,
193
+ dropout=0.0 if not self.training else self.dropout_prob,
194
+ )
195
+
196
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
197
+ context_layer = context_layer.reshape(new_context_layer_shape)
198
+
199
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
200
+
201
+ return outputs
202
+
203
+
204
+ # Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->AST
205
+ class ASTSelfOutput(nn.Module):
206
+ """
207
+ The residual connection is defined in ASTLayer instead of here (as is the case with other models), due to the
208
+ layernorm applied before each block.
209
+ """
210
+
211
+ def __init__(self, config: ASTConfig) -> None:
212
+ super().__init__()
213
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
214
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
215
+
216
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
217
+ hidden_states = self.dense(hidden_states)
218
+ hidden_states = self.dropout(hidden_states)
219
+
220
+ return hidden_states
221
+
222
+
223
+ # Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->AST
224
+ class ASTAttention(nn.Module):
225
+ def __init__(self, config: ASTConfig) -> None:
226
+ super().__init__()
227
+ self.attention = ASTSelfAttention(config)
228
+ self.output = ASTSelfOutput(config)
229
+ self.pruned_heads = set()
230
+
231
+ def prune_heads(self, heads: Set[int]) -> None:
232
+ if len(heads) == 0:
233
+ return
234
+ heads, index = find_pruneable_heads_and_indices(
235
+ heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
236
+ )
237
+
238
+ # Prune linear layers
239
+ self.attention.query = prune_linear_layer(self.attention.query, index)
240
+ self.attention.key = prune_linear_layer(self.attention.key, index)
241
+ self.attention.value = prune_linear_layer(self.attention.value, index)
242
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
243
+
244
+ # Update hyper params and store pruned heads
245
+ self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
246
+ self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
247
+ self.pruned_heads = self.pruned_heads.union(heads)
248
+
249
+ def forward(
250
+ self,
251
+ hidden_states: torch.Tensor,
252
+ head_mask: Optional[torch.Tensor] = None,
253
+ output_attentions: bool = False,
254
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
255
+ self_outputs = self.attention(hidden_states, head_mask, output_attentions)
256
+
257
+ attention_output = self.output(self_outputs[0], hidden_states)
258
+
259
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
260
+ return outputs
261
+
262
+
263
+ # Copied from transformers.models.vit.modeling_vit.ViTIntermediate with ViT->AST
264
+ class ASTIntermediate(nn.Module):
265
+ def __init__(self, config: ASTConfig) -> None:
266
+ super().__init__()
267
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
268
+ if isinstance(config.hidden_act, str):
269
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
270
+ else:
271
+ self.intermediate_act_fn = config.hidden_act
272
+
273
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
274
+ hidden_states = self.dense(hidden_states)
275
+ hidden_states = self.intermediate_act_fn(hidden_states)
276
+
277
+ return hidden_states
278
+
279
+
280
+ # Copied from transformers.models.vit.modeling_vit.ViTOutput with ViT->AST
281
+ class ASTOutput(nn.Module):
282
+ def __init__(self, config: ASTConfig) -> None:
283
+ super().__init__()
284
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
285
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
286
+
287
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
288
+ hidden_states = self.dense(hidden_states)
289
+ hidden_states = self.dropout(hidden_states)
290
+
291
+ hidden_states = hidden_states + input_tensor
292
+
293
+ return hidden_states
294
+
295
+
296
+ # Copied from transformers.models.vit.modeling_vit.ViTLayer with ViT->AST,VIT->AST
297
+ class ASTLayer(nn.Module):
298
+ """This corresponds to the Block class in the timm implementation."""
299
+
300
+ def __init__(self, config: ASTConfig) -> None:
301
+ super().__init__()
302
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
303
+ self.seq_len_dim = 1
304
+ self.attention = ASTAttention(config)
305
+ self.intermediate = ASTIntermediate(config)
306
+ self.output = ASTOutput(config)
307
+ self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
308
+ self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
309
+
310
+ def forward(
311
+ self,
312
+ hidden_states: torch.Tensor,
313
+ head_mask: Optional[torch.Tensor] = None,
314
+ output_attentions: bool = False,
315
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
316
+ self_attention_outputs = self.attention(
317
+ self.layernorm_before(hidden_states), # in AST, layernorm is applied before self-attention
318
+ head_mask,
319
+ output_attentions=output_attentions,
320
+ )
321
+ attention_output = self_attention_outputs[0]
322
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
323
+
324
+ # first residual connection
325
+ hidden_states = attention_output + hidden_states
326
+
327
+ # in AST, layernorm is also applied after self-attention
328
+ layer_output = self.layernorm_after(hidden_states)
329
+ layer_output = self.intermediate(layer_output)
330
+
331
+ # second residual connection is done here
332
+ layer_output = self.output(layer_output, hidden_states)
333
+
334
+ outputs = (layer_output,) + outputs
335
+
336
+ return outputs
337
+
338
+
339
+ # Copied from transformers.models.vit.modeling_vit.ViTEncoder with ViT->AST
340
+ class ASTEncoder(nn.Module):
341
+ def __init__(self, config: ASTConfig) -> None:
342
+ super().__init__()
343
+ self.config = config
344
+ self.layer = nn.ModuleList([ASTLayer(config) for _ in range(config.num_hidden_layers)])
345
+ self.gradient_checkpointing = False
346
+
347
+ def forward(
348
+ self,
349
+ hidden_states: torch.Tensor,
350
+ head_mask: Optional[torch.Tensor] = None,
351
+ output_attentions: bool = False,
352
+ output_hidden_states: bool = False,
353
+ return_dict: bool = True,
354
+ ) -> Union[tuple, BaseModelOutput]:
355
+ all_hidden_states = () if output_hidden_states else None
356
+ all_self_attentions = () if output_attentions else None
357
+
358
+ for i, layer_module in enumerate(self.layer):
359
+ if output_hidden_states:
360
+ all_hidden_states = all_hidden_states + (hidden_states,)
361
+
362
+ layer_head_mask = head_mask[i] if head_mask is not None else None
363
+
364
+ if self.gradient_checkpointing and self.training:
365
+ layer_outputs = self._gradient_checkpointing_func(
366
+ layer_module.__call__,
367
+ hidden_states,
368
+ layer_head_mask,
369
+ output_attentions,
370
+ )
371
+ else:
372
+ layer_outputs = layer_module(hidden_states, layer_head_mask, output_attentions)
373
+
374
+ hidden_states = layer_outputs[0]
375
+
376
+ if output_attentions:
377
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
378
+
379
+ if output_hidden_states:
380
+ all_hidden_states = all_hidden_states + (hidden_states,)
381
+
382
+ if not return_dict:
383
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
384
+ return BaseModelOutput(
385
+ last_hidden_state=hidden_states,
386
+ hidden_states=all_hidden_states,
387
+ attentions=all_self_attentions,
388
+ )
389
+
390
+
391
+ class ASTPreTrainedModel(PreTrainedModel):
392
+ """
393
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
394
+ models.
395
+ """
396
+
397
+ config_class = ASTConfig
398
+ base_model_prefix = "audio_spectrogram_transformer"
399
+ main_input_name = "input_values"
400
+ supports_gradient_checkpointing = True
401
+ _supports_sdpa = True
402
+ _supports_flash_attn_2 = True
403
+
404
+ def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
405
+ """Initialize the weights"""
406
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
407
+ # Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
408
+ # `trunc_normal_cpu` not implemented in `half` issues
409
+ module.weight.data = nn.init.trunc_normal_(
410
+ module.weight.data.to(torch.float32), mean=0.0, std=self.config.initializer_range
411
+ ).to(module.weight.dtype)
412
+ if module.bias is not None:
413
+ module.bias.data.zero_()
414
+ elif isinstance(module, nn.LayerNorm):
415
+ module.bias.data.zero_()
416
+ module.weight.data.fill_(1.0)
417
+ elif isinstance(module, ASTEmbeddings):
418
+ module.cls_token.data.zero_()
419
+ module.position_embeddings.data.zero_()
420
+ module.distillation_token.data.zero_()
421
+
422
+
423
+ AUDIO_SPECTROGRAM_TRANSFORMER_START_DOCSTRING = r"""
424
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
425
+ as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
426
+ behavior.
427
+
428
+ Parameters:
429
+ config ([`ASTConfig`]):
430
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
431
+ load the weights associated with the model, only the configuration. Check out the
432
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
433
+ """
434
+
435
+ AUDIO_SPECTROGRAM_TRANSFORMER_INPUTS_DOCSTRING = r"""
436
+ Args:
437
+ input_values (`torch.FloatTensor` of shape `(batch_size, max_length, num_mel_bins)`):
438
+ Float values mel features extracted from the raw audio waveform. Raw audio waveform can be obtained by
439
+ loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via
440
+ the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the
441
+ [`AutoFeatureExtractor`] should be used for extracting the mel features, padding and conversion into a
442
+ tensor of type `torch.FloatTensor`. See [`~ASTFeatureExtractor.__call__`]
443
+
444
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
445
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
446
+
447
+ - 1 indicates the head is **not masked**,
448
+ - 0 indicates the head is **masked**.
449
+
450
+ output_attentions (`bool`, *optional*):
451
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
452
+ tensors for more detail.
453
+ output_hidden_states (`bool`, *optional*):
454
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
455
+ more detail.
456
+ return_dict (`bool`, *optional*):
457
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
458
+ """
459
+
460
+
461
+ @add_start_docstrings(
462
+ "The bare AST Model transformer outputting raw hidden-states without any specific head on top.",
463
+ AUDIO_SPECTROGRAM_TRANSFORMER_START_DOCSTRING,
464
+ )
465
+ class ASTModel(ASTPreTrainedModel):
466
+ def __init__(self, config: ASTConfig) -> None:
467
+ super().__init__(config)
468
+ self.config = config
469
+
470
+ self.embeddings = ASTEmbeddings(config)
471
+ self.encoder = ASTEncoder(config)
472
+
473
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
474
+
475
+ # Initialize weights and apply final processing
476
+ self.post_init()
477
+
478
+ def get_input_embeddings(self) -> ASTPatchEmbeddings:
479
+ return self.embeddings.patch_embeddings
480
+
481
+ def _prune_heads(self, heads_to_prune: Dict[int, List[int]]) -> None:
482
+ """
483
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
484
+ class PreTrainedModel
485
+ """
486
+ for layer, heads in heads_to_prune.items():
487
+ self.encoder.layer[layer].attention.prune_heads(heads)
488
+
489
+ @add_start_docstrings_to_model_forward(AUDIO_SPECTROGRAM_TRANSFORMER_INPUTS_DOCSTRING)
490
+ @add_code_sample_docstrings(
491
+ checkpoint=_CHECKPOINT_FOR_DOC,
492
+ output_type=BaseModelOutputWithPooling,
493
+ config_class=_CONFIG_FOR_DOC,
494
+ modality="audio",
495
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
496
+ )
497
+ def forward(
498
+ self,
499
+ input_values: Optional[torch.Tensor] = None,
500
+ head_mask: Optional[torch.Tensor] = None,
501
+ output_attentions: Optional[bool] = None,
502
+ output_hidden_states: Optional[bool] = None,
503
+ return_dict: Optional[bool] = None,
504
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
505
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
506
+ output_hidden_states = (
507
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
508
+ )
509
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
510
+
511
+ if input_values is None:
512
+ raise ValueError("You have to specify input_values")
513
+
514
+ # Prepare head mask if needed
515
+ # 1.0 in head_mask indicate we keep the head
516
+ # attention_probs has shape bsz x n_heads x N x N
517
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
518
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
519
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
520
+
521
+ embedding_output = self.embeddings(input_values)
522
+
523
+ encoder_outputs = self.encoder(
524
+ embedding_output,
525
+ head_mask=head_mask,
526
+ output_attentions=output_attentions,
527
+ output_hidden_states=output_hidden_states,
528
+ return_dict=return_dict,
529
+ )
530
+ sequence_output = encoder_outputs[0]
531
+ sequence_output = self.layernorm(sequence_output)
532
+
533
+ pooled_output = (sequence_output[:, 0] + sequence_output[:, 1]) / 2
534
+
535
+ if not return_dict:
536
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
537
+
538
+ return BaseModelOutputWithPooling(
539
+ last_hidden_state=sequence_output,
540
+ pooler_output=pooled_output,
541
+ hidden_states=encoder_outputs.hidden_states,
542
+ attentions=encoder_outputs.attentions,
543
+ )
544
+
545
+
546
+ class ASTMLPHead(nn.Module):
547
+ def __init__(self, config: ASTConfig):
548
+ super().__init__()
549
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
550
+ self.dense = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
551
+
552
+ def forward(self, hidden_state):
553
+ hidden_state = self.layernorm(hidden_state)
554
+ hidden_state = self.dense(hidden_state)
555
+ return hidden_state
556
+
557
+
558
+ @add_start_docstrings(
559
+ """
560
+ Audio Spectrogram Transformer model with an audio classification head on top (a linear layer on top of the pooled
561
+ output) e.g. for datasets like AudioSet, Speech Commands v2.
562
+ """,
563
+ AUDIO_SPECTROGRAM_TRANSFORMER_START_DOCSTRING,
564
+ )
565
+ class ASTForAudioClassification(ASTPreTrainedModel):
566
+ def __init__(self, config: ASTConfig) -> None:
567
+ super().__init__(config)
568
+
569
+ self.num_labels = config.num_labels
570
+ self.audio_spectrogram_transformer = ASTModel(config)
571
+
572
+ # Classifier head
573
+ self.classifier = ASTMLPHead(config)
574
+
575
+ # Initialize weights and apply final processing
576
+ self.post_init()
577
+
578
+ @add_start_docstrings_to_model_forward(AUDIO_SPECTROGRAM_TRANSFORMER_INPUTS_DOCSTRING)
579
+ @add_code_sample_docstrings(
580
+ checkpoint=_SEQ_CLASS_CHECKPOINT,
581
+ output_type=SequenceClassifierOutput,
582
+ config_class=_CONFIG_FOR_DOC,
583
+ modality="audio",
584
+ expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,
585
+ expected_loss=_SEQ_CLASS_EXPECTED_LOSS,
586
+ )
587
+ def forward(
588
+ self,
589
+ input_values: Optional[torch.Tensor] = None,
590
+ head_mask: Optional[torch.Tensor] = None,
591
+ labels: Optional[torch.Tensor] = None,
592
+ output_attentions: Optional[bool] = None,
593
+ output_hidden_states: Optional[bool] = None,
594
+ return_dict: Optional[bool] = None,
595
+ ) -> Union[tuple, SequenceClassifierOutput]:
596
+ r"""
597
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
598
+ Labels for computing the audio classification/regression loss. Indices should be in `[0, ...,
599
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
600
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
601
+ """
602
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
603
+
604
+ outputs = self.audio_spectrogram_transformer(
605
+ input_values,
606
+ head_mask=head_mask,
607
+ output_attentions=output_attentions,
608
+ output_hidden_states=output_hidden_states,
609
+ return_dict=return_dict,
610
+ )
611
+
612
+ pooled_output = outputs[1]
613
+ logits = self.classifier(pooled_output)
614
+
615
+ loss = None
616
+ if labels is not None:
617
+ if self.config.problem_type is None:
618
+ if self.num_labels == 1:
619
+ self.config.problem_type = "regression"
620
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
621
+ self.config.problem_type = "single_label_classification"
622
+ else:
623
+ self.config.problem_type = "multi_label_classification"
624
+
625
+ if self.config.problem_type == "regression":
626
+ loss_fct = MSELoss()
627
+ if self.num_labels == 1:
628
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
629
+ else:
630
+ loss = loss_fct(logits, labels)
631
+ elif self.config.problem_type == "single_label_classification":
632
+ loss_fct = CrossEntropyLoss()
633
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
634
+ elif self.config.problem_type == "multi_label_classification":
635
+ loss_fct = BCEWithLogitsLoss()
636
+ loss = loss_fct(logits, labels)
637
+
638
+ if not return_dict:
639
+ output = (logits,) + outputs[2:]
640
+ return ((loss,) + output) if loss is not None else output
641
+
642
+ return SequenceClassifierOutput(
643
+ loss=loss,
644
+ logits=logits,
645
+ hidden_states=outputs.hidden_states,
646
+ attentions=outputs.attentions,
647
+ )
648
+
649
+
650
+ __all__ = ["ASTForAudioClassification", "ASTModel", "ASTPreTrainedModel"]
lib/python3.12/site-packages/transformers/models/bart/__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_bart import *
22
+ from .modeling_bart import *
23
+ from .modeling_flax_bart import *
24
+ from .modeling_tf_bart import *
25
+ from .tokenization_bart import *
26
+ from .tokenization_bart_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__)
lib/python3.12/site-packages/transformers/models/bart/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (794 Bytes). View file
 
lib/python3.12/site-packages/transformers/models/bart/__pycache__/configuration_bart.cpython-312.pyc ADDED
Binary file (16.6 kB). View file
 
lib/python3.12/site-packages/transformers/models/bart/__pycache__/modeling_flax_bart.cpython-312.pyc ADDED
Binary file (85.8 kB). View file
 
lib/python3.12/site-packages/transformers/models/bart/__pycache__/modeling_tf_bart.cpython-312.pyc ADDED
Binary file (84.3 kB). View file
 
lib/python3.12/site-packages/transformers/models/bart/__pycache__/tokenization_bart.cpython-312.pyc ADDED
Binary file (20.2 kB). View file
 
lib/python3.12/site-packages/transformers/models/bart/__pycache__/tokenization_bart_fast.cpython-312.pyc ADDED
Binary file (11.4 kB). View file
 
lib/python3.12/site-packages/transformers/models/bart/configuration_bart.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Fairseq 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
+ """BART model configuration"""
16
+
17
+ import warnings
18
+ from collections import OrderedDict
19
+ from typing import Any, Mapping, Optional
20
+
21
+ from ... import PreTrainedTokenizer
22
+ from ...configuration_utils import PretrainedConfig
23
+ from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeq2SeqConfigWithPast
24
+ from ...onnx.utils import compute_effective_axis_dimension
25
+ from ...utils import TensorType, is_torch_available, logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+
31
+ class BartConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`BartModel`]. It is used to instantiate a BART
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the BART
36
+ [facebook/bart-large](https://huggingface.co/facebook/bart-large) architecture.
37
+
38
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
39
+ documentation from [`PretrainedConfig`] for more information.
40
+
41
+
42
+ Args:
43
+ vocab_size (`int`, *optional*, defaults to 50265):
44
+ Vocabulary size of the BART model. Defines the number of different tokens that can be represented by the
45
+ `inputs_ids` passed when calling [`BartModel`] or [`TFBartModel`].
46
+ d_model (`int`, *optional*, defaults to 1024):
47
+ Dimensionality of the layers and the pooler layer.
48
+ encoder_layers (`int`, *optional*, defaults to 12):
49
+ Number of encoder layers.
50
+ decoder_layers (`int`, *optional*, defaults to 12):
51
+ Number of decoder layers.
52
+ encoder_attention_heads (`int`, *optional*, defaults to 16):
53
+ Number of attention heads for each attention layer in the Transformer encoder.
54
+ decoder_attention_heads (`int`, *optional*, defaults to 16):
55
+ Number of attention heads for each attention layer in the Transformer decoder.
56
+ decoder_ffn_dim (`int`, *optional*, defaults to 4096):
57
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
58
+ encoder_ffn_dim (`int`, *optional*, defaults to 4096):
59
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
60
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
61
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
62
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
63
+ dropout (`float`, *optional*, defaults to 0.1):
64
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
65
+ attention_dropout (`float`, *optional*, defaults to 0.0):
66
+ The dropout ratio for the attention probabilities.
67
+ activation_dropout (`float`, *optional*, defaults to 0.0):
68
+ The dropout ratio for activations inside the fully connected layer.
69
+ classifier_dropout (`float`, *optional*, defaults to 0.0):
70
+ The dropout ratio for classifier.
71
+ max_position_embeddings (`int`, *optional*, defaults to 1024):
72
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
73
+ just in case (e.g., 512 or 1024 or 2048).
74
+ init_std (`float`, *optional*, defaults to 0.02):
75
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
76
+ encoder_layerdrop (`float`, *optional*, defaults to 0.0):
77
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
78
+ for more details.
79
+ decoder_layerdrop (`float`, *optional*, defaults to 0.0):
80
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
81
+ for more details.
82
+ scale_embedding (`bool`, *optional*, defaults to `False`):
83
+ Scale embeddings by diving by sqrt(d_model).
84
+ use_cache (`bool`, *optional*, defaults to `True`):
85
+ Whether or not the model should return the last key/values attentions (not used by all models).
86
+ num_labels (`int`, *optional*, defaults to 3):
87
+ The number of labels to use in [`BartForSequenceClassification`].
88
+ forced_eos_token_id (`int`, *optional*, defaults to 2):
89
+ The id of the token to force as the last generated token when `max_length` is reached. Usually set to
90
+ `eos_token_id`.
91
+
92
+ Example:
93
+
94
+ ```python
95
+ >>> from transformers import BartConfig, BartModel
96
+
97
+ >>> # Initializing a BART facebook/bart-large style configuration
98
+ >>> configuration = BartConfig()
99
+
100
+ >>> # Initializing a model (with random weights) from the facebook/bart-large style configuration
101
+ >>> model = BartModel(configuration)
102
+
103
+ >>> # Accessing the model configuration
104
+ >>> configuration = model.config
105
+ ```"""
106
+
107
+ model_type = "bart"
108
+ keys_to_ignore_at_inference = ["past_key_values"]
109
+ attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
110
+
111
+ def __init__(
112
+ self,
113
+ vocab_size=50265,
114
+ max_position_embeddings=1024,
115
+ encoder_layers=12,
116
+ encoder_ffn_dim=4096,
117
+ encoder_attention_heads=16,
118
+ decoder_layers=12,
119
+ decoder_ffn_dim=4096,
120
+ decoder_attention_heads=16,
121
+ encoder_layerdrop=0.0,
122
+ decoder_layerdrop=0.0,
123
+ activation_function="gelu",
124
+ d_model=1024,
125
+ dropout=0.1,
126
+ attention_dropout=0.0,
127
+ activation_dropout=0.0,
128
+ init_std=0.02,
129
+ classifier_dropout=0.0,
130
+ scale_embedding=False,
131
+ use_cache=True,
132
+ num_labels=3,
133
+ pad_token_id=1,
134
+ bos_token_id=0,
135
+ eos_token_id=2,
136
+ is_encoder_decoder=True,
137
+ decoder_start_token_id=2,
138
+ forced_eos_token_id=2,
139
+ **kwargs,
140
+ ):
141
+ self.vocab_size = vocab_size
142
+ self.max_position_embeddings = max_position_embeddings
143
+ self.d_model = d_model
144
+ self.encoder_ffn_dim = encoder_ffn_dim
145
+ self.encoder_layers = encoder_layers
146
+ self.encoder_attention_heads = encoder_attention_heads
147
+ self.decoder_ffn_dim = decoder_ffn_dim
148
+ self.decoder_layers = decoder_layers
149
+ self.decoder_attention_heads = decoder_attention_heads
150
+ self.dropout = dropout
151
+ self.attention_dropout = attention_dropout
152
+ self.activation_dropout = activation_dropout
153
+ self.activation_function = activation_function
154
+ self.init_std = init_std
155
+ self.encoder_layerdrop = encoder_layerdrop
156
+ self.decoder_layerdrop = decoder_layerdrop
157
+ self.classifier_dropout = classifier_dropout
158
+ self.use_cache = use_cache
159
+ self.num_hidden_layers = encoder_layers
160
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
161
+
162
+ super().__init__(
163
+ num_labels=num_labels,
164
+ pad_token_id=pad_token_id,
165
+ bos_token_id=bos_token_id,
166
+ eos_token_id=eos_token_id,
167
+ is_encoder_decoder=is_encoder_decoder,
168
+ decoder_start_token_id=decoder_start_token_id,
169
+ forced_eos_token_id=forced_eos_token_id,
170
+ **kwargs,
171
+ )
172
+
173
+ # ensure backward compatibility for BART CNN models
174
+ if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated", False):
175
+ self.forced_bos_token_id = self.bos_token_id
176
+ warnings.warn(
177
+ f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. "
178
+ "The config can simply be saved and uploaded again to be fixed."
179
+ )
180
+
181
+
182
+ class BartOnnxConfig(OnnxSeq2SeqConfigWithPast):
183
+ @property
184
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
185
+ if self.task in ["default", "seq2seq-lm"]:
186
+ common_inputs = OrderedDict(
187
+ [
188
+ ("input_ids", {0: "batch", 1: "encoder_sequence"}),
189
+ ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
190
+ ]
191
+ )
192
+
193
+ if self.use_past:
194
+ common_inputs["decoder_input_ids"] = {0: "batch"}
195
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
196
+ else:
197
+ common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
198
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"}
199
+
200
+ if self.use_past:
201
+ self.fill_with_past_key_values_(common_inputs, direction="inputs")
202
+ elif self.task == "causal-lm":
203
+ # TODO: figure this case out.
204
+ common_inputs = OrderedDict(
205
+ [
206
+ ("input_ids", {0: "batch", 1: "encoder_sequence"}),
207
+ ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
208
+ ]
209
+ )
210
+ if self.use_past:
211
+ num_encoder_layers, _ = self.num_layers
212
+ for i in range(num_encoder_layers):
213
+ common_inputs[f"past_key_values.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
214
+ common_inputs[f"past_key_values.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
215
+ else:
216
+ common_inputs = OrderedDict(
217
+ [
218
+ ("input_ids", {0: "batch", 1: "encoder_sequence"}),
219
+ ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
220
+ ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}),
221
+ ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}),
222
+ ]
223
+ )
224
+
225
+ return common_inputs
226
+
227
+ @property
228
+ def outputs(self) -> Mapping[str, Mapping[int, str]]:
229
+ if self.task in ["default", "seq2seq-lm"]:
230
+ common_outputs = super().outputs
231
+ else:
232
+ common_outputs = super(OnnxConfigWithPast, self).outputs
233
+ if self.use_past:
234
+ num_encoder_layers, _ = self.num_layers
235
+ for i in range(num_encoder_layers):
236
+ common_outputs[f"present.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
237
+ common_outputs[f"present.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
238
+ return common_outputs
239
+
240
+ def _generate_dummy_inputs_for_default_and_seq2seq_lm(
241
+ self,
242
+ tokenizer: PreTrainedTokenizer,
243
+ batch_size: int = -1,
244
+ seq_length: int = -1,
245
+ is_pair: bool = False,
246
+ framework: Optional[TensorType] = None,
247
+ ) -> Mapping[str, Any]:
248
+ encoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
249
+ tokenizer, batch_size, seq_length, is_pair, framework
250
+ )
251
+
252
+ # Generate decoder inputs
253
+ decoder_seq_length = seq_length if not self.use_past else 1
254
+ decoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
255
+ tokenizer, batch_size, decoder_seq_length, is_pair, framework
256
+ )
257
+ decoder_inputs = {f"decoder_{name}": tensor for name, tensor in decoder_inputs.items()}
258
+ common_inputs = dict(**encoder_inputs, **decoder_inputs)
259
+
260
+ if self.use_past:
261
+ if not is_torch_available():
262
+ raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
263
+ else:
264
+ import torch
265
+ batch, encoder_seq_length = common_inputs["input_ids"].shape
266
+ decoder_seq_length = common_inputs["decoder_input_ids"].shape[1]
267
+ num_encoder_attention_heads, num_decoder_attention_heads = self.num_attention_heads
268
+ encoder_shape = (
269
+ batch,
270
+ num_encoder_attention_heads,
271
+ encoder_seq_length,
272
+ self._config.hidden_size // num_encoder_attention_heads,
273
+ )
274
+ decoder_past_length = decoder_seq_length + 3
275
+ decoder_shape = (
276
+ batch,
277
+ num_decoder_attention_heads,
278
+ decoder_past_length,
279
+ self._config.hidden_size // num_decoder_attention_heads,
280
+ )
281
+
282
+ common_inputs["decoder_attention_mask"] = torch.cat(
283
+ [common_inputs["decoder_attention_mask"], torch.ones(batch, decoder_past_length)], dim=1
284
+ )
285
+
286
+ common_inputs["past_key_values"] = []
287
+ # If the number of encoder and decoder layers are present in the model configuration, both are considered
288
+ num_encoder_layers, num_decoder_layers = self.num_layers
289
+ min_num_layers = min(num_encoder_layers, num_decoder_layers)
290
+ max_num_layers = max(num_encoder_layers, num_decoder_layers) - min_num_layers
291
+ remaining_side_name = "encoder" if num_encoder_layers > num_decoder_layers else "decoder"
292
+
293
+ for _ in range(min_num_layers):
294
+ common_inputs["past_key_values"].append(
295
+ (
296
+ torch.zeros(decoder_shape),
297
+ torch.zeros(decoder_shape),
298
+ torch.zeros(encoder_shape),
299
+ torch.zeros(encoder_shape),
300
+ )
301
+ )
302
+ # TODO: test this.
303
+ shape = encoder_shape if remaining_side_name == "encoder" else decoder_shape
304
+ for _ in range(min_num_layers, max_num_layers):
305
+ common_inputs["past_key_values"].append((torch.zeros(shape), torch.zeros(shape)))
306
+ return common_inputs
307
+
308
+ def _generate_dummy_inputs_for_causal_lm(
309
+ self,
310
+ tokenizer: PreTrainedTokenizer,
311
+ batch_size: int = -1,
312
+ seq_length: int = -1,
313
+ is_pair: bool = False,
314
+ framework: Optional[TensorType] = None,
315
+ ) -> Mapping[str, Any]:
316
+ common_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
317
+ tokenizer, batch_size, seq_length, is_pair, framework
318
+ )
319
+
320
+ if self.use_past:
321
+ if not is_torch_available():
322
+ raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
323
+ else:
324
+ import torch
325
+ batch, seqlen = common_inputs["input_ids"].shape
326
+ # Not using the same length for past_key_values
327
+ past_key_values_length = seqlen + 2
328
+ num_encoder_layers, _ = self.num_layers
329
+ num_encoder_attention_heads, _ = self.num_attention_heads
330
+ past_shape = (
331
+ batch,
332
+ num_encoder_attention_heads,
333
+ past_key_values_length,
334
+ self._config.hidden_size // num_encoder_attention_heads,
335
+ )
336
+
337
+ mask_dtype = common_inputs["attention_mask"].dtype
338
+ common_inputs["attention_mask"] = torch.cat(
339
+ [common_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
340
+ )
341
+ common_inputs["past_key_values"] = [
342
+ (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(num_encoder_layers)
343
+ ]
344
+ return common_inputs
345
+
346
+ def _generate_dummy_inputs_for_sequence_classification_and_question_answering(
347
+ self,
348
+ tokenizer: PreTrainedTokenizer,
349
+ batch_size: int = -1,
350
+ seq_length: int = -1,
351
+ is_pair: bool = False,
352
+ framework: Optional[TensorType] = None,
353
+ ) -> Mapping[str, Any]:
354
+ # Copied from OnnxConfig.generate_dummy_inputs
355
+ # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
356
+ # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
357
+ batch_size = compute_effective_axis_dimension(
358
+ batch_size, fixed_dimension=OnnxConfig.default_fixed_batch, num_token_to_add=0
359
+ )
360
+
361
+ # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
362
+ token_to_add = tokenizer.num_special_tokens_to_add(is_pair)
363
+ seq_length = compute_effective_axis_dimension(
364
+ seq_length, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=token_to_add
365
+ )
366
+
367
+ # Generate dummy inputs according to compute batch and sequence
368
+ dummy_input = [" ".join([tokenizer.unk_token]) * seq_length] * batch_size
369
+ common_inputs = dict(tokenizer(dummy_input, return_tensors=framework))
370
+ return common_inputs
371
+
372
+ def generate_dummy_inputs(
373
+ self,
374
+ tokenizer: PreTrainedTokenizer,
375
+ batch_size: int = -1,
376
+ seq_length: int = -1,
377
+ is_pair: bool = False,
378
+ framework: Optional[TensorType] = None,
379
+ ) -> Mapping[str, Any]:
380
+ if self.task in ["default", "seq2seq-lm"]:
381
+ common_inputs = self._generate_dummy_inputs_for_default_and_seq2seq_lm(
382
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
383
+ )
384
+
385
+ elif self.task == "causal-lm":
386
+ common_inputs = self._generate_dummy_inputs_for_causal_lm(
387
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
388
+ )
389
+ else:
390
+ common_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
391
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
392
+ )
393
+
394
+ return common_inputs
395
+
396
+ def _flatten_past_key_values_(self, flattened_output, name, idx, t):
397
+ if self.task in ["default", "seq2seq-lm"]:
398
+ flattened_output = super()._flatten_past_key_values_(flattened_output, name, idx, t)
399
+ else:
400
+ flattened_output = super(OnnxSeq2SeqConfigWithPast, self)._flatten_past_key_values_(
401
+ flattened_output, name, idx, t
402
+ )
403
+
404
+
405
+ __all__ = ["BartConfig", "BartOnnxConfig"]
lib/python3.12/site-packages/transformers/models/bart/modeling_bart.py ADDED
The diff for this file is too large to render. See raw diff
 
lib/python3.12/site-packages/transformers/models/bart/modeling_flax_bart.py ADDED
@@ -0,0 +1,2006 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Fairseq Authors and The Google Flax Team 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
+ """Flax Bart model."""
16
+
17
+ import math
18
+ import random
19
+ from functools import partial
20
+ from typing import Callable, Optional, Tuple
21
+
22
+ import flax.linen as nn
23
+ import jax
24
+ import jax.numpy as jnp
25
+ from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
26
+ from flax.linen import combine_masks, make_causal_mask
27
+ from flax.linen.attention import dot_product_attention_weights
28
+ from flax.traverse_util import flatten_dict, unflatten_dict
29
+ from jax import lax
30
+ from jax.random import PRNGKey
31
+
32
+ from ...modeling_flax_outputs import (
33
+ FlaxBaseModelOutput,
34
+ FlaxBaseModelOutputWithPastAndCrossAttentions,
35
+ FlaxCausalLMOutputWithCrossAttentions,
36
+ FlaxSeq2SeqLMOutput,
37
+ FlaxSeq2SeqModelOutput,
38
+ FlaxSeq2SeqQuestionAnsweringModelOutput,
39
+ FlaxSeq2SeqSequenceClassifierOutput,
40
+ )
41
+ from ...modeling_flax_utils import (
42
+ ACT2FN,
43
+ FlaxPreTrainedModel,
44
+ append_call_sample_docstring,
45
+ append_replace_return_docstrings,
46
+ overwrite_call_docstring,
47
+ )
48
+ from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
49
+ from .configuration_bart import BartConfig
50
+
51
+
52
+ logger = logging.get_logger(__name__)
53
+
54
+ _CHECKPOINT_FOR_DOC = "facebook/bart-base"
55
+ _CONFIG_FOR_DOC = "BartConfig"
56
+
57
+
58
+ BART_START_DOCSTRING = r"""
59
+ This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
60
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
61
+ etc.)
62
+
63
+ This model is also a Flax Linen
64
+ [flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
65
+ regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
66
+
67
+ Finally, this model supports inherent JAX features such as:
68
+
69
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
70
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
71
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
72
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
73
+
74
+ Parameters:
75
+ config ([`BartConfig`]): Model configuration class with all the parameters of the model.
76
+ Initializing with a config file does not load the weights associated with the model, only the
77
+ configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
78
+ dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
79
+ The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
80
+ `jax.numpy.bfloat16` (on TPUs).
81
+
82
+ This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
83
+ specified all the computation will be performed with the given `dtype`.
84
+
85
+ **Note that this only specifies the dtype of the computation and does not influence the dtype of model
86
+ parameters.**
87
+
88
+ If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
89
+ [`~FlaxPreTrainedModel.to_bf16`].
90
+ """
91
+
92
+ BART_INPUTS_DOCSTRING = r"""
93
+ Args:
94
+ input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
95
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
96
+ it.
97
+
98
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
99
+ [`PreTrainedTokenizer.__call__`] for details.
100
+
101
+ [What are input IDs?](../glossary#input-ids)
102
+ attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
103
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
104
+
105
+ - 1 for tokens that are **not masked**,
106
+ - 0 for tokens that are **masked**.
107
+
108
+ [What are attention masks?](../glossary#attention-mask)
109
+ decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
110
+ Indices of decoder input sequence tokens in the vocabulary.
111
+
112
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
113
+ [`PreTrainedTokenizer.__call__`] for details.
114
+
115
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
116
+
117
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
118
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
119
+ for denoising pre-training following the paper.
120
+ decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
121
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
122
+ be used by default.
123
+
124
+ If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
125
+ paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
126
+ position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
127
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
128
+ config.max_position_embeddings - 1]`.
129
+ decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
130
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
131
+ range `[0, config.max_position_embeddings - 1]`.
132
+ output_attentions (`bool`, *optional*):
133
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
134
+ tensors for more detail.
135
+ output_hidden_states (`bool`, *optional*):
136
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
137
+ more detail.
138
+ return_dict (`bool`, *optional*):
139
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
140
+ """
141
+
142
+
143
+ BART_ENCODE_INPUTS_DOCSTRING = r"""
144
+ Args:
145
+ input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
146
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
147
+ it.
148
+
149
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
150
+ [`PreTrainedTokenizer.__call__`] for details.
151
+
152
+ [What are input IDs?](../glossary#input-ids)
153
+ attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
154
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
155
+
156
+ - 1 for tokens that are **not masked**,
157
+ - 0 for tokens that are **masked**.
158
+
159
+ [What are attention masks?](../glossary#attention-mask)
160
+ position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
161
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
162
+ config.max_position_embeddings - 1]`.
163
+ output_attentions (`bool`, *optional*):
164
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
165
+ tensors for more detail.
166
+ output_hidden_states (`bool`, *optional*):
167
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
168
+ more detail.
169
+ return_dict (`bool`, *optional*):
170
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
171
+ """
172
+
173
+ BART_DECODE_INPUTS_DOCSTRING = r"""
174
+ Args:
175
+ decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`):
176
+ Indices of decoder input sequence tokens in the vocabulary.
177
+
178
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
179
+ [`PreTrainedTokenizer.__call__`] for details.
180
+
181
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
182
+
183
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
184
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
185
+ for denoising pre-training following the paper.
186
+ encoder_outputs (`tuple(tuple(jnp.ndarray)`):
187
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
188
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
189
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
190
+ encoder_attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
191
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
192
+
193
+ - 1 for tokens that are **not masked**,
194
+ - 0 for tokens that are **masked**.
195
+
196
+ [What are attention masks?](../glossary#attention-mask)
197
+ decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
198
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
199
+ be used by default.
200
+
201
+ If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
202
+ paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
203
+ decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
204
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
205
+ range `[0, config.max_position_embeddings - 1]`.
206
+ past_key_values (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
207
+ Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
208
+ auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
209
+ output_attentions (`bool`, *optional*):
210
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
211
+ tensors for more detail.
212
+ output_hidden_states (`bool`, *optional*):
213
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
214
+ more detail.
215
+ return_dict (`bool`, *optional*):
216
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
217
+ """
218
+
219
+
220
+ def shift_tokens_right(input_ids: jnp.ndarray, pad_token_id: int, decoder_start_token_id: int) -> jnp.ndarray:
221
+ """
222
+ Shift input ids one token to the right.
223
+ """
224
+ shifted_input_ids = jnp.zeros_like(input_ids)
225
+ shifted_input_ids = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1])
226
+ shifted_input_ids = shifted_input_ids.at[:, 0].set(decoder_start_token_id)
227
+
228
+ shifted_input_ids = jnp.where(shifted_input_ids == -100, pad_token_id, shifted_input_ids)
229
+ return shifted_input_ids
230
+
231
+
232
+ class FlaxBartAttention(nn.Module):
233
+ config: BartConfig
234
+ embed_dim: int
235
+ num_heads: int
236
+ dropout: float = 0.0
237
+ causal: bool = False
238
+ bias: bool = True
239
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
240
+
241
+ def setup(self) -> None:
242
+ self.head_dim = self.embed_dim // self.num_heads
243
+ if self.head_dim * self.num_heads != self.embed_dim:
244
+ raise ValueError(
245
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
246
+ f" and `num_heads`: {self.num_heads})."
247
+ )
248
+
249
+ dense = partial(
250
+ nn.Dense,
251
+ self.embed_dim,
252
+ use_bias=self.bias,
253
+ dtype=self.dtype,
254
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
255
+ )
256
+
257
+ self.q_proj, self.k_proj, self.v_proj = dense(), dense(), dense()
258
+ self.out_proj = dense()
259
+
260
+ self.dropout_layer = nn.Dropout(rate=self.dropout)
261
+
262
+ if self.causal:
263
+ self.causal_mask = make_causal_mask(
264
+ jnp.ones((1, self.config.max_position_embeddings), dtype="bool"), dtype="bool"
265
+ )
266
+
267
+ def _split_heads(self, hidden_states):
268
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.num_heads, self.head_dim))
269
+
270
+ def _merge_heads(self, hidden_states):
271
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))
272
+
273
+ @nn.compact
274
+ def _concatenate_to_cache(self, key, value, query, attention_mask):
275
+ """
276
+ This function takes projected key, value states from a single input token and concatenates the states to cached
277
+ states from previous steps. This function is slightly adapted from the official Flax repository:
278
+ https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
279
+ """
280
+ # detect if we're initializing by absence of existing cache data.
281
+ is_initialized = self.has_variable("cache", "cached_key")
282
+ cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
283
+ cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
284
+ cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
285
+
286
+ if is_initialized:
287
+ *batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
288
+ # update key, value caches with our new 1d spatial slices
289
+ cur_index = cache_index.value
290
+ indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
291
+ key = lax.dynamic_update_slice(cached_key.value, key, indices)
292
+ value = lax.dynamic_update_slice(cached_value.value, value, indices)
293
+ cached_key.value = key
294
+ cached_value.value = value
295
+ num_updated_cache_vectors = query.shape[1]
296
+ cache_index.value = cache_index.value + num_updated_cache_vectors
297
+ # causal mask for cached decoder self-attention: our single query position should only attend to those key positions that have already been generated and cached, not the remaining zero elements.
298
+ pad_mask = jnp.broadcast_to(
299
+ jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
300
+ tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
301
+ )
302
+ attention_mask = combine_masks(pad_mask, attention_mask)
303
+ return key, value, attention_mask
304
+
305
+ def __call__(
306
+ self,
307
+ hidden_states: jnp.ndarray,
308
+ key_value_states: Optional[jnp.ndarray] = None,
309
+ attention_mask: Optional[jnp.ndarray] = None,
310
+ init_cache: bool = False,
311
+ deterministic: bool = True,
312
+ ) -> Tuple[jnp.ndarray]:
313
+ """Input shape: Batch x Time x Channel"""
314
+
315
+ # if key_value_states are provided this layer is used as a cross-attention layer
316
+ # for the decoder
317
+ is_cross_attention = key_value_states is not None
318
+ batch_size = hidden_states.shape[0]
319
+
320
+ # get query proj
321
+ query_states = self.q_proj(hidden_states)
322
+ # get key, value proj
323
+ if is_cross_attention:
324
+ # cross_attentions
325
+ key_states = self.k_proj(key_value_states)
326
+ value_states = self.v_proj(key_value_states)
327
+ else:
328
+ # self_attention
329
+ key_states = self.k_proj(hidden_states)
330
+ value_states = self.v_proj(hidden_states)
331
+
332
+ query_states = self._split_heads(query_states)
333
+ key_states = self._split_heads(key_states)
334
+ value_states = self._split_heads(value_states)
335
+
336
+ # handle cache prepare causal attention mask
337
+ if self.causal:
338
+ query_length, key_length = query_states.shape[1], key_states.shape[1]
339
+ if self.has_variable("cache", "cached_key"):
340
+ mask_shift = self.variables["cache"]["cache_index"]
341
+ max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
342
+ causal_mask = lax.dynamic_slice(
343
+ self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)
344
+ )
345
+ else:
346
+ causal_mask = self.causal_mask[:, :, :query_length, :key_length]
347
+ causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
348
+
349
+ # combine masks if needed
350
+ if attention_mask is not None and self.causal:
351
+ attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)
352
+ attention_mask = combine_masks(attention_mask, causal_mask)
353
+ elif self.causal:
354
+ attention_mask = causal_mask
355
+ elif attention_mask is not None:
356
+ attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
357
+
358
+ # During fast autoregressive decoding, we feed one position at a time,
359
+ # and cache the keys and values step by step.
360
+ if self.causal and (self.has_variable("cache", "cached_key") or init_cache):
361
+ key_states, value_states, attention_mask = self._concatenate_to_cache(
362
+ key_states, value_states, query_states, attention_mask
363
+ )
364
+
365
+ # Convert the boolean attention mask to an attention bias.
366
+ if attention_mask is not None:
367
+ # attention mask in the form of attention bias
368
+ attention_bias = lax.select(
369
+ attention_mask > 0,
370
+ jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
371
+ jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
372
+ )
373
+ else:
374
+ attention_bias = None
375
+
376
+ dropout_rng = None
377
+ if not deterministic and self.dropout > 0.0:
378
+ dropout_rng = self.make_rng("dropout")
379
+
380
+ attn_weights = dot_product_attention_weights(
381
+ query_states,
382
+ key_states,
383
+ bias=attention_bias,
384
+ dropout_rng=dropout_rng,
385
+ dropout_rate=self.dropout,
386
+ broadcast_dropout=True,
387
+ deterministic=deterministic,
388
+ dtype=self.dtype,
389
+ precision=None,
390
+ )
391
+
392
+ attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
393
+ attn_output = self._merge_heads(attn_output)
394
+ attn_output = self.out_proj(attn_output)
395
+
396
+ return attn_output, attn_weights
397
+
398
+
399
+ class FlaxBartEncoderLayer(nn.Module):
400
+ config: BartConfig
401
+ dtype: jnp.dtype = jnp.float32
402
+
403
+ def setup(self) -> None:
404
+ self.embed_dim = self.config.d_model
405
+ self.self_attn = FlaxBartAttention(
406
+ config=self.config,
407
+ embed_dim=self.embed_dim,
408
+ num_heads=self.config.encoder_attention_heads,
409
+ dropout=self.config.attention_dropout,
410
+ dtype=self.dtype,
411
+ )
412
+ self.self_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
413
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
414
+ self.activation_fn = ACT2FN[self.config.activation_function]
415
+ self.activation_dropout_layer = nn.Dropout(rate=self.config.activation_dropout)
416
+ self.fc1 = nn.Dense(
417
+ self.config.encoder_ffn_dim,
418
+ dtype=self.dtype,
419
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
420
+ )
421
+ self.fc2 = nn.Dense(
422
+ self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)
423
+ )
424
+ self.final_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
425
+
426
+ def __call__(
427
+ self,
428
+ hidden_states: jnp.ndarray,
429
+ attention_mask: jnp.ndarray,
430
+ output_attentions: bool = True,
431
+ deterministic: bool = True,
432
+ ) -> Tuple[jnp.ndarray]:
433
+ residual = hidden_states
434
+ hidden_states, attn_weights = self.self_attn(hidden_states=hidden_states, attention_mask=attention_mask)
435
+
436
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
437
+ hidden_states = residual + hidden_states
438
+ hidden_states = self.self_attn_layer_norm(hidden_states)
439
+
440
+ residual = hidden_states
441
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
442
+ hidden_states = self.activation_dropout_layer(hidden_states, deterministic=deterministic)
443
+ hidden_states = self.fc2(hidden_states)
444
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
445
+ hidden_states = residual + hidden_states
446
+ hidden_states = self.final_layer_norm(hidden_states)
447
+
448
+ outputs = (hidden_states,)
449
+
450
+ if output_attentions:
451
+ outputs += (attn_weights,)
452
+
453
+ return outputs
454
+
455
+
456
+ class FlaxBartEncoderLayerCollection(nn.Module):
457
+ config: BartConfig
458
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
459
+
460
+ def setup(self):
461
+ self.layers = [
462
+ FlaxBartEncoderLayer(self.config, name=str(i), dtype=self.dtype) for i in range(self.config.encoder_layers)
463
+ ]
464
+ self.layerdrop = self.config.encoder_layerdrop
465
+
466
+ def __call__(
467
+ self,
468
+ hidden_states,
469
+ attention_mask,
470
+ deterministic: bool = True,
471
+ output_attentions: bool = False,
472
+ output_hidden_states: bool = False,
473
+ return_dict: bool = True,
474
+ ):
475
+ all_attentions = () if output_attentions else None
476
+ all_hidden_states = () if output_hidden_states else None
477
+
478
+ for encoder_layer in self.layers:
479
+ if output_hidden_states:
480
+ all_hidden_states = all_hidden_states + (hidden_states,)
481
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
482
+ dropout_probability = random.uniform(0, 1)
483
+ if not deterministic and (dropout_probability < self.layerdrop): # skip the layer
484
+ layer_outputs = (None, None)
485
+ else:
486
+ layer_outputs = encoder_layer(
487
+ hidden_states,
488
+ attention_mask,
489
+ output_attentions,
490
+ deterministic,
491
+ )
492
+ hidden_states = layer_outputs[0]
493
+ if output_attentions:
494
+ all_attentions = all_attentions + (layer_outputs[1],)
495
+
496
+ if output_hidden_states:
497
+ all_hidden_states += (hidden_states,)
498
+
499
+ outputs = (hidden_states, all_hidden_states, all_attentions)
500
+
501
+ if not return_dict:
502
+ return tuple(v for v in outputs if v is not None)
503
+
504
+ return FlaxBaseModelOutput(
505
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
506
+ )
507
+
508
+
509
+ class FlaxBartDecoderLayer(nn.Module):
510
+ config: BartConfig
511
+ dtype: jnp.dtype = jnp.float32
512
+
513
+ def setup(self) -> None:
514
+ self.embed_dim = self.config.d_model
515
+ self.self_attn = FlaxBartAttention(
516
+ config=self.config,
517
+ embed_dim=self.embed_dim,
518
+ num_heads=self.config.decoder_attention_heads,
519
+ dropout=self.config.attention_dropout,
520
+ causal=True,
521
+ dtype=self.dtype,
522
+ )
523
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
524
+ self.activation_fn = ACT2FN[self.config.activation_function]
525
+ self.activation_dropout_layer = nn.Dropout(rate=self.config.activation_dropout)
526
+
527
+ self.self_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
528
+ self.encoder_attn = FlaxBartAttention(
529
+ config=self.config,
530
+ embed_dim=self.embed_dim,
531
+ num_heads=self.config.decoder_attention_heads,
532
+ dropout=self.config.attention_dropout,
533
+ dtype=self.dtype,
534
+ )
535
+ self.encoder_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
536
+ self.fc1 = nn.Dense(
537
+ self.config.decoder_ffn_dim,
538
+ dtype=self.dtype,
539
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
540
+ )
541
+ self.fc2 = nn.Dense(
542
+ self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)
543
+ )
544
+ self.final_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
545
+
546
+ def __call__(
547
+ self,
548
+ hidden_states: jnp.ndarray,
549
+ attention_mask: jnp.ndarray,
550
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
551
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
552
+ init_cache: bool = False,
553
+ output_attentions: bool = True,
554
+ deterministic: bool = True,
555
+ ) -> Tuple[jnp.ndarray]:
556
+ residual = hidden_states
557
+
558
+ # Self Attention
559
+ hidden_states, self_attn_weights = self.self_attn(
560
+ hidden_states=hidden_states, attention_mask=attention_mask, init_cache=init_cache
561
+ )
562
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
563
+ hidden_states = residual + hidden_states
564
+ hidden_states = self.self_attn_layer_norm(hidden_states)
565
+
566
+ # Cross-Attention Block
567
+ cross_attn_weights = None
568
+ if encoder_hidden_states is not None:
569
+ residual = hidden_states
570
+
571
+ hidden_states, cross_attn_weights = self.encoder_attn(
572
+ hidden_states=hidden_states,
573
+ key_value_states=encoder_hidden_states,
574
+ attention_mask=encoder_attention_mask,
575
+ )
576
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
577
+ hidden_states = residual + hidden_states
578
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
579
+
580
+ # Fully Connected
581
+ residual = hidden_states
582
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
583
+ hidden_states = self.activation_dropout_layer(hidden_states, deterministic=deterministic)
584
+ hidden_states = self.fc2(hidden_states)
585
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
586
+ hidden_states = residual + hidden_states
587
+ hidden_states = self.final_layer_norm(hidden_states)
588
+
589
+ outputs = (hidden_states,)
590
+
591
+ if output_attentions:
592
+ outputs += (self_attn_weights, cross_attn_weights)
593
+
594
+ return outputs
595
+
596
+
597
+ class FlaxBartDecoderLayerCollection(nn.Module):
598
+ config: BartConfig
599
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
600
+
601
+ def setup(self):
602
+ self.layers = [
603
+ FlaxBartDecoderLayer(self.config, name=str(i), dtype=self.dtype) for i in range(self.config.decoder_layers)
604
+ ]
605
+ self.layerdrop = self.config.decoder_layerdrop
606
+
607
+ def __call__(
608
+ self,
609
+ hidden_states,
610
+ attention_mask,
611
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
612
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
613
+ deterministic: bool = True,
614
+ init_cache: bool = False,
615
+ output_attentions: bool = False,
616
+ output_hidden_states: bool = False,
617
+ return_dict: bool = True,
618
+ ):
619
+ # decoder layers
620
+ all_hidden_states = () if output_hidden_states else None
621
+ all_self_attns = () if output_attentions else None
622
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
623
+
624
+ for decoder_layer in self.layers:
625
+ if output_hidden_states:
626
+ all_hidden_states += (hidden_states,)
627
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
628
+ dropout_probability = random.uniform(0, 1)
629
+ if not deterministic and (dropout_probability < self.layerdrop):
630
+ layer_outputs = (None, None, None)
631
+ else:
632
+ layer_outputs = decoder_layer(
633
+ hidden_states,
634
+ attention_mask=attention_mask,
635
+ encoder_hidden_states=encoder_hidden_states,
636
+ encoder_attention_mask=encoder_attention_mask,
637
+ init_cache=init_cache,
638
+ output_attentions=output_attentions,
639
+ deterministic=deterministic,
640
+ )
641
+
642
+ hidden_states = layer_outputs[0]
643
+ if output_attentions:
644
+ all_self_attns += (layer_outputs[1],)
645
+
646
+ if encoder_hidden_states is not None:
647
+ all_cross_attentions += (layer_outputs[2],)
648
+
649
+ # add hidden states from the last decoder layer
650
+ if output_hidden_states:
651
+ all_hidden_states += (hidden_states,)
652
+
653
+ outputs = [hidden_states, all_hidden_states, all_self_attns, all_cross_attentions]
654
+
655
+ if not return_dict:
656
+ return tuple(v for v in outputs if v is not None)
657
+
658
+ return FlaxBaseModelOutputWithPastAndCrossAttentions(
659
+ last_hidden_state=hidden_states,
660
+ hidden_states=all_hidden_states,
661
+ attentions=all_self_attns,
662
+ cross_attentions=all_cross_attentions,
663
+ )
664
+
665
+
666
+ class FlaxBartClassificationHead(nn.Module):
667
+ """Head for sentence-level classification tasks."""
668
+
669
+ config: BartConfig
670
+ inner_dim: int
671
+ num_classes: int
672
+ pooler_dropout: float
673
+ dtype: jnp.dtype = jnp.float32
674
+
675
+ def setup(self):
676
+ self.dense = nn.Dense(
677
+ self.inner_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)
678
+ )
679
+ self.dropout = nn.Dropout(rate=self.pooler_dropout)
680
+ self.out_proj = nn.Dense(
681
+ self.num_classes,
682
+ dtype=self.dtype,
683
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
684
+ )
685
+
686
+ def __call__(self, hidden_states: jnp.ndarray, deterministic: bool):
687
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
688
+ hidden_states = self.dense(hidden_states)
689
+ hidden_states = jnp.tanh(hidden_states)
690
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
691
+ hidden_states = self.out_proj(hidden_states)
692
+ return hidden_states
693
+
694
+
695
+ class FlaxBartEncoder(nn.Module):
696
+ config: BartConfig
697
+ embed_tokens: nn.Embed
698
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
699
+
700
+ def setup(self):
701
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
702
+
703
+ embed_dim = self.config.d_model
704
+ self.padding_idx = self.config.pad_token_id
705
+ self.max_source_positions = self.config.max_position_embeddings
706
+ self.embed_scale = math.sqrt(embed_dim) if self.config.scale_embedding else 1.0
707
+
708
+ # Bart is set up so that if padding_idx is specified then offset the embedding ids by 2
709
+ # and adjust num_embeddings appropriately. Other models don't have this hack
710
+ self.offset = 2
711
+ self.embed_positions = nn.Embed(
712
+ self.config.max_position_embeddings + self.offset,
713
+ embed_dim,
714
+ embedding_init=jax.nn.initializers.normal(self.config.init_std),
715
+ dtype=self.dtype,
716
+ )
717
+ self.layers = FlaxBartEncoderLayerCollection(self.config, self.dtype)
718
+ self.layernorm_embedding = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
719
+
720
+ def __call__(
721
+ self,
722
+ input_ids,
723
+ attention_mask,
724
+ position_ids,
725
+ output_attentions: bool = False,
726
+ output_hidden_states: bool = False,
727
+ return_dict: bool = True,
728
+ deterministic: bool = True,
729
+ ):
730
+ input_shape = input_ids.shape
731
+ input_ids = input_ids.reshape(-1, input_shape[-1])
732
+
733
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
734
+
735
+ embed_pos = self.embed_positions(position_ids + self.offset)
736
+
737
+ hidden_states = inputs_embeds + embed_pos
738
+ hidden_states = self.layernorm_embedding(hidden_states)
739
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
740
+
741
+ outputs = self.layers(
742
+ hidden_states,
743
+ attention_mask,
744
+ deterministic=deterministic,
745
+ output_attentions=output_attentions,
746
+ output_hidden_states=output_hidden_states,
747
+ return_dict=return_dict,
748
+ )
749
+
750
+ if not return_dict:
751
+ return outputs
752
+
753
+ return FlaxBaseModelOutput(
754
+ last_hidden_state=outputs.last_hidden_state,
755
+ hidden_states=outputs.hidden_states,
756
+ attentions=outputs.attentions,
757
+ )
758
+
759
+
760
+ class FlaxBartDecoder(nn.Module):
761
+ config: BartConfig
762
+ embed_tokens: nn.Embed
763
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
764
+
765
+ def setup(self):
766
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
767
+
768
+ embed_dim = self.config.d_model
769
+ self.padding_idx = self.config.pad_token_id
770
+ self.max_target_positions = self.config.max_position_embeddings
771
+ self.embed_scale = math.sqrt(self.config.d_model) if self.config.scale_embedding else 1.0
772
+
773
+ # Bart is set up so that if padding_idx is specified then offset the embedding ids by 2
774
+ # and adjust num_embeddings appropriately. Other models don't have this hack
775
+ self.offset = 2
776
+ self.embed_positions = nn.Embed(
777
+ self.config.max_position_embeddings + self.offset,
778
+ embed_dim,
779
+ embedding_init=jax.nn.initializers.normal(self.config.init_std),
780
+ dtype=self.dtype,
781
+ )
782
+
783
+ self.layers = FlaxBartDecoderLayerCollection(self.config, self.dtype)
784
+ self.layernorm_embedding = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
785
+
786
+ def __call__(
787
+ self,
788
+ input_ids,
789
+ attention_mask,
790
+ position_ids,
791
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
792
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
793
+ init_cache: bool = False,
794
+ output_attentions: bool = False,
795
+ output_hidden_states: bool = False,
796
+ return_dict: bool = True,
797
+ deterministic: bool = True,
798
+ ):
799
+ input_shape = input_ids.shape
800
+ input_ids = input_ids.reshape(-1, input_shape[-1])
801
+
802
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
803
+
804
+ # embed positions
805
+ positions = self.embed_positions(position_ids + self.offset)
806
+
807
+ hidden_states = inputs_embeds + positions
808
+ hidden_states = self.layernorm_embedding(hidden_states)
809
+
810
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
811
+
812
+ outputs = self.layers(
813
+ hidden_states,
814
+ attention_mask,
815
+ encoder_hidden_states,
816
+ encoder_attention_mask,
817
+ deterministic=deterministic,
818
+ init_cache=init_cache,
819
+ output_attentions=output_attentions,
820
+ output_hidden_states=output_hidden_states,
821
+ return_dict=return_dict,
822
+ )
823
+
824
+ if not return_dict:
825
+ return outputs
826
+
827
+ return FlaxBaseModelOutputWithPastAndCrossAttentions(
828
+ last_hidden_state=outputs.last_hidden_state,
829
+ hidden_states=outputs.hidden_states,
830
+ attentions=outputs.attentions,
831
+ cross_attentions=outputs.cross_attentions,
832
+ )
833
+
834
+
835
+ class FlaxBartModule(nn.Module):
836
+ config: BartConfig
837
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
838
+
839
+ def setup(self):
840
+ self.shared = nn.Embed(
841
+ self.config.vocab_size,
842
+ self.config.d_model,
843
+ embedding_init=jax.nn.initializers.normal(self.config.init_std),
844
+ dtype=self.dtype,
845
+ )
846
+
847
+ self.encoder = FlaxBartEncoder(self.config, dtype=self.dtype, embed_tokens=self.shared)
848
+ self.decoder = FlaxBartDecoder(self.config, dtype=self.dtype, embed_tokens=self.shared)
849
+
850
+ def _get_encoder_module(self):
851
+ return self.encoder
852
+
853
+ def _get_decoder_module(self):
854
+ return self.decoder
855
+
856
+ def __call__(
857
+ self,
858
+ input_ids,
859
+ attention_mask,
860
+ decoder_input_ids,
861
+ decoder_attention_mask,
862
+ position_ids,
863
+ decoder_position_ids,
864
+ output_attentions: bool = False,
865
+ output_hidden_states: bool = False,
866
+ return_dict: bool = True,
867
+ deterministic: bool = True,
868
+ ):
869
+ encoder_outputs = self.encoder(
870
+ input_ids=input_ids,
871
+ attention_mask=attention_mask,
872
+ position_ids=position_ids,
873
+ output_attentions=output_attentions,
874
+ output_hidden_states=output_hidden_states,
875
+ return_dict=return_dict,
876
+ deterministic=deterministic,
877
+ )
878
+
879
+ decoder_outputs = self.decoder(
880
+ input_ids=decoder_input_ids,
881
+ attention_mask=decoder_attention_mask,
882
+ position_ids=decoder_position_ids,
883
+ encoder_hidden_states=encoder_outputs[0],
884
+ encoder_attention_mask=attention_mask,
885
+ output_attentions=output_attentions,
886
+ output_hidden_states=output_hidden_states,
887
+ return_dict=return_dict,
888
+ deterministic=deterministic,
889
+ )
890
+
891
+ if not return_dict:
892
+ return decoder_outputs + encoder_outputs
893
+
894
+ return FlaxSeq2SeqModelOutput(
895
+ last_hidden_state=decoder_outputs.last_hidden_state,
896
+ decoder_hidden_states=decoder_outputs.hidden_states,
897
+ decoder_attentions=decoder_outputs.attentions,
898
+ cross_attentions=decoder_outputs.cross_attentions,
899
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
900
+ encoder_hidden_states=encoder_outputs.hidden_states,
901
+ encoder_attentions=encoder_outputs.attentions,
902
+ )
903
+
904
+
905
+ class FlaxBartPreTrainedModel(FlaxPreTrainedModel):
906
+ config_class = BartConfig
907
+ base_model_prefix: str = "model"
908
+ module_class: nn.Module = None
909
+
910
+ def __init__(
911
+ self,
912
+ config: BartConfig,
913
+ input_shape: Tuple[int] = (1, 1),
914
+ seed: int = 0,
915
+ dtype: jnp.dtype = jnp.float32,
916
+ _do_init: bool = True,
917
+ **kwargs,
918
+ ):
919
+ module = self.module_class(config=config, dtype=dtype, **kwargs)
920
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
921
+
922
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
923
+ # init input tensors
924
+ input_ids = jnp.zeros(input_shape, dtype="i4")
925
+ # make sure initialization pass will work for FlaxBartForSequenceClassificationModule
926
+ input_ids = input_ids.at[(..., -1)].set(self.config.eos_token_id)
927
+ attention_mask = jnp.ones_like(input_ids)
928
+ decoder_input_ids = input_ids
929
+ decoder_attention_mask = jnp.ones_like(input_ids)
930
+
931
+ batch_size, sequence_length = input_ids.shape
932
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
933
+ decoder_position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
934
+
935
+ params_rng, dropout_rng = jax.random.split(rng)
936
+ rngs = {"params": params_rng, "dropout": dropout_rng}
937
+
938
+ random_params = self.module.init(
939
+ rngs,
940
+ input_ids,
941
+ attention_mask,
942
+ decoder_input_ids,
943
+ decoder_attention_mask,
944
+ position_ids,
945
+ decoder_position_ids,
946
+ )["params"]
947
+
948
+ if params is not None:
949
+ random_params = flatten_dict(unfreeze(random_params))
950
+ params = flatten_dict(unfreeze(params))
951
+ for missing_key in self._missing_keys:
952
+ params[missing_key] = random_params[missing_key]
953
+ self._missing_keys = set()
954
+ return freeze(unflatten_dict(params))
955
+ else:
956
+ return random_params
957
+
958
+ def init_cache(self, batch_size, max_length, encoder_outputs):
959
+ r"""
960
+ Args:
961
+ batch_size (`int`):
962
+ batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
963
+ max_length (`int`):
964
+ maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
965
+ cache.
966
+ encoder_outputs (`Union[FlaxBaseModelOutput, tuple(tuple(jnp.ndarray)]`):
967
+ `encoder_outputs` consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*:
968
+ `attentions`). `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*)
969
+ is a sequence of hidden-states at the output of the last layer of the encoder. Used in the
970
+ cross-attention of the decoder.
971
+ """
972
+ # init input variables to retrieve cache
973
+ decoder_input_ids = jnp.ones((batch_size, max_length), dtype="i4")
974
+ decoder_attention_mask = jnp.ones_like(decoder_input_ids)
975
+ decoder_position_ids = jnp.broadcast_to(
976
+ jnp.arange(jnp.atleast_2d(decoder_input_ids).shape[-1]), decoder_input_ids.shape
977
+ )
978
+
979
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
980
+ decoder_module = module._get_decoder_module()
981
+ return decoder_module(
982
+ decoder_input_ids,
983
+ decoder_attention_mask,
984
+ decoder_position_ids,
985
+ **kwargs,
986
+ )
987
+
988
+ init_variables = self.module.init(
989
+ jax.random.PRNGKey(0),
990
+ decoder_input_ids=decoder_input_ids,
991
+ decoder_attention_mask=decoder_attention_mask,
992
+ decoder_position_ids=decoder_position_ids,
993
+ encoder_hidden_states=encoder_outputs[0],
994
+ init_cache=True,
995
+ method=_decoder_forward, # we only need to call the decoder to init the cache
996
+ )
997
+ return unfreeze(init_variables["cache"])
998
+
999
+ @add_start_docstrings(BART_ENCODE_INPUTS_DOCSTRING)
1000
+ @replace_return_docstrings(output_type=FlaxBaseModelOutput, config_class=BartConfig)
1001
+ def encode(
1002
+ self,
1003
+ input_ids: jnp.ndarray,
1004
+ attention_mask: Optional[jnp.ndarray] = None,
1005
+ position_ids: Optional[jnp.ndarray] = None,
1006
+ output_attentions: Optional[bool] = None,
1007
+ output_hidden_states: Optional[bool] = None,
1008
+ return_dict: Optional[bool] = None,
1009
+ train: bool = False,
1010
+ params: dict = None,
1011
+ dropout_rng: PRNGKey = None,
1012
+ ):
1013
+ r"""
1014
+ Returns:
1015
+
1016
+ Example:
1017
+
1018
+ ```python
1019
+ >>> from transformers import AutoTokenizer, FlaxBartForConditionalGeneration
1020
+
1021
+ >>> model = FlaxBartForConditionalGeneration.from_pretrained("facebook/bart-large-cnn")
1022
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-cnn")
1023
+
1024
+ >>> text = "My friends are cool but they eat too many carbs."
1025
+ >>> inputs = tokenizer(text, max_length=1024, return_tensors="jax")
1026
+ >>> encoder_outputs = model.encode(**inputs)
1027
+ ```"""
1028
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1029
+ output_hidden_states = (
1030
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1031
+ )
1032
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1033
+
1034
+ if attention_mask is None:
1035
+ attention_mask = jnp.ones_like(input_ids)
1036
+ if position_ids is None:
1037
+ batch_size, sequence_length = input_ids.shape
1038
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
1039
+
1040
+ # Handle any PRNG if needed
1041
+ rngs = {}
1042
+ if dropout_rng is not None:
1043
+ rngs["dropout"] = dropout_rng
1044
+
1045
+ def _encoder_forward(module, input_ids, attention_mask, position_ids, **kwargs):
1046
+ encode_module = module._get_encoder_module()
1047
+ return encode_module(input_ids, attention_mask, position_ids, **kwargs)
1048
+
1049
+ return self.module.apply(
1050
+ {"params": params or self.params},
1051
+ input_ids=jnp.array(input_ids, dtype="i4"),
1052
+ attention_mask=jnp.array(attention_mask, dtype="i4"),
1053
+ position_ids=jnp.array(position_ids, dtype="i4"),
1054
+ output_attentions=output_attentions,
1055
+ output_hidden_states=output_hidden_states,
1056
+ return_dict=return_dict,
1057
+ deterministic=not train,
1058
+ rngs=rngs,
1059
+ method=_encoder_forward,
1060
+ )
1061
+
1062
+ @add_start_docstrings(BART_DECODE_INPUTS_DOCSTRING)
1063
+ @replace_return_docstrings(output_type=FlaxBaseModelOutputWithPastAndCrossAttentions, config_class=BartConfig)
1064
+ def decode(
1065
+ self,
1066
+ decoder_input_ids,
1067
+ encoder_outputs,
1068
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
1069
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
1070
+ decoder_position_ids: Optional[jnp.ndarray] = None,
1071
+ past_key_values: dict = None,
1072
+ output_attentions: Optional[bool] = None,
1073
+ output_hidden_states: Optional[bool] = None,
1074
+ return_dict: Optional[bool] = None,
1075
+ train: bool = False,
1076
+ params: dict = None,
1077
+ dropout_rng: PRNGKey = None,
1078
+ ):
1079
+ r"""
1080
+ Returns:
1081
+
1082
+ Example:
1083
+
1084
+ ```python
1085
+ >>> import jax.numpy as jnp
1086
+ >>> from transformers import AutoTokenizer, FlaxBartForConditionalGeneration
1087
+
1088
+ >>> model = FlaxBartForConditionalGeneration.from_pretrained("facebook/bart-large-cnn")
1089
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-cnn")
1090
+
1091
+ >>> text = "My friends are cool but they eat too many carbs."
1092
+ >>> inputs = tokenizer(text, max_length=1024, return_tensors="jax")
1093
+ >>> encoder_outputs = model.encode(**inputs)
1094
+
1095
+ >>> decoder_start_token_id = model.config.decoder_start_token_id
1096
+ >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id
1097
+
1098
+ >>> outputs = model.decode(decoder_input_ids, encoder_outputs)
1099
+ >>> last_decoder_hidden_states = outputs.last_hidden_state
1100
+ ```"""
1101
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1102
+ output_hidden_states = (
1103
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1104
+ )
1105
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1106
+
1107
+ encoder_hidden_states = encoder_outputs[0]
1108
+ if encoder_attention_mask is None:
1109
+ batch_size, sequence_length = encoder_hidden_states.shape[:2]
1110
+ encoder_attention_mask = jnp.ones((batch_size, sequence_length))
1111
+
1112
+ batch_size, sequence_length = decoder_input_ids.shape
1113
+ if decoder_attention_mask is None:
1114
+ decoder_attention_mask = jnp.ones((batch_size, sequence_length))
1115
+
1116
+ if decoder_position_ids is None:
1117
+ if past_key_values is not None:
1118
+ raise ValueError("Make sure to provide `decoder_position_ids` when passing `past_key_values`.")
1119
+
1120
+ decoder_position_ids = jnp.broadcast_to(
1121
+ jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
1122
+ )
1123
+
1124
+ # Handle any PRNG if needed
1125
+ rngs = {}
1126
+ if dropout_rng is not None:
1127
+ rngs["dropout"] = dropout_rng
1128
+
1129
+ inputs = {"params": params or self.params}
1130
+
1131
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be
1132
+ # passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that
1133
+ # it can be changed by FlaxBartAttention module
1134
+ if past_key_values:
1135
+ inputs["cache"] = past_key_values
1136
+ mutable = ["cache"]
1137
+ else:
1138
+ mutable = False
1139
+
1140
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
1141
+ decoder_module = module._get_decoder_module()
1142
+ return decoder_module(
1143
+ decoder_input_ids,
1144
+ decoder_attention_mask,
1145
+ decoder_position_ids,
1146
+ **kwargs,
1147
+ )
1148
+
1149
+ outputs = self.module.apply(
1150
+ inputs,
1151
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1152
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1153
+ decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
1154
+ encoder_hidden_states=encoder_hidden_states,
1155
+ encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"),
1156
+ output_attentions=output_attentions,
1157
+ output_hidden_states=output_hidden_states,
1158
+ return_dict=return_dict,
1159
+ deterministic=not train,
1160
+ rngs=rngs,
1161
+ mutable=mutable,
1162
+ method=_decoder_forward,
1163
+ )
1164
+
1165
+ # add updated cache to model output
1166
+ if past_key_values is not None and return_dict:
1167
+ outputs, past = outputs
1168
+ outputs["past_key_values"] = unfreeze(past["cache"])
1169
+ return outputs
1170
+ elif past_key_values is not None and not return_dict:
1171
+ outputs, past = outputs
1172
+ outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:]
1173
+
1174
+ return outputs
1175
+
1176
+ @add_start_docstrings_to_model_forward(BART_INPUTS_DOCSTRING)
1177
+ def __call__(
1178
+ self,
1179
+ input_ids: jnp.ndarray,
1180
+ attention_mask: Optional[jnp.ndarray] = None,
1181
+ decoder_input_ids: Optional[jnp.ndarray] = None,
1182
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
1183
+ position_ids: Optional[jnp.ndarray] = None,
1184
+ decoder_position_ids: Optional[jnp.ndarray] = None,
1185
+ output_attentions: Optional[bool] = None,
1186
+ output_hidden_states: Optional[bool] = None,
1187
+ return_dict: Optional[bool] = None,
1188
+ train: bool = False,
1189
+ params: dict = None,
1190
+ dropout_rng: PRNGKey = None,
1191
+ ):
1192
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1193
+ output_hidden_states = (
1194
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1195
+ )
1196
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1197
+
1198
+ # prepare encoder inputs
1199
+ if attention_mask is None:
1200
+ attention_mask = jnp.ones_like(input_ids)
1201
+ if position_ids is None:
1202
+ batch_size, sequence_length = input_ids.shape
1203
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
1204
+
1205
+ # prepare decoder inputs
1206
+ if decoder_input_ids is None:
1207
+ decoder_input_ids = shift_tokens_right(
1208
+ input_ids, self.config.pad_token_id, decoder_start_token_id=self.config.decoder_start_token_id
1209
+ )
1210
+ if decoder_attention_mask is None:
1211
+ decoder_attention_mask = jnp.ones_like(decoder_input_ids)
1212
+ if decoder_position_ids is None:
1213
+ batch_size, sequence_length = decoder_input_ids.shape
1214
+ decoder_position_ids = jnp.broadcast_to(
1215
+ jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
1216
+ )
1217
+
1218
+ # Handle any PRNG if needed
1219
+ rngs = {"dropout": dropout_rng} if dropout_rng is not None else {}
1220
+
1221
+ return self.module.apply(
1222
+ {"params": params or self.params},
1223
+ input_ids=jnp.array(input_ids, dtype="i4"),
1224
+ attention_mask=jnp.array(attention_mask, dtype="i4"),
1225
+ position_ids=jnp.array(position_ids, dtype="i4"),
1226
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1227
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1228
+ decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
1229
+ output_attentions=output_attentions,
1230
+ output_hidden_states=output_hidden_states,
1231
+ return_dict=return_dict,
1232
+ deterministic=not train,
1233
+ rngs=rngs,
1234
+ )
1235
+
1236
+
1237
+ @add_start_docstrings(
1238
+ "The bare Bart Model transformer outputting raw hidden-states without any specific head on top.",
1239
+ BART_START_DOCSTRING,
1240
+ )
1241
+ class FlaxBartModel(FlaxBartPreTrainedModel):
1242
+ config: BartConfig
1243
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
1244
+ module_class = FlaxBartModule
1245
+
1246
+
1247
+ append_call_sample_docstring(FlaxBartModel, _CHECKPOINT_FOR_DOC, FlaxSeq2SeqModelOutput, _CONFIG_FOR_DOC)
1248
+
1249
+
1250
+ class FlaxBartForConditionalGenerationModule(nn.Module):
1251
+ config: BartConfig
1252
+ dtype: jnp.dtype = jnp.float32
1253
+ bias_init: Callable[..., jnp.ndarray] = jax.nn.initializers.zeros
1254
+
1255
+ def setup(self):
1256
+ self.model = FlaxBartModule(config=self.config, dtype=self.dtype)
1257
+ self.lm_head = nn.Dense(
1258
+ self.model.shared.num_embeddings,
1259
+ use_bias=False,
1260
+ dtype=self.dtype,
1261
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
1262
+ )
1263
+ self.final_logits_bias = self.param("final_logits_bias", self.bias_init, (1, self.model.shared.num_embeddings))
1264
+
1265
+ def _get_encoder_module(self):
1266
+ return self.model.encoder
1267
+
1268
+ def _get_decoder_module(self):
1269
+ return self.model.decoder
1270
+
1271
+ def __call__(
1272
+ self,
1273
+ input_ids,
1274
+ attention_mask,
1275
+ decoder_input_ids,
1276
+ decoder_attention_mask,
1277
+ position_ids,
1278
+ decoder_position_ids,
1279
+ output_attentions: bool = False,
1280
+ output_hidden_states: bool = False,
1281
+ return_dict: bool = True,
1282
+ deterministic: bool = True,
1283
+ ):
1284
+ outputs = self.model(
1285
+ input_ids=input_ids,
1286
+ attention_mask=attention_mask,
1287
+ decoder_input_ids=decoder_input_ids,
1288
+ decoder_attention_mask=decoder_attention_mask,
1289
+ position_ids=position_ids,
1290
+ decoder_position_ids=decoder_position_ids,
1291
+ output_attentions=output_attentions,
1292
+ output_hidden_states=output_hidden_states,
1293
+ return_dict=return_dict,
1294
+ deterministic=deterministic,
1295
+ )
1296
+
1297
+ hidden_states = outputs[0]
1298
+
1299
+ if self.config.tie_word_embeddings:
1300
+ shared_embedding = self.model.variables["params"]["shared"]["embedding"]
1301
+ lm_logits = self.lm_head.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
1302
+ else:
1303
+ lm_logits = self.lm_head(hidden_states)
1304
+
1305
+ lm_logits += jax.lax.stop_gradient(self.final_logits_bias.astype(self.dtype))
1306
+
1307
+ if not return_dict:
1308
+ output = (lm_logits,) + outputs[1:]
1309
+ return output
1310
+
1311
+ return FlaxSeq2SeqLMOutput(
1312
+ logits=lm_logits,
1313
+ decoder_hidden_states=outputs.decoder_hidden_states,
1314
+ decoder_attentions=outputs.decoder_attentions,
1315
+ cross_attentions=outputs.cross_attentions,
1316
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1317
+ encoder_hidden_states=outputs.encoder_hidden_states,
1318
+ encoder_attentions=outputs.encoder_attentions,
1319
+ )
1320
+
1321
+
1322
+ @add_start_docstrings(
1323
+ "The BART Model with a language modeling head. Can be used for summarization.", BART_START_DOCSTRING
1324
+ )
1325
+ class FlaxBartForConditionalGeneration(FlaxBartPreTrainedModel):
1326
+ module_class = FlaxBartForConditionalGenerationModule
1327
+ dtype: jnp.dtype = jnp.float32
1328
+
1329
+ @add_start_docstrings(BART_DECODE_INPUTS_DOCSTRING)
1330
+ @replace_return_docstrings(output_type=FlaxCausalLMOutputWithCrossAttentions, config_class=BartConfig)
1331
+ def decode(
1332
+ self,
1333
+ decoder_input_ids,
1334
+ encoder_outputs,
1335
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
1336
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
1337
+ decoder_position_ids: Optional[jnp.ndarray] = None,
1338
+ past_key_values: dict = None,
1339
+ output_attentions: Optional[bool] = None,
1340
+ output_hidden_states: Optional[bool] = None,
1341
+ return_dict: Optional[bool] = None,
1342
+ train: bool = False,
1343
+ params: dict = None,
1344
+ dropout_rng: PRNGKey = None,
1345
+ ):
1346
+ r"""
1347
+ Returns:
1348
+
1349
+ Example:
1350
+
1351
+ ```python
1352
+ >>> import jax.numpy as jnp
1353
+ >>> from transformers import AutoTokenizer, FlaxBartForConditionalGeneration
1354
+
1355
+ >>> model = FlaxBartForConditionalGeneration.from_pretrained("facebook/bart-large-cnn")
1356
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-cnn")
1357
+
1358
+ >>> text = "My friends are cool but they eat too many carbs."
1359
+ >>> inputs = tokenizer(text, max_length=1024, return_tensors="jax")
1360
+ >>> encoder_outputs = model.encode(**inputs)
1361
+
1362
+ >>> decoder_start_token_id = model.config.decoder_start_token_id
1363
+ >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id
1364
+
1365
+ >>> outputs = model.decode(decoder_input_ids, encoder_outputs)
1366
+ >>> logits = outputs.logits
1367
+ ```"""
1368
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1369
+ output_hidden_states = (
1370
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1371
+ )
1372
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1373
+
1374
+ encoder_hidden_states = encoder_outputs[0]
1375
+ if encoder_attention_mask is None:
1376
+ batch_size, sequence_length = encoder_hidden_states.shape[:2]
1377
+ encoder_attention_mask = jnp.ones((batch_size, sequence_length))
1378
+
1379
+ batch_size, sequence_length = decoder_input_ids.shape
1380
+ if decoder_attention_mask is None:
1381
+ decoder_attention_mask = jnp.ones((batch_size, sequence_length))
1382
+
1383
+ if decoder_position_ids is None:
1384
+ if past_key_values is not None:
1385
+ raise ValueError("Make sure to provide `decoder_position_ids` when passing `past_key_values`.")
1386
+
1387
+ decoder_position_ids = jnp.broadcast_to(
1388
+ jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
1389
+ )
1390
+
1391
+ # Handle any PRNG if needed
1392
+ rngs = {}
1393
+ if dropout_rng is not None:
1394
+ rngs["dropout"] = dropout_rng
1395
+
1396
+ inputs = {"params": params or self.params}
1397
+
1398
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be
1399
+ # passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that
1400
+ # it can be changed by FlaxBartAttention module
1401
+ if past_key_values:
1402
+ inputs["cache"] = past_key_values
1403
+ mutable = ["cache"]
1404
+ else:
1405
+ mutable = False
1406
+
1407
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
1408
+ decoder_module = module._get_decoder_module()
1409
+ outputs = decoder_module(
1410
+ decoder_input_ids,
1411
+ decoder_attention_mask,
1412
+ decoder_position_ids,
1413
+ **kwargs,
1414
+ )
1415
+ hidden_states = outputs[0]
1416
+
1417
+ if self.config.tie_word_embeddings:
1418
+ shared_embedding = module.model.variables["params"]["shared"]["embedding"]
1419
+ lm_logits = module.lm_head.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
1420
+ else:
1421
+ lm_logits = module.lm_head(hidden_states)
1422
+
1423
+ lm_logits += module.final_logits_bias.astype(self.dtype)
1424
+ return lm_logits, outputs
1425
+
1426
+ outputs = self.module.apply(
1427
+ inputs,
1428
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1429
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1430
+ decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
1431
+ encoder_hidden_states=encoder_hidden_states,
1432
+ encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"),
1433
+ output_attentions=output_attentions,
1434
+ output_hidden_states=output_hidden_states,
1435
+ return_dict=return_dict,
1436
+ deterministic=not train,
1437
+ rngs=rngs,
1438
+ mutable=mutable,
1439
+ method=_decoder_forward,
1440
+ )
1441
+
1442
+ if past_key_values is None:
1443
+ lm_logits, decoder_outputs = outputs
1444
+ else:
1445
+ (lm_logits, decoder_outputs), past = outputs
1446
+
1447
+ if return_dict:
1448
+ outputs = FlaxCausalLMOutputWithCrossAttentions(
1449
+ logits=lm_logits,
1450
+ hidden_states=decoder_outputs.hidden_states,
1451
+ attentions=decoder_outputs.attentions,
1452
+ cross_attentions=decoder_outputs.cross_attentions,
1453
+ )
1454
+ else:
1455
+ outputs = (lm_logits,) + decoder_outputs[1:]
1456
+
1457
+ # add updated cache to model output
1458
+ if past_key_values is not None and return_dict:
1459
+ outputs["past_key_values"] = unfreeze(past["cache"])
1460
+ return outputs
1461
+ elif past_key_values is not None and not return_dict:
1462
+ outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:]
1463
+
1464
+ return outputs
1465
+
1466
+ def prepare_inputs_for_generation(
1467
+ self,
1468
+ decoder_input_ids,
1469
+ max_length,
1470
+ attention_mask: Optional[jax.Array] = None,
1471
+ decoder_attention_mask: Optional[jax.Array] = None,
1472
+ encoder_outputs=None,
1473
+ **kwargs,
1474
+ ):
1475
+ # initializing the cache
1476
+ batch_size, seq_length = decoder_input_ids.shape
1477
+
1478
+ past_key_values = self.init_cache(batch_size, max_length, encoder_outputs)
1479
+ # Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
1480
+ # But since the decoder uses a causal mask, those positions are masked anyways.
1481
+ # Thus we can create a single static attention_mask here, which is more efficient for compilation
1482
+ extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
1483
+ if decoder_attention_mask is not None:
1484
+ position_ids = decoder_attention_mask.cumsum(axis=-1) - 1
1485
+ extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, decoder_attention_mask, (0, 0))
1486
+ else:
1487
+ position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
1488
+
1489
+ return {
1490
+ "past_key_values": past_key_values,
1491
+ "encoder_outputs": encoder_outputs,
1492
+ "encoder_attention_mask": attention_mask,
1493
+ "decoder_attention_mask": extended_attention_mask,
1494
+ "decoder_position_ids": position_ids,
1495
+ }
1496
+
1497
+ def update_inputs_for_generation(self, model_outputs, model_kwargs):
1498
+ model_kwargs["past_key_values"] = model_outputs.past_key_values
1499
+ model_kwargs["decoder_position_ids"] = model_kwargs["decoder_position_ids"][:, -1:] + 1
1500
+ return model_kwargs
1501
+
1502
+
1503
+ FLAX_BART_CONDITIONAL_GENERATION_DOCSTRING = """
1504
+ Returns:
1505
+
1506
+ Summarization example:
1507
+
1508
+ ```python
1509
+ >>> from transformers import AutoTokenizer, FlaxBartForConditionalGeneration
1510
+
1511
+ >>> model = FlaxBartForConditionalGeneration.from_pretrained("facebook/bart-large-cnn")
1512
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-cnn")
1513
+
1514
+ >>> ARTICLE_TO_SUMMARIZE = "My friends are cool but they eat too many carbs."
1515
+ >>> inputs = tokenizer([ARTICLE_TO_SUMMARIZE], max_length=1024, return_tensors="np")
1516
+
1517
+ >>> # Generate Summary
1518
+ >>> summary_ids = model.generate(inputs["input_ids"]).sequences
1519
+ >>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False))
1520
+ ```
1521
+
1522
+ Mask filling example:
1523
+
1524
+ ```python
1525
+ >>> import jax
1526
+ >>> from transformers import AutoTokenizer, FlaxBartForConditionalGeneration
1527
+
1528
+ >>> model = FlaxBartForConditionalGeneration.from_pretrained("facebook/bart-large")
1529
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large")
1530
+
1531
+ >>> TXT = "My friends are <mask> but they eat too many carbs."
1532
+ >>> input_ids = tokenizer([TXT], return_tensors="jax")["input_ids"]
1533
+
1534
+ >>> logits = model(input_ids).logits
1535
+ >>> masked_index = (input_ids[0] == tokenizer.mask_token_id).nonzero()[0].item()
1536
+ >>> probs = jax.nn.softmax(logits[0, masked_index], axis=0)
1537
+ >>> values, predictions = jax.lax.top_k(probs, k=1)
1538
+
1539
+ >>> tokenizer.decode(predictions).split()
1540
+ ```
1541
+ """
1542
+
1543
+ overwrite_call_docstring(
1544
+ FlaxBartForConditionalGeneration, BART_INPUTS_DOCSTRING + FLAX_BART_CONDITIONAL_GENERATION_DOCSTRING
1545
+ )
1546
+ append_replace_return_docstrings(
1547
+ FlaxBartForConditionalGeneration, output_type=FlaxSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC
1548
+ )
1549
+
1550
+
1551
+ class FlaxBartForSequenceClassificationModule(nn.Module):
1552
+ config: BartConfig
1553
+ dtype: jnp.dtype = jnp.float32
1554
+ num_labels: Optional[int] = None
1555
+
1556
+ def setup(self):
1557
+ self.model = FlaxBartModule(config=self.config, dtype=self.dtype)
1558
+ self.classification_head = FlaxBartClassificationHead(
1559
+ config=self.config,
1560
+ inner_dim=self.config.d_model,
1561
+ num_classes=self.num_labels if self.num_labels is not None else self.config.num_labels,
1562
+ pooler_dropout=self.config.classifier_dropout,
1563
+ )
1564
+
1565
+ def _get_encoder_module(self):
1566
+ return self.model.encoder
1567
+
1568
+ def _get_decoder_module(self):
1569
+ return self.model.decoder
1570
+
1571
+ def __call__(
1572
+ self,
1573
+ input_ids,
1574
+ attention_mask,
1575
+ decoder_input_ids,
1576
+ decoder_attention_mask,
1577
+ position_ids,
1578
+ decoder_position_ids,
1579
+ output_attentions: bool = False,
1580
+ output_hidden_states: bool = False,
1581
+ return_dict: bool = True,
1582
+ deterministic: bool = True,
1583
+ ):
1584
+ outputs = self.model(
1585
+ input_ids=input_ids,
1586
+ attention_mask=attention_mask,
1587
+ decoder_input_ids=decoder_input_ids,
1588
+ decoder_attention_mask=decoder_attention_mask,
1589
+ position_ids=position_ids,
1590
+ decoder_position_ids=decoder_position_ids,
1591
+ output_attentions=output_attentions,
1592
+ output_hidden_states=output_hidden_states,
1593
+ return_dict=return_dict,
1594
+ deterministic=deterministic,
1595
+ )
1596
+
1597
+ hidden_states = outputs[0] # last hidden state
1598
+
1599
+ eos_mask = jnp.where(input_ids == self.config.eos_token_id, 1, 0)
1600
+
1601
+ # The first condition is necessary to overcome jax._src.errors.ConcretizationTypeError during JIT compilation
1602
+ if not isinstance(eos_mask, jax.interpreters.partial_eval.DynamicJaxprTracer):
1603
+ if len(jnp.unique(eos_mask.sum(1))) > 1:
1604
+ raise ValueError("All examples must have the same number of <eos> tokens.")
1605
+
1606
+ if any(eos_mask.sum(1) == 0):
1607
+ raise ValueError("There are missing <eos> tokens in input_ids")
1608
+
1609
+ # Ensure to keep 1 only for the last <eos> token for each example
1610
+ eos_mask_noised = eos_mask + jnp.arange(eos_mask.shape[1]) * 1e-6
1611
+ eos_mask = jnp.where(eos_mask_noised == eos_mask_noised.max(1).reshape(-1, 1), 1, 0)
1612
+
1613
+ sentence_representation = jnp.einsum("ijk, ij -> ijk", hidden_states, eos_mask).sum(1)
1614
+ logits = self.classification_head(sentence_representation, deterministic=deterministic)
1615
+
1616
+ if not return_dict:
1617
+ output = (logits,) + outputs[1:]
1618
+ return output
1619
+
1620
+ return FlaxSeq2SeqSequenceClassifierOutput(
1621
+ logits=logits,
1622
+ decoder_hidden_states=outputs.decoder_hidden_states,
1623
+ decoder_attentions=outputs.decoder_attentions,
1624
+ cross_attentions=outputs.cross_attentions,
1625
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1626
+ encoder_hidden_states=outputs.encoder_hidden_states,
1627
+ encoder_attentions=outputs.encoder_attentions,
1628
+ )
1629
+
1630
+
1631
+ @add_start_docstrings(
1632
+ """
1633
+ Bart model with a sequence classification/head on top (a linear layer on top of the pooled output) e.g. for GLUE
1634
+ tasks.
1635
+ """,
1636
+ BART_START_DOCSTRING,
1637
+ )
1638
+ class FlaxBartForSequenceClassification(FlaxBartPreTrainedModel):
1639
+ module_class = FlaxBartForSequenceClassificationModule
1640
+ dtype = jnp.float32
1641
+
1642
+
1643
+ append_call_sample_docstring(
1644
+ FlaxBartForSequenceClassification,
1645
+ _CHECKPOINT_FOR_DOC,
1646
+ FlaxSeq2SeqSequenceClassifierOutput,
1647
+ _CONFIG_FOR_DOC,
1648
+ )
1649
+
1650
+
1651
+ class FlaxBartForQuestionAnsweringModule(nn.Module):
1652
+ config: BartConfig
1653
+ dtype: jnp.dtype = jnp.float32
1654
+ num_labels = 2
1655
+
1656
+ def setup(self):
1657
+ self.model = FlaxBartModule(config=self.config, dtype=self.dtype)
1658
+ self.qa_outputs = nn.Dense(
1659
+ self.num_labels, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)
1660
+ )
1661
+
1662
+ def _get_encoder_module(self):
1663
+ return self.model.encoder
1664
+
1665
+ def _get_decoder_module(self):
1666
+ return self.model.decoder
1667
+
1668
+ def __call__(
1669
+ self,
1670
+ input_ids,
1671
+ attention_mask,
1672
+ decoder_input_ids,
1673
+ decoder_attention_mask,
1674
+ position_ids,
1675
+ decoder_position_ids,
1676
+ output_attentions: bool = False,
1677
+ output_hidden_states: bool = False,
1678
+ return_dict: bool = True,
1679
+ deterministic: bool = True,
1680
+ ):
1681
+ outputs = self.model(
1682
+ input_ids=input_ids,
1683
+ attention_mask=attention_mask,
1684
+ decoder_input_ids=decoder_input_ids,
1685
+ decoder_attention_mask=decoder_attention_mask,
1686
+ position_ids=position_ids,
1687
+ decoder_position_ids=decoder_position_ids,
1688
+ output_attentions=output_attentions,
1689
+ output_hidden_states=output_hidden_states,
1690
+ return_dict=return_dict,
1691
+ deterministic=deterministic,
1692
+ )
1693
+
1694
+ sequence_output = outputs[0]
1695
+
1696
+ logits = self.qa_outputs(sequence_output)
1697
+ start_logits, end_logits = jnp.split(logits, logits.shape[-1], axis=-1)
1698
+ start_logits = start_logits.squeeze(-1)
1699
+ end_logits = end_logits.squeeze(-1)
1700
+
1701
+ if not return_dict:
1702
+ output = (start_logits, end_logits) + outputs[1:]
1703
+ return output
1704
+
1705
+ return FlaxSeq2SeqQuestionAnsweringModelOutput(
1706
+ start_logits=start_logits,
1707
+ end_logits=end_logits,
1708
+ decoder_hidden_states=outputs.decoder_hidden_states,
1709
+ decoder_attentions=outputs.decoder_attentions,
1710
+ cross_attentions=outputs.cross_attentions,
1711
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1712
+ encoder_hidden_states=outputs.encoder_hidden_states,
1713
+ encoder_attentions=outputs.encoder_attentions,
1714
+ )
1715
+
1716
+
1717
+ @add_start_docstrings(
1718
+ """
1719
+ BART Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1720
+ layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1721
+ """,
1722
+ BART_START_DOCSTRING,
1723
+ )
1724
+ class FlaxBartForQuestionAnswering(FlaxBartPreTrainedModel):
1725
+ module_class = FlaxBartForQuestionAnsweringModule
1726
+ dtype = jnp.float32
1727
+
1728
+
1729
+ append_call_sample_docstring(
1730
+ FlaxBartForQuestionAnswering,
1731
+ _CHECKPOINT_FOR_DOC,
1732
+ FlaxSeq2SeqQuestionAnsweringModelOutput,
1733
+ _CONFIG_FOR_DOC,
1734
+ )
1735
+
1736
+
1737
+ class FlaxBartDecoderPreTrainedModel(FlaxPreTrainedModel):
1738
+ config_class = BartConfig
1739
+ base_model_prefix: str = "model"
1740
+ module_class: nn.Module = None
1741
+
1742
+ def __init__(
1743
+ self,
1744
+ config: BartConfig,
1745
+ input_shape: Tuple[int] = (1, 1),
1746
+ seed: int = 0,
1747
+ dtype: jnp.dtype = jnp.float32,
1748
+ _do_init: bool = True,
1749
+ **kwargs,
1750
+ ):
1751
+ config.is_decoder = True
1752
+ config.is_encoder_decoder = False
1753
+ module = self.module_class(config=config, dtype=dtype, **kwargs)
1754
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
1755
+
1756
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
1757
+ # init input tensors
1758
+ input_ids = jnp.zeros(input_shape, dtype="i4")
1759
+ attention_mask = jnp.ones_like(input_ids)
1760
+
1761
+ batch_size, sequence_length = input_ids.shape
1762
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
1763
+
1764
+ params_rng, dropout_rng = jax.random.split(rng)
1765
+ rngs = {"params": params_rng, "dropout": dropout_rng}
1766
+ encoder_hidden_states = jnp.zeros(input_shape + (self.config.d_model,))
1767
+ encoder_attention_mask = attention_mask
1768
+ module_init_outputs = self.module.init(
1769
+ rngs,
1770
+ input_ids,
1771
+ attention_mask,
1772
+ position_ids,
1773
+ encoder_hidden_states,
1774
+ encoder_attention_mask,
1775
+ return_dict=False,
1776
+ )
1777
+ return module_init_outputs["params"]
1778
+
1779
+ def init_cache(self, batch_size, max_length):
1780
+ r"""
1781
+ Args:
1782
+ batch_size (`int`):
1783
+ batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
1784
+ max_length (`int`):
1785
+ maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
1786
+ cache.
1787
+ """
1788
+ # init input variables to retrieve cache
1789
+ input_ids = jnp.ones((batch_size, max_length), dtype="i4")
1790
+ attention_mask = jnp.ones_like(input_ids, dtype="i4")
1791
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
1792
+
1793
+ init_variables = self.module.init(
1794
+ jax.random.PRNGKey(0), input_ids, attention_mask, position_ids, return_dict=False, init_cache=True
1795
+ )
1796
+ return unfreeze(init_variables["cache"])
1797
+
1798
+ @add_start_docstrings_to_model_forward(BART_DECODE_INPUTS_DOCSTRING)
1799
+ def __call__(
1800
+ self,
1801
+ input_ids: jnp.ndarray,
1802
+ attention_mask: Optional[jnp.ndarray] = None,
1803
+ position_ids: Optional[jnp.ndarray] = None,
1804
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
1805
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
1806
+ output_attentions: Optional[bool] = None,
1807
+ output_hidden_states: Optional[bool] = None,
1808
+ return_dict: Optional[bool] = None,
1809
+ train: bool = False,
1810
+ params: dict = None,
1811
+ past_key_values: dict = None,
1812
+ dropout_rng: PRNGKey = None,
1813
+ ):
1814
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1815
+ output_hidden_states = (
1816
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1817
+ )
1818
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1819
+
1820
+ if encoder_hidden_states is not None and encoder_attention_mask is None:
1821
+ batch_size, sequence_length = encoder_hidden_states.shape[:2]
1822
+ encoder_attention_mask = jnp.ones((batch_size, sequence_length))
1823
+
1824
+ # prepare decoder inputs
1825
+ if attention_mask is None:
1826
+ attention_mask = jnp.ones_like(input_ids)
1827
+ if position_ids is None:
1828
+ batch_size, sequence_length = input_ids.shape
1829
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
1830
+
1831
+ # Handle any PRNG if needed
1832
+ rngs = {"dropout": dropout_rng} if dropout_rng is not None else {}
1833
+
1834
+ inputs = {"params": params or self.params}
1835
+
1836
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be passed
1837
+ # down to ensure cache is used. It has to be made sure that cache is marked as mutable so that it can be
1838
+ # changed by FlaxBartAttention module
1839
+ if past_key_values:
1840
+ inputs["cache"] = past_key_values
1841
+ mutable = ["cache"]
1842
+ else:
1843
+ mutable = False
1844
+
1845
+ outputs = self.module.apply(
1846
+ inputs,
1847
+ input_ids=jnp.array(input_ids, dtype="i4"),
1848
+ attention_mask=jnp.array(attention_mask, dtype="i4"),
1849
+ position_ids=jnp.array(position_ids, dtype="i4"),
1850
+ encoder_hidden_states=encoder_hidden_states,
1851
+ encoder_attention_mask=encoder_attention_mask,
1852
+ output_attentions=output_attentions,
1853
+ output_hidden_states=output_hidden_states,
1854
+ return_dict=return_dict,
1855
+ deterministic=not train,
1856
+ rngs=rngs,
1857
+ mutable=mutable,
1858
+ )
1859
+
1860
+ # add updated cache to model output
1861
+ if past_key_values is not None and return_dict:
1862
+ outputs, past_key_values = outputs
1863
+ outputs["past_key_values"] = unfreeze(past_key_values["cache"])
1864
+ return outputs
1865
+ elif past_key_values is not None and not return_dict:
1866
+ outputs, past_key_values = outputs
1867
+ outputs = outputs[:1] + (unfreeze(past_key_values["cache"]),) + outputs[1:]
1868
+
1869
+ return outputs
1870
+
1871
+
1872
+ class FlaxBartDecoderWrapper(nn.Module):
1873
+ """
1874
+ This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
1875
+ used in combination with the [`EncoderDecoderModel`] framework.
1876
+ """
1877
+
1878
+ config: BartConfig
1879
+ dtype: jnp.dtype = jnp.float32
1880
+
1881
+ def setup(self):
1882
+ embed_dim = self.config.d_model
1883
+ embed_tokens = nn.Embed(
1884
+ self.config.vocab_size,
1885
+ embed_dim,
1886
+ embedding_init=jax.nn.initializers.normal(self.config.init_std),
1887
+ dtype=self.dtype,
1888
+ )
1889
+ self.decoder = FlaxBartDecoder(config=self.config, embed_tokens=embed_tokens, dtype=self.dtype)
1890
+
1891
+ def __call__(self, *args, **kwargs):
1892
+ return self.decoder(*args, **kwargs)
1893
+
1894
+
1895
+ class FlaxBartForCausalLMModule(nn.Module):
1896
+ config: BartConfig
1897
+ dtype: jnp.dtype = jnp.float32
1898
+
1899
+ def setup(self):
1900
+ self.model = FlaxBartDecoderWrapper(config=self.config, dtype=self.dtype)
1901
+ self.lm_head = nn.Dense(
1902
+ self.config.vocab_size,
1903
+ use_bias=False,
1904
+ dtype=self.dtype,
1905
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
1906
+ )
1907
+
1908
+ def __call__(
1909
+ self,
1910
+ input_ids,
1911
+ attention_mask,
1912
+ position_ids,
1913
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
1914
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
1915
+ init_cache: bool = False,
1916
+ output_attentions: bool = False,
1917
+ output_hidden_states: bool = False,
1918
+ return_dict: bool = True,
1919
+ deterministic: bool = True,
1920
+ ):
1921
+ outputs = self.model(
1922
+ input_ids,
1923
+ attention_mask,
1924
+ position_ids,
1925
+ encoder_hidden_states,
1926
+ encoder_attention_mask,
1927
+ deterministic=deterministic,
1928
+ init_cache=init_cache,
1929
+ output_attentions=output_attentions,
1930
+ output_hidden_states=output_hidden_states,
1931
+ return_dict=return_dict,
1932
+ )
1933
+
1934
+ hidden_states = outputs[0]
1935
+
1936
+ if self.config.tie_word_embeddings:
1937
+ shared_embedding = self.model.variables["params"]["decoder"]["embed_tokens"]["embedding"]
1938
+ lm_logits = self.lm_head.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
1939
+ else:
1940
+ lm_logits = self.lm_head(hidden_states)
1941
+
1942
+ if not return_dict:
1943
+ return (lm_logits,) + outputs[1:]
1944
+
1945
+ return FlaxCausalLMOutputWithCrossAttentions(
1946
+ logits=lm_logits,
1947
+ hidden_states=outputs.hidden_states,
1948
+ attentions=outputs.attentions,
1949
+ cross_attentions=outputs.cross_attentions,
1950
+ )
1951
+
1952
+
1953
+ @add_start_docstrings(
1954
+ """
1955
+ Bart Decoder Model with a language modeling head on top (linear layer with weights tied to the input embeddings)
1956
+ e.g for autoregressive tasks.
1957
+ """,
1958
+ BART_START_DOCSTRING,
1959
+ )
1960
+ class FlaxBartForCausalLM(FlaxBartDecoderPreTrainedModel):
1961
+ module_class = FlaxBartForCausalLMModule
1962
+
1963
+ def prepare_inputs_for_generation(self, input_ids, max_length, attention_mask: Optional[jax.Array] = None):
1964
+ # initializing the cache
1965
+ batch_size, seq_length = input_ids.shape
1966
+
1967
+ past_key_values = self.init_cache(batch_size, max_length)
1968
+ # Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
1969
+ # But since the decoder uses a causal mask, those positions are masked anyway.
1970
+ # Thus, we can create a single static attention_mask here, which is more efficient for compilation
1971
+ extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
1972
+ if attention_mask is not None:
1973
+ position_ids = attention_mask.cumsum(axis=-1) - 1
1974
+ extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, attention_mask, (0, 0))
1975
+ else:
1976
+ position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
1977
+
1978
+ return {
1979
+ "past_key_values": past_key_values,
1980
+ "attention_mask": extended_attention_mask,
1981
+ "position_ids": position_ids,
1982
+ }
1983
+
1984
+ def update_inputs_for_generation(self, model_outputs, model_kwargs):
1985
+ model_kwargs["past_key_values"] = model_outputs.past_key_values
1986
+ model_kwargs["position_ids"] = model_kwargs["position_ids"][:, -1:] + 1
1987
+ return model_kwargs
1988
+
1989
+
1990
+ append_call_sample_docstring(
1991
+ FlaxBartForCausalLM,
1992
+ _CHECKPOINT_FOR_DOC,
1993
+ FlaxCausalLMOutputWithCrossAttentions,
1994
+ _CONFIG_FOR_DOC,
1995
+ )
1996
+
1997
+
1998
+ __all__ = [
1999
+ "FlaxBartDecoderPreTrainedModel",
2000
+ "FlaxBartForCausalLM",
2001
+ "FlaxBartForConditionalGeneration",
2002
+ "FlaxBartForQuestionAnswering",
2003
+ "FlaxBartForSequenceClassification",
2004
+ "FlaxBartModel",
2005
+ "FlaxBartPreTrainedModel",
2006
+ ]
lib/python3.12/site-packages/transformers/models/bart/modeling_tf_bart.py ADDED
@@ -0,0 +1,1714 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Fairseq 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
+ """TF 2.0 Bart model."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import random
20
+ from typing import Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+ import tensorflow as tf
24
+
25
+ from ...activations_tf import get_tf_activation
26
+ from ...modeling_tf_outputs import (
27
+ TFBaseModelOutput,
28
+ TFBaseModelOutputWithPastAndCrossAttentions,
29
+ TFSeq2SeqLMOutput,
30
+ TFSeq2SeqModelOutput,
31
+ TFSeq2SeqSequenceClassifierOutput,
32
+ )
33
+
34
+ # Public API
35
+ from ...modeling_tf_utils import (
36
+ TFCausalLanguageModelingLoss,
37
+ TFModelInputType,
38
+ TFPreTrainedModel,
39
+ TFSequenceClassificationLoss,
40
+ keras,
41
+ keras_serializable,
42
+ unpack_inputs,
43
+ )
44
+ from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
45
+ from ...utils import (
46
+ add_code_sample_docstrings,
47
+ add_end_docstrings,
48
+ add_start_docstrings,
49
+ add_start_docstrings_to_model_forward,
50
+ logging,
51
+ replace_return_docstrings,
52
+ )
53
+ from .configuration_bart import BartConfig
54
+
55
+
56
+ logger = logging.get_logger(__name__)
57
+
58
+ _CHECKPOINT_FOR_DOC = "facebook/bart-large"
59
+ _CONFIG_FOR_DOC = "BartConfig"
60
+
61
+
62
+ LARGE_NEGATIVE = -1e8
63
+
64
+
65
+ def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int, decoder_start_token_id: int):
66
+ pad_token_id = tf.cast(pad_token_id, input_ids.dtype)
67
+ decoder_start_token_id = tf.cast(decoder_start_token_id, input_ids.dtype)
68
+ start_tokens = tf.fill(
69
+ (shape_list(input_ids)[0], 1), tf.convert_to_tensor(decoder_start_token_id, input_ids.dtype)
70
+ )
71
+ shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1)
72
+ # replace possible -100 values in labels by `pad_token_id`
73
+ shifted_input_ids = tf.where(
74
+ shifted_input_ids == -100,
75
+ tf.fill(shape_list(shifted_input_ids), tf.convert_to_tensor(pad_token_id, input_ids.dtype)),
76
+ shifted_input_ids,
77
+ )
78
+
79
+ # "Verify that `labels` has only positive values and -100"
80
+ assert_gte0 = tf.debugging.assert_greater_equal(shifted_input_ids, tf.constant(0, dtype=input_ids.dtype))
81
+
82
+ # Make sure the assertion op is called by wrapping the result in an identity no-op
83
+ with tf.control_dependencies([assert_gte0]):
84
+ shifted_input_ids = tf.identity(shifted_input_ids)
85
+
86
+ return shifted_input_ids
87
+
88
+
89
+ def _make_causal_mask(input_ids_shape: tf.TensorShape, past_key_values_length: int = 0):
90
+ """
91
+ Make causal mask used for bi-directional self-attention.
92
+ """
93
+ bsz = input_ids_shape[0]
94
+ tgt_len = input_ids_shape[1]
95
+ mask = tf.ones((tgt_len, tgt_len)) * LARGE_NEGATIVE
96
+ mask_cond = tf.range(shape_list(mask)[-1])
97
+
98
+ mask = tf.where(mask_cond < tf.reshape(mask_cond + 1, (shape_list(mask)[-1], 1)), 0.0, mask)
99
+
100
+ if past_key_values_length > 0:
101
+ mask = tf.concat([tf.zeros((tgt_len, past_key_values_length)), mask], axis=-1)
102
+
103
+ return tf.tile(mask[None, None, :, :], (bsz, 1, 1, 1))
104
+
105
+
106
+ def _expand_mask(mask: tf.Tensor, tgt_len: Optional[int] = None):
107
+ """
108
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
109
+ """
110
+ src_len = shape_list(mask)[1]
111
+ tgt_len = tgt_len if tgt_len is not None else src_len
112
+ one_cst = tf.constant(1.0)
113
+ mask = tf.cast(mask, dtype=one_cst.dtype)
114
+ expanded_mask = tf.tile(mask[:, None, None, :], (1, 1, tgt_len, 1))
115
+
116
+ return (one_cst - expanded_mask) * LARGE_NEGATIVE
117
+
118
+
119
+ class TFBartLearnedPositionalEmbedding(keras.layers.Embedding):
120
+ """
121
+ This module learns positional embeddings up to a fixed maximum size.
122
+ """
123
+
124
+ def __init__(self, num_embeddings: int, embedding_dim: int, **kwargs):
125
+ # Bart is set up so that if padding_idx is specified then offset the embedding ids by 2
126
+ # and adjust num_embeddings appropriately. Other models don't have this hack
127
+ self.offset = 2
128
+ super().__init__(num_embeddings + self.offset, embedding_dim, **kwargs)
129
+
130
+ def call(
131
+ self,
132
+ input_shape: Optional[tf.TensorShape] = None,
133
+ past_key_values_length: int = 0,
134
+ position_ids: tf.Tensor | None = None,
135
+ ):
136
+ """Input is expected to be of size [bsz x seqlen]."""
137
+ if position_ids is None:
138
+ seq_len = input_shape[1]
139
+ position_ids = tf.range(seq_len, delta=1, name="range")
140
+ position_ids += past_key_values_length
141
+
142
+ offset_dtype = position_ids.dtype if isinstance(position_ids, tf.Tensor) else tf.int32
143
+ return super().call(position_ids + tf.constant(self.offset, dtype=offset_dtype))
144
+
145
+
146
+ class TFBartAttention(keras.layers.Layer):
147
+ """Multi-headed attention from "Attention Is All You Need"""
148
+
149
+ def __init__(
150
+ self,
151
+ embed_dim: int,
152
+ num_heads: int,
153
+ dropout: float = 0.0,
154
+ is_decoder: bool = False,
155
+ bias: bool = True,
156
+ **kwargs,
157
+ ):
158
+ super().__init__(**kwargs)
159
+ self.embed_dim = embed_dim
160
+
161
+ self.num_heads = num_heads
162
+ self.dropout = keras.layers.Dropout(dropout)
163
+ self.head_dim = embed_dim // num_heads
164
+ if (self.head_dim * num_heads) != self.embed_dim:
165
+ raise ValueError(
166
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
167
+ f" and `num_heads`: {num_heads})."
168
+ )
169
+ self.scaling = self.head_dim**-0.5
170
+ self.is_decoder = is_decoder
171
+
172
+ self.k_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="k_proj")
173
+ self.q_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="q_proj")
174
+ self.v_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="v_proj")
175
+ self.out_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="out_proj")
176
+
177
+ def _shape(self, tensor: tf.Tensor, seq_len: int, bsz: int):
178
+ return tf.transpose(tf.reshape(tensor, (bsz, seq_len, self.num_heads, self.head_dim)), (0, 2, 1, 3))
179
+
180
+ def call(
181
+ self,
182
+ hidden_states: tf.Tensor,
183
+ key_value_states: tf.Tensor | None = None,
184
+ past_key_value: Tuple[Tuple[tf.Tensor]] | None = None,
185
+ attention_mask: tf.Tensor | None = None,
186
+ layer_head_mask: tf.Tensor | None = None,
187
+ training: Optional[bool] = False,
188
+ ) -> Tuple[tf.Tensor, tf.Tensor | None]:
189
+ """Input shape: Batch x Time x Channel"""
190
+
191
+ # if key_value_states are provided this layer is used as a cross-attention layer
192
+ # for the decoder
193
+ is_cross_attention = key_value_states is not None
194
+ bsz, tgt_len, embed_dim = shape_list(hidden_states)
195
+
196
+ # get query proj
197
+ query_states = self.q_proj(hidden_states) * self.scaling
198
+ # get key, value proj
199
+ if is_cross_attention and past_key_value is not None:
200
+ # reuse k,v, cross_attentions
201
+ key_states = past_key_value[0]
202
+ value_states = past_key_value[1]
203
+ elif is_cross_attention:
204
+ # cross_attentions
205
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
206
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
207
+ elif past_key_value is not None:
208
+ # reuse k, v, self_attention
209
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
210
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
211
+ key_states = tf.concat([past_key_value[0], key_states], axis=2)
212
+ value_states = tf.concat([past_key_value[1], value_states], axis=2)
213
+ else:
214
+ # self_attention
215
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
216
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
217
+
218
+ if self.is_decoder:
219
+ # if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
220
+ # Further calls to cross_attention layer can then reuse all cross-attention
221
+ # key/value_states (first "if" case)
222
+ # if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
223
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
224
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
225
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
226
+ past_key_value = (key_states, value_states)
227
+
228
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
229
+ query_states = tf.reshape(self._shape(query_states, tgt_len, bsz), proj_shape)
230
+ key_states = tf.reshape(key_states, proj_shape)
231
+ value_states = tf.reshape(value_states, proj_shape)
232
+
233
+ src_len = shape_list(key_states)[1]
234
+ attn_weights = tf.matmul(query_states, key_states, transpose_b=True)
235
+
236
+ tf.debugging.assert_equal(
237
+ shape_list(attn_weights),
238
+ [bsz * self.num_heads, tgt_len, src_len],
239
+ message=(
240
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
241
+ f" {shape_list(attn_weights)}"
242
+ ),
243
+ )
244
+
245
+ if attention_mask is not None:
246
+ tf.debugging.assert_equal(
247
+ shape_list(attention_mask),
248
+ [bsz, 1, tgt_len, src_len],
249
+ message=(
250
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
251
+ f" {shape_list(attention_mask)}"
252
+ ),
253
+ )
254
+
255
+ attention_mask = tf.cast(attention_mask, dtype=attn_weights.dtype)
256
+ attn_weights = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) + attention_mask
257
+ attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
258
+
259
+ attn_weights = stable_softmax(attn_weights, axis=-1)
260
+
261
+ if layer_head_mask is not None:
262
+ tf.debugging.assert_equal(
263
+ shape_list(layer_head_mask),
264
+ [self.num_heads],
265
+ message=(
266
+ f"Head mask for a single layer should be of size {(self.num_heads)}, but is"
267
+ f" {shape_list(layer_head_mask)}"
268
+ ),
269
+ )
270
+
271
+ attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape(
272
+ attn_weights, (bsz, self.num_heads, tgt_len, src_len)
273
+ )
274
+ attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
275
+
276
+ attn_probs = self.dropout(attn_weights, training=training)
277
+ attn_output = tf.matmul(attn_probs, value_states)
278
+
279
+ tf.debugging.assert_equal(
280
+ shape_list(attn_output),
281
+ [bsz * self.num_heads, tgt_len, self.head_dim],
282
+ message=(
283
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
284
+ f" {shape_list(attn_output)}"
285
+ ),
286
+ )
287
+
288
+ attn_output = tf.transpose(
289
+ tf.reshape(attn_output, (bsz, self.num_heads, tgt_len, self.head_dim)), (0, 2, 1, 3)
290
+ )
291
+ attn_output = tf.reshape(attn_output, (bsz, tgt_len, embed_dim))
292
+
293
+ attn_output = self.out_proj(attn_output)
294
+ attn_weights: tf.Tensor = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len))
295
+
296
+ return attn_output, attn_weights, past_key_value
297
+
298
+ def build(self, input_shape=None):
299
+ if self.built:
300
+ return
301
+ self.built = True
302
+ if getattr(self, "k_proj", None) is not None:
303
+ with tf.name_scope(self.k_proj.name):
304
+ self.k_proj.build([None, None, self.embed_dim])
305
+ if getattr(self, "q_proj", None) is not None:
306
+ with tf.name_scope(self.q_proj.name):
307
+ self.q_proj.build([None, None, self.embed_dim])
308
+ if getattr(self, "v_proj", None) is not None:
309
+ with tf.name_scope(self.v_proj.name):
310
+ self.v_proj.build([None, None, self.embed_dim])
311
+ if getattr(self, "out_proj", None) is not None:
312
+ with tf.name_scope(self.out_proj.name):
313
+ self.out_proj.build([None, None, self.embed_dim])
314
+
315
+
316
+ class TFBartEncoderLayer(keras.layers.Layer):
317
+ def __init__(self, config: BartConfig, **kwargs):
318
+ super().__init__(**kwargs)
319
+ self.embed_dim = config.d_model
320
+ self.self_attn = TFBartAttention(
321
+ self.embed_dim, config.encoder_attention_heads, dropout=config.attention_dropout, name="self_attn"
322
+ )
323
+ self.self_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
324
+ self.dropout = keras.layers.Dropout(config.dropout)
325
+ self.activation_fn = get_tf_activation(config.activation_function)
326
+ self.activation_dropout = keras.layers.Dropout(config.activation_dropout)
327
+ self.fc1 = keras.layers.Dense(config.encoder_ffn_dim, name="fc1")
328
+ self.fc2 = keras.layers.Dense(self.embed_dim, name="fc2")
329
+ self.final_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
330
+ self.config = config
331
+
332
+ def call(
333
+ self,
334
+ hidden_states: tf.Tensor,
335
+ attention_mask: np.ndarray | tf.Tensor | None,
336
+ layer_head_mask: tf.Tensor | None,
337
+ training: Optional[bool] = False,
338
+ ) -> tf.Tensor:
339
+ """
340
+ Args:
341
+ hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
342
+ attention_mask (`tf.Tensor`): attention mask of size
343
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
344
+ layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
345
+ `(encoder_attention_heads,)`
346
+ """
347
+ residual = hidden_states
348
+ hidden_states, self_attn_weights, _ = self.self_attn(
349
+ hidden_states=hidden_states, attention_mask=attention_mask, layer_head_mask=layer_head_mask
350
+ )
351
+
352
+ tf.debugging.assert_equal(
353
+ shape_list(hidden_states),
354
+ shape_list(residual),
355
+ message=f"Self attn modified the shape of query {shape_list(residual)} to {shape_list(hidden_states)}",
356
+ )
357
+
358
+ hidden_states = self.dropout(hidden_states, training=training)
359
+ hidden_states = residual + hidden_states
360
+ hidden_states = self.self_attn_layer_norm(hidden_states)
361
+
362
+ residual = hidden_states
363
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
364
+ hidden_states = self.activation_dropout(hidden_states, training=training)
365
+ hidden_states = self.fc2(hidden_states)
366
+ hidden_states = self.dropout(hidden_states, training=training)
367
+ hidden_states = residual + hidden_states
368
+ hidden_states = self.final_layer_norm(hidden_states)
369
+
370
+ return hidden_states, self_attn_weights
371
+
372
+ def build(self, input_shape=None):
373
+ if self.built:
374
+ return
375
+ self.built = True
376
+ if getattr(self, "self_attn", None) is not None:
377
+ with tf.name_scope(self.self_attn.name):
378
+ self.self_attn.build(None)
379
+ if getattr(self, "self_attn_layer_norm", None) is not None:
380
+ with tf.name_scope(self.self_attn_layer_norm.name):
381
+ self.self_attn_layer_norm.build([None, None, self.embed_dim])
382
+ if getattr(self, "fc1", None) is not None:
383
+ with tf.name_scope(self.fc1.name):
384
+ self.fc1.build([None, None, self.embed_dim])
385
+ if getattr(self, "fc2", None) is not None:
386
+ with tf.name_scope(self.fc2.name):
387
+ self.fc2.build([None, None, self.config.encoder_ffn_dim])
388
+ if getattr(self, "final_layer_norm", None) is not None:
389
+ with tf.name_scope(self.final_layer_norm.name):
390
+ self.final_layer_norm.build([None, None, self.embed_dim])
391
+
392
+
393
+ class TFBartDecoderLayer(keras.layers.Layer):
394
+ def __init__(self, config: BartConfig, **kwargs):
395
+ super().__init__(**kwargs)
396
+ self.embed_dim = config.d_model
397
+ self.self_attn = TFBartAttention(
398
+ embed_dim=self.embed_dim,
399
+ num_heads=config.decoder_attention_heads,
400
+ dropout=config.attention_dropout,
401
+ name="self_attn",
402
+ is_decoder=True,
403
+ )
404
+ self.dropout = keras.layers.Dropout(config.dropout)
405
+ self.activation_fn = get_tf_activation(config.activation_function)
406
+ self.activation_dropout = keras.layers.Dropout(config.activation_dropout)
407
+
408
+ self.self_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
409
+ self.encoder_attn = TFBartAttention(
410
+ self.embed_dim,
411
+ config.decoder_attention_heads,
412
+ dropout=config.attention_dropout,
413
+ name="encoder_attn",
414
+ is_decoder=True,
415
+ )
416
+ self.encoder_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="encoder_attn_layer_norm")
417
+ self.fc1 = keras.layers.Dense(config.decoder_ffn_dim, name="fc1")
418
+ self.fc2 = keras.layers.Dense(self.embed_dim, name="fc2")
419
+ self.final_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
420
+ self.config = config
421
+
422
+ def call(
423
+ self,
424
+ hidden_states: tf.Tensor,
425
+ attention_mask: np.ndarray | tf.Tensor | None = None,
426
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
427
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
428
+ layer_head_mask: tf.Tensor | None = None,
429
+ cross_attn_layer_head_mask: tf.Tensor | None = None,
430
+ past_key_value: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
431
+ training: Optional[bool] = False,
432
+ ) -> Tuple[tf.Tensor, tf.Tensor, Tuple[Tuple[tf.Tensor]]]:
433
+ """
434
+ Args:
435
+ hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
436
+ attention_mask (`tf.Tensor`): attention mask of size
437
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
438
+ encoder_hidden_states (`tf.Tensor`):
439
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
440
+ encoder_attention_mask (`tf.Tensor`): encoder attention mask of size
441
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
442
+ layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
443
+ `(decoder_attention_heads,)`
444
+ cross_attn_layer_head_mask (`tf.Tensor`): mask for heads of the cross-attention module.
445
+ `(decoder_attention_heads,)`
446
+ past_key_value (`Tuple(tf.Tensor)`): cached past key and value projection states
447
+ """
448
+ residual = hidden_states
449
+
450
+ # Self Attention
451
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
452
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
453
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
454
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
455
+ hidden_states=hidden_states,
456
+ past_key_value=self_attn_past_key_value,
457
+ attention_mask=attention_mask,
458
+ layer_head_mask=layer_head_mask,
459
+ )
460
+ hidden_states = self.dropout(hidden_states, training=training)
461
+ hidden_states = residual + hidden_states
462
+ hidden_states = self.self_attn_layer_norm(hidden_states)
463
+
464
+ # Cross-Attention Block
465
+ cross_attn_present_key_value = None
466
+ cross_attn_weights = None
467
+ if encoder_hidden_states is not None:
468
+ residual = hidden_states
469
+
470
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
471
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
472
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
473
+ hidden_states=hidden_states,
474
+ key_value_states=encoder_hidden_states,
475
+ attention_mask=encoder_attention_mask,
476
+ layer_head_mask=cross_attn_layer_head_mask,
477
+ past_key_value=cross_attn_past_key_value,
478
+ )
479
+ hidden_states = self.dropout(hidden_states, training=training)
480
+ hidden_states = residual + hidden_states
481
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
482
+
483
+ # add cross-attn to positions 3,4 of present_key_value tuple
484
+ present_key_value = present_key_value + cross_attn_present_key_value
485
+
486
+ # Fully Connected
487
+ residual = hidden_states
488
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
489
+ hidden_states = self.activation_dropout(hidden_states, training=training)
490
+ hidden_states = self.fc2(hidden_states)
491
+ hidden_states = self.dropout(hidden_states, training=training)
492
+ hidden_states = residual + hidden_states
493
+ hidden_states = self.final_layer_norm(hidden_states)
494
+
495
+ return (
496
+ hidden_states,
497
+ self_attn_weights,
498
+ cross_attn_weights,
499
+ present_key_value,
500
+ )
501
+
502
+ def build(self, input_shape=None):
503
+ if self.built:
504
+ return
505
+ self.built = True
506
+ if getattr(self, "self_attn", None) is not None:
507
+ with tf.name_scope(self.self_attn.name):
508
+ self.self_attn.build(None)
509
+ if getattr(self, "self_attn_layer_norm", None) is not None:
510
+ with tf.name_scope(self.self_attn_layer_norm.name):
511
+ self.self_attn_layer_norm.build([None, None, self.embed_dim])
512
+ if getattr(self, "encoder_attn", None) is not None:
513
+ with tf.name_scope(self.encoder_attn.name):
514
+ self.encoder_attn.build(None)
515
+ if getattr(self, "encoder_attn_layer_norm", None) is not None:
516
+ with tf.name_scope(self.encoder_attn_layer_norm.name):
517
+ self.encoder_attn_layer_norm.build([None, None, self.embed_dim])
518
+ if getattr(self, "fc1", None) is not None:
519
+ with tf.name_scope(self.fc1.name):
520
+ self.fc1.build([None, None, self.embed_dim])
521
+ if getattr(self, "fc2", None) is not None:
522
+ with tf.name_scope(self.fc2.name):
523
+ self.fc2.build([None, None, self.config.decoder_ffn_dim])
524
+ if getattr(self, "final_layer_norm", None) is not None:
525
+ with tf.name_scope(self.final_layer_norm.name):
526
+ self.final_layer_norm.build([None, None, self.embed_dim])
527
+
528
+
529
+ class TFBartClassificationHead(keras.layers.Layer):
530
+ """Head for sentence-level classification tasks."""
531
+
532
+ def __init__(self, inner_dim: int, num_classes: int, pooler_dropout: float, name: str, **kwargs):
533
+ super().__init__(name=name, **kwargs)
534
+ self.dense = keras.layers.Dense(inner_dim, name="dense")
535
+ self.dropout = keras.layers.Dropout(pooler_dropout)
536
+ self.out_proj = keras.layers.Dense(num_classes, name="out_proj")
537
+ self.input_dim = inner_dim
538
+ self.inner_dim = inner_dim
539
+
540
+ def call(self, inputs):
541
+ hidden_states = self.dropout(inputs)
542
+ hidden_states = self.dense(hidden_states)
543
+ hidden_states = keras.activations.tanh(hidden_states)
544
+ hidden_states = self.dropout(hidden_states)
545
+ hidden_states = self.out_proj(hidden_states)
546
+ return hidden_states
547
+
548
+ def build(self, input_shape=None):
549
+ if self.built:
550
+ return
551
+ self.built = True
552
+ if getattr(self, "dense", None) is not None:
553
+ with tf.name_scope(self.dense.name):
554
+ self.dense.build([None, None, self.input_dim])
555
+ if getattr(self, "out_proj", None) is not None:
556
+ with tf.name_scope(self.out_proj.name):
557
+ self.out_proj.build([None, None, self.inner_dim])
558
+
559
+
560
+ class TFBartPretrainedModel(TFPreTrainedModel):
561
+ config_class = BartConfig
562
+ base_model_prefix = "model"
563
+
564
+ @property
565
+ def dummy_inputs(self):
566
+ dummy_inputs = super().dummy_inputs
567
+ # Dummy inputs should not contain the default val of 1
568
+ # as this is the padding token and some assertions check it
569
+ dummy_inputs["input_ids"] = dummy_inputs["input_ids"] * 2
570
+ if "decoder_input_ids" in dummy_inputs:
571
+ dummy_inputs["decoder_input_ids"] = dummy_inputs["decoder_input_ids"] * 2
572
+ return dummy_inputs
573
+
574
+ def tf_to_pt_weight_rename(self, tf_weight):
575
+ if tf_weight == "model.shared.weight":
576
+ return tf_weight, "model.decoder.embed_tokens.weight"
577
+ else:
578
+ return (tf_weight,)
579
+
580
+
581
+ BART_START_DOCSTRING = r"""
582
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
583
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
584
+ etc.)
585
+
586
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
587
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
588
+ behavior.
589
+
590
+ <Tip>
591
+
592
+ TensorFlow models and layers in `transformers` accept two formats as input:
593
+
594
+ - having all inputs as keyword arguments (like PyTorch models), or
595
+ - having all inputs as a list, tuple or dict in the first positional argument.
596
+
597
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
598
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
599
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
600
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
601
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
602
+ positional argument:
603
+
604
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
605
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
606
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
607
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
608
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
609
+
610
+ Note that when creating models and layers with
611
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
612
+ about any of this, as you can just pass inputs like you would to any other Python function!
613
+
614
+ </Tip>
615
+
616
+ Args:
617
+ config ([`BartConfig`]): Model configuration class with all the parameters of the model.
618
+ Initializing with a config file does not load the weights associated with the model, only the
619
+ configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
620
+ """
621
+
622
+
623
+ BART_GENERATION_EXAMPLE = r"""
624
+ Summarization example:
625
+
626
+ ```python
627
+ >>> from transformers import AutoTokenizer, TFBartForConditionalGeneration
628
+
629
+ >>> model = TFBartForConditionalGeneration.from_pretrained("facebook/bart-large")
630
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large")
631
+
632
+ >>> ARTICLE_TO_SUMMARIZE = "My friends are cool but they eat too many carbs."
633
+ >>> inputs = tokenizer([ARTICLE_TO_SUMMARIZE], max_length=1024, return_tensors="tf")
634
+
635
+ >>> # Generate Summary
636
+ >>> summary_ids = model.generate(inputs["input_ids"], num_beams=4, max_length=5)
637
+ >>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False))
638
+ ```
639
+
640
+ Mask filling example:
641
+
642
+ ```python
643
+ >>> from transformers import AutoTokenizer, TFBartForConditionalGeneration
644
+
645
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large")
646
+ >>> TXT = "My friends are <mask> but they eat too many carbs."
647
+
648
+ >>> model = TFBartForConditionalGeneration.from_pretrained("facebook/bart-large")
649
+ >>> input_ids = tokenizer([TXT], return_tensors="tf")["input_ids"]
650
+ >>> logits = model(input_ids).logits
651
+ >>> probs = tf.nn.softmax(logits[0])
652
+ >>> # probs[5] is associated with the mask token
653
+ ```
654
+ """
655
+
656
+
657
+ BART_INPUTS_DOCSTRING = r"""
658
+ Args:
659
+ input_ids (`tf.Tensor` of shape `({0})`):
660
+ Indices of input sequence tokens in the vocabulary.
661
+
662
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
663
+ [`PreTrainedTokenizer.__call__`] for details.
664
+
665
+ [What are input IDs?](../glossary#input-ids)
666
+ attention_mask (`tf.Tensor` of shape `({0})`, *optional*):
667
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
668
+
669
+ - 1 for tokens that are **not masked**,
670
+ - 0 for tokens that are **masked**.
671
+
672
+ [What are attention masks?](../glossary#attention-mask)
673
+ decoder_input_ids (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
674
+ Indices of decoder input sequence tokens in the vocabulary.
675
+
676
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
677
+ [`PreTrainedTokenizer.__call__`] for details.
678
+
679
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
680
+
681
+ Bart uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
682
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
683
+
684
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
685
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
686
+ for denoising pre-training following the paper.
687
+ decoder_attention_mask (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
688
+ will be made by default and ignore pad tokens. It is not recommended to set this for most use cases.
689
+ decoder_position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
690
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
691
+ range `[0, config.max_position_embeddings - 1]`.
692
+ head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
693
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
694
+
695
+ - 1 indicates the head is **not masked**,
696
+ - 0 indicates the head is **masked**.
697
+
698
+ decoder_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
699
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
700
+
701
+ - 1 indicates the head is **not masked**,
702
+ - 0 indicates the head is **masked**.
703
+
704
+ cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
705
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
706
+
707
+ - 1 indicates the head is **not masked**,
708
+ - 0 indicates the head is **masked**.
709
+
710
+ encoder_outputs (`tf.FloatTensor`, *optional*):
711
+ hidden states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
712
+ of shape `(batch_size, sequence_length, hidden_size)` is a sequence of
713
+ past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
714
+ contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
715
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
716
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
717
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
718
+ inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
719
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
720
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
721
+ than the model's internal embedding lookup matrix.
722
+ use_cache (`bool`, *optional*, defaults to `True`):
723
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
724
+ `past_key_values`). Set to `False` during training, `True` during generation
725
+ output_attentions (`bool`, *optional*):
726
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
727
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
728
+ config will be used instead.
729
+ output_hidden_states (`bool`, *optional*):
730
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
731
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
732
+ used instead.
733
+ return_dict (`bool`, *optional*):
734
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
735
+ eager mode, in graph mode the value will always be set to True.
736
+ training (`bool`, *optional*, defaults to `False`):
737
+ Whether or not to use the model in training mode (some modules like dropout modules have different
738
+ behaviors between training and evaluation).
739
+ """
740
+
741
+
742
+ @keras_serializable
743
+ class TFBartEncoder(keras.layers.Layer):
744
+ config_class = BartConfig
745
+ """
746
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
747
+ [`TFBartEncoderLayer`].
748
+
749
+ Args:
750
+ config: BartConfig
751
+ """
752
+
753
+ def __init__(self, config: BartConfig, embed_tokens: Optional[keras.layers.Embedding] = None, **kwargs):
754
+ super().__init__(**kwargs)
755
+ self.config = config
756
+ self.dropout = keras.layers.Dropout(config.dropout)
757
+ self.layerdrop = config.encoder_layerdrop
758
+ self.padding_idx = config.pad_token_id
759
+ self.max_source_positions = config.max_position_embeddings
760
+ self.embed_scale = tf.math.sqrt(float(config.d_model)) if config.scale_embedding else 1.0
761
+
762
+ self.embed_tokens = embed_tokens
763
+ self.embed_positions = TFBartLearnedPositionalEmbedding(
764
+ config.max_position_embeddings,
765
+ config.d_model,
766
+ name="embed_positions",
767
+ )
768
+ self.layers = [TFBartEncoderLayer(config, name=f"layers.{i}") for i in range(config.encoder_layers)]
769
+ self.layernorm_embedding = keras.layers.LayerNormalization(epsilon=1e-5, name="layernorm_embedding")
770
+ self.embed_dim = config.d_model
771
+
772
+ @unpack_inputs
773
+ def call(
774
+ self,
775
+ input_ids: TFModelInputType | None = None,
776
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
777
+ attention_mask: np.ndarray | tf.Tensor | None = None,
778
+ head_mask: np.ndarray | tf.Tensor | None = None,
779
+ output_attentions: Optional[bool] = None,
780
+ output_hidden_states: Optional[bool] = None,
781
+ return_dict: Optional[bool] = None,
782
+ training: Optional[bool] = False,
783
+ ) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:
784
+ """
785
+ Args:
786
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
787
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
788
+ provide it.
789
+
790
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
791
+ [`PreTrainedTokenizer.__call__`] for details.
792
+
793
+ [What are input IDs?](../glossary#input-ids)
794
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
795
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
796
+
797
+ - 1 for tokens that are **not masked**,
798
+ - 0 for tokens that are **masked**.
799
+
800
+ [What are attention masks?](../glossary#attention-mask)
801
+ head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, `optional):
802
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
803
+
804
+ - 1 indicates the head is **not masked**,
805
+ - 0 indicates the head is **masked**.
806
+
807
+ inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
808
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
809
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
810
+ than the model's internal embedding lookup matrix.
811
+ output_attentions (`bool`, *optional*):
812
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
813
+ returned tensors for more detail.
814
+ output_hidden_states (`bool`, *optional*):
815
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
816
+ for more detail.
817
+ return_dict (`bool`, *optional*):
818
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
819
+ """
820
+ if input_ids is not None and inputs_embeds is not None:
821
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
822
+ elif input_ids is not None:
823
+ input_shape = shape_list(input_ids)
824
+ elif inputs_embeds is not None:
825
+ input_shape = shape_list(inputs_embeds)[:-1]
826
+ else:
827
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
828
+
829
+ if inputs_embeds is None:
830
+ check_embeddings_within_bounds(input_ids, self.embed_tokens.input_dim)
831
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
832
+
833
+ embed_pos = self.embed_positions(input_shape)
834
+ hidden_states = inputs_embeds + embed_pos
835
+ hidden_states = self.layernorm_embedding(hidden_states)
836
+ hidden_states = self.dropout(hidden_states, training=training)
837
+
838
+ # check attention mask and invert
839
+ if attention_mask is not None:
840
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
841
+ attention_mask = _expand_mask(attention_mask)
842
+ else:
843
+ attention_mask = None
844
+
845
+ encoder_states = () if output_hidden_states else None
846
+ all_attentions = () if output_attentions else None
847
+
848
+ # check if head_mask has a correct number of layers specified if desired
849
+ if head_mask is not None:
850
+ tf.debugging.assert_equal(
851
+ shape_list(head_mask)[0],
852
+ len(self.layers),
853
+ message=(
854
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
855
+ f" {shape_list(head_mask)[0]}."
856
+ ),
857
+ )
858
+
859
+ # encoder layers
860
+ for idx, encoder_layer in enumerate(self.layers):
861
+ if output_hidden_states:
862
+ encoder_states = encoder_states + (hidden_states,)
863
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
864
+ dropout_probability = random.uniform(0, 1)
865
+ if training and (dropout_probability < self.layerdrop): # skip the layer
866
+ continue
867
+
868
+ hidden_states, attn = encoder_layer(
869
+ hidden_states,
870
+ attention_mask,
871
+ head_mask[idx] if head_mask is not None else None,
872
+ )
873
+
874
+ if output_attentions:
875
+ all_attentions += (attn,)
876
+
877
+ if output_hidden_states:
878
+ encoder_states = encoder_states + (hidden_states,)
879
+
880
+ if not return_dict:
881
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
882
+ return TFBaseModelOutput(
883
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
884
+ )
885
+
886
+ def build(self, input_shape=None):
887
+ if self.built:
888
+ return
889
+ self.built = True
890
+ if getattr(self, "embed_positions", None) is not None:
891
+ with tf.name_scope(self.embed_positions.name):
892
+ self.embed_positions.build(None)
893
+ if getattr(self, "layernorm_embedding", None) is not None:
894
+ with tf.name_scope(self.layernorm_embedding.name):
895
+ self.layernorm_embedding.build([None, None, self.embed_dim])
896
+ if getattr(self, "layers", None) is not None:
897
+ for layer in self.layers:
898
+ with tf.name_scope(layer.name):
899
+ layer.build(None)
900
+
901
+
902
+ @keras_serializable
903
+ class TFBartDecoder(keras.layers.Layer):
904
+ config_class = BartConfig
905
+ """
906
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`TFBartDecoderLayer`]
907
+
908
+ Args:
909
+ config: BartConfig
910
+ embed_tokens: output embedding
911
+ """
912
+
913
+ def __init__(self, config: BartConfig, embed_tokens: Optional[keras.layers.Embedding] = None, **kwargs):
914
+ super().__init__(**kwargs)
915
+ self.config = config
916
+ self.padding_idx = config.pad_token_id
917
+ self.embed_tokens = embed_tokens
918
+ self.layerdrop = config.decoder_layerdrop
919
+ self.embed_positions = TFBartLearnedPositionalEmbedding(
920
+ config.max_position_embeddings,
921
+ config.d_model,
922
+ name="embed_positions",
923
+ )
924
+ self.embed_scale = tf.math.sqrt(float(config.d_model)) if config.scale_embedding else 1.0
925
+ self.layers = [TFBartDecoderLayer(config, name=f"layers.{i}") for i in range(config.decoder_layers)]
926
+ self.layernorm_embedding = keras.layers.LayerNormalization(epsilon=1e-5, name="layernorm_embedding")
927
+
928
+ self.dropout = keras.layers.Dropout(config.dropout)
929
+
930
+ @unpack_inputs
931
+ def call(
932
+ self,
933
+ input_ids: TFModelInputType | None = None,
934
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
935
+ attention_mask: np.ndarray | tf.Tensor | None = None,
936
+ position_ids: np.ndarray | tf.Tensor | None = None,
937
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
938
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
939
+ head_mask: np.ndarray | tf.Tensor | None = None,
940
+ cross_attn_head_mask: np.ndarray | tf.Tensor | None = None,
941
+ past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
942
+ use_cache: Optional[bool] = None,
943
+ output_attentions: Optional[bool] = None,
944
+ output_hidden_states: Optional[bool] = None,
945
+ return_dict: Optional[bool] = None,
946
+ training: Optional[bool] = False,
947
+ ) -> Union[TFBaseModelOutputWithPastAndCrossAttentions, Tuple[tf.Tensor]]:
948
+ r"""
949
+ Args:
950
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
951
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
952
+ provide it.
953
+
954
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
955
+ [`PreTrainedTokenizer.__call__`] for details.
956
+
957
+ [What are input IDs?](../glossary#input-ids)
958
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
959
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
960
+
961
+ - 1 for tokens that are **not masked**,
962
+ - 0 for tokens that are **masked**.
963
+
964
+ [What are attention masks?](../glossary#attention-mask)
965
+ position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
966
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
967
+ range `[0, config.max_position_embeddings - 1]`.
968
+ encoder_hidden_states (`tf.Tensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
969
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
970
+ of the decoder.
971
+ encoder_attention_mask (`tf.Tensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
972
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
973
+ selected in `[0, 1]`:
974
+
975
+ - 1 for tokens that are **not masked**,
976
+ - 0 for tokens that are **masked**.
977
+
978
+ [What are attention masks?](../glossary#attention-mask)
979
+ head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
980
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
981
+
982
+ - 1 indicates the head is **not masked**,
983
+ - 0 indicates the head is **masked**.
984
+
985
+ cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
986
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
987
+
988
+ - 1 indicates the head is **not masked**,
989
+ - 0 indicates the head is **masked**.
990
+
991
+ past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
992
+ Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up
993
+ decoding.
994
+
995
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
996
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
997
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
998
+ inputs_embeds (`tf.tTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
999
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
1000
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
1001
+ than the model's internal embedding lookup matrix.
1002
+ output_attentions (`bool`, *optional*):
1003
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1004
+ returned tensors for more detail.
1005
+ output_hidden_states (`bool`, *optional*):
1006
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1007
+ for more detail.
1008
+ return_dict (`bool`, *optional*):
1009
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1010
+ """
1011
+
1012
+ if input_ids is not None and inputs_embeds is not None:
1013
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1014
+ elif input_ids is not None:
1015
+ input_shape = shape_list(input_ids)
1016
+ elif inputs_embeds is not None:
1017
+ input_shape = shape_list(inputs_embeds)[:-1]
1018
+ else:
1019
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1020
+
1021
+ past_key_values_length = shape_list(past_key_values[0][0])[2] if past_key_values is not None else 0
1022
+
1023
+ # embed positions
1024
+ if position_ids is None:
1025
+ positions = self.embed_positions(input_shape, past_key_values_length)
1026
+ else:
1027
+ positions = self.embed_positions(input_shape, position_ids=position_ids)
1028
+
1029
+ if inputs_embeds is None:
1030
+ check_embeddings_within_bounds(input_ids, self.embed_tokens.input_dim)
1031
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
1032
+
1033
+ hidden_states = inputs_embeds
1034
+
1035
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1036
+ if input_shape[-1] > 1:
1037
+ combined_attention_mask = _make_causal_mask(input_shape, past_key_values_length=past_key_values_length)
1038
+ else:
1039
+ combined_attention_mask = _expand_mask(
1040
+ tf.ones((input_shape[0], input_shape[1] + past_key_values_length)), tgt_len=input_shape[-1]
1041
+ )
1042
+
1043
+ if attention_mask is not None:
1044
+ combined_attention_mask = combined_attention_mask + _expand_mask(attention_mask, tgt_len=input_shape[-1])
1045
+
1046
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
1047
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1048
+ encoder_attention_mask = _expand_mask(encoder_attention_mask, tgt_len=input_shape[-1])
1049
+
1050
+ hidden_states = self.layernorm_embedding(hidden_states + positions)
1051
+ hidden_states = self.dropout(hidden_states, training=training)
1052
+
1053
+ # decoder layers
1054
+ all_hidden_states = () if output_hidden_states else None
1055
+ all_self_attns = () if output_attentions else None
1056
+ all_cross_attns = () if (output_attentions and encoder_hidden_states is not None) else None
1057
+ present_key_values = () if use_cache else None
1058
+
1059
+ # check if head_mask and cross_attn_head_mask have a correct number of layers specified if desired
1060
+ for attn_mask_name, attn_mask in [("head_mask", head_mask), ("cross_attn_head_mask", cross_attn_head_mask)]:
1061
+ if attn_mask is not None:
1062
+ tf.debugging.assert_equal(
1063
+ shape_list(attn_mask)[0],
1064
+ len(self.layers),
1065
+ message=(
1066
+ f"The {attn_mask_name} should be specified for {len(self.layers)} layers, but it is for"
1067
+ f" {shape_list(attn_mask)[0]}."
1068
+ ),
1069
+ )
1070
+
1071
+ for idx, decoder_layer in enumerate(self.layers):
1072
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1073
+ if output_hidden_states:
1074
+ all_hidden_states += (hidden_states,)
1075
+
1076
+ dropout_probability = random.uniform(0, 1)
1077
+
1078
+ if training and (dropout_probability < self.layerdrop):
1079
+ continue
1080
+
1081
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
1082
+
1083
+ hidden_states, layer_self_attn, layer_cross_attn, present_key_value = decoder_layer(
1084
+ hidden_states,
1085
+ attention_mask=combined_attention_mask,
1086
+ encoder_hidden_states=encoder_hidden_states,
1087
+ encoder_attention_mask=encoder_attention_mask,
1088
+ layer_head_mask=head_mask[idx] if head_mask is not None else None,
1089
+ cross_attn_layer_head_mask=cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
1090
+ past_key_value=past_key_value,
1091
+ )
1092
+
1093
+ if use_cache:
1094
+ present_key_values += (present_key_value,)
1095
+
1096
+ if output_attentions:
1097
+ all_self_attns += (layer_self_attn,)
1098
+
1099
+ if encoder_hidden_states is not None:
1100
+ all_cross_attns += (layer_cross_attn,)
1101
+
1102
+ if output_hidden_states:
1103
+ all_hidden_states += (hidden_states,)
1104
+
1105
+ if not return_dict:
1106
+ return hidden_states, present_key_values, all_hidden_states, all_self_attns, all_cross_attns
1107
+ else:
1108
+ return TFBaseModelOutputWithPastAndCrossAttentions(
1109
+ last_hidden_state=hidden_states,
1110
+ past_key_values=present_key_values,
1111
+ hidden_states=all_hidden_states,
1112
+ attentions=all_self_attns,
1113
+ cross_attentions=all_cross_attns,
1114
+ )
1115
+
1116
+ def build(self, input_shape=None):
1117
+ if self.built:
1118
+ return
1119
+ self.built = True
1120
+ if getattr(self, "embed_positions", None) is not None:
1121
+ with tf.name_scope(self.embed_positions.name):
1122
+ self.embed_positions.build(None)
1123
+ if getattr(self, "layernorm_embedding", None) is not None:
1124
+ with tf.name_scope(self.layernorm_embedding.name):
1125
+ self.layernorm_embedding.build([None, None, self.config.d_model])
1126
+ if getattr(self, "layers", None) is not None:
1127
+ for layer in self.layers:
1128
+ with tf.name_scope(layer.name):
1129
+ layer.build(None)
1130
+
1131
+
1132
+ @keras_serializable
1133
+ class TFBartMainLayer(keras.layers.Layer):
1134
+ config_class = BartConfig
1135
+
1136
+ def __init__(self, config: BartConfig, load_weight_prefix=None, **kwargs):
1137
+ super().__init__(**kwargs)
1138
+ self.config = config
1139
+ self.shared = keras.layers.Embedding(
1140
+ input_dim=config.vocab_size,
1141
+ output_dim=config.d_model,
1142
+ embeddings_initializer=keras.initializers.TruncatedNormal(stddev=self.config.init_std),
1143
+ name="model.shared",
1144
+ )
1145
+ # Additional attribute to specify the expected name scope of the layer (for loading/storing weights)
1146
+ self.shared.load_weight_prefix = "model.shared" if load_weight_prefix is None else load_weight_prefix
1147
+
1148
+ self.encoder = TFBartEncoder(config, self.shared, name="encoder")
1149
+ self.decoder = TFBartDecoder(config, self.shared, name="decoder")
1150
+
1151
+ def get_input_embeddings(self):
1152
+ return self.shared
1153
+
1154
+ def set_input_embeddings(self, new_embeddings):
1155
+ self.shared = new_embeddings
1156
+ self.encoder.embed_tokens = self.shared
1157
+ self.decoder.embed_tokens = self.shared
1158
+
1159
+ @unpack_inputs
1160
+ def call(
1161
+ self,
1162
+ input_ids: TFModelInputType | None = None,
1163
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1164
+ decoder_input_ids: np.ndarray | tf.Tensor | None = None,
1165
+ decoder_attention_mask: np.ndarray | tf.Tensor | None = None,
1166
+ decoder_position_ids: np.ndarray | tf.Tensor | None = None,
1167
+ head_mask: np.ndarray | tf.Tensor | None = None,
1168
+ decoder_head_mask: np.ndarray | tf.Tensor | None = None,
1169
+ cross_attn_head_mask: np.ndarray | tf.Tensor | None = None,
1170
+ encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,
1171
+ past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
1172
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1173
+ decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None,
1174
+ use_cache: Optional[bool] = None,
1175
+ output_attentions: Optional[bool] = None,
1176
+ output_hidden_states: Optional[bool] = None,
1177
+ return_dict: Optional[bool] = None,
1178
+ training: Optional[bool] = False,
1179
+ **kwargs,
1180
+ ) -> Union[TFSeq2SeqModelOutput, Tuple[tf.Tensor]]:
1181
+ # different to other models, Bart automatically creates decoder_input_ids from
1182
+ # input_ids if no decoder_input_ids are provided
1183
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1184
+ if input_ids is None:
1185
+ raise ValueError(
1186
+ "If no `decoder_input_ids` or `decoder_inputs_embeds` are "
1187
+ "passed, `input_ids` cannot be `None`. Please pass either "
1188
+ "`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`."
1189
+ )
1190
+
1191
+ decoder_input_ids = shift_tokens_right(
1192
+ input_ids, self.config.pad_token_id, self.config.decoder_start_token_id
1193
+ )
1194
+
1195
+ if encoder_outputs is None:
1196
+ encoder_outputs = self.encoder(
1197
+ input_ids=input_ids,
1198
+ attention_mask=attention_mask,
1199
+ head_mask=head_mask,
1200
+ inputs_embeds=inputs_embeds,
1201
+ output_attentions=output_attentions,
1202
+ output_hidden_states=output_hidden_states,
1203
+ return_dict=return_dict,
1204
+ training=training,
1205
+ )
1206
+ # If the user passed a tuple for encoder_outputs, we wrap it in a TFBaseModelOutput when return_dict=True
1207
+ elif return_dict and not isinstance(encoder_outputs, TFBaseModelOutput):
1208
+ encoder_outputs = TFBaseModelOutput(
1209
+ last_hidden_state=encoder_outputs[0],
1210
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1211
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1212
+ )
1213
+ # If the user passed a TFBaseModelOutput for encoder_outputs, we wrap it in a tuple when return_dict=False
1214
+ elif not return_dict and not isinstance(encoder_outputs, tuple):
1215
+ encoder_outputs = encoder_outputs.to_tuple()
1216
+
1217
+ decoder_outputs = self.decoder(
1218
+ decoder_input_ids,
1219
+ attention_mask=decoder_attention_mask,
1220
+ position_ids=decoder_position_ids,
1221
+ encoder_hidden_states=encoder_outputs[0],
1222
+ encoder_attention_mask=attention_mask,
1223
+ head_mask=decoder_head_mask,
1224
+ cross_attn_head_mask=cross_attn_head_mask,
1225
+ past_key_values=past_key_values,
1226
+ inputs_embeds=decoder_inputs_embeds,
1227
+ use_cache=use_cache,
1228
+ output_attentions=output_attentions,
1229
+ output_hidden_states=output_hidden_states,
1230
+ return_dict=return_dict,
1231
+ training=training,
1232
+ )
1233
+
1234
+ if not return_dict:
1235
+ return decoder_outputs + encoder_outputs
1236
+
1237
+ return TFSeq2SeqModelOutput(
1238
+ last_hidden_state=decoder_outputs.last_hidden_state,
1239
+ past_key_values=decoder_outputs.past_key_values,
1240
+ decoder_hidden_states=decoder_outputs.hidden_states,
1241
+ decoder_attentions=decoder_outputs.attentions,
1242
+ cross_attentions=decoder_outputs.cross_attentions,
1243
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1244
+ encoder_hidden_states=encoder_outputs.hidden_states,
1245
+ encoder_attentions=encoder_outputs.attentions,
1246
+ )
1247
+
1248
+ def build(self, input_shape=None):
1249
+ if self.built:
1250
+ return
1251
+ self.built = True
1252
+ # The shared/tied weights expect to be in the model base namespace
1253
+ # Adding "/" to the end (not the start!) of a tf.name_scope puts it in the root namespace rather than
1254
+ # the current one.
1255
+ with tf.name_scope(self.shared.load_weight_prefix + "/" + self.shared.name + "/"):
1256
+ self.shared.build(None)
1257
+ if getattr(self, "encoder", None) is not None:
1258
+ with tf.name_scope(self.encoder.name):
1259
+ self.encoder.build(None)
1260
+ if getattr(self, "decoder", None) is not None:
1261
+ with tf.name_scope(self.decoder.name):
1262
+ self.decoder.build(None)
1263
+
1264
+
1265
+ @add_start_docstrings(
1266
+ "The bare BART Model outputting raw hidden-states without any specific head on top.",
1267
+ BART_START_DOCSTRING,
1268
+ )
1269
+ class TFBartModel(TFBartPretrainedModel):
1270
+ _requires_load_weight_prefix = True
1271
+
1272
+ def __init__(self, config: BartConfig, load_weight_prefix=None, *inputs, **kwargs):
1273
+ super().__init__(config, *inputs, **kwargs)
1274
+
1275
+ self.model = TFBartMainLayer(config, load_weight_prefix=load_weight_prefix, name="model")
1276
+
1277
+ def get_encoder(self):
1278
+ return self.model.encoder
1279
+
1280
+ def get_decoder(self):
1281
+ return self.model.decoder
1282
+
1283
+ @add_start_docstrings_to_model_forward(BART_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1284
+ @add_code_sample_docstrings(
1285
+ checkpoint=_CHECKPOINT_FOR_DOC,
1286
+ output_type=TFSeq2SeqModelOutput,
1287
+ config_class=_CONFIG_FOR_DOC,
1288
+ )
1289
+ @unpack_inputs
1290
+ def call(
1291
+ self,
1292
+ input_ids: TFModelInputType | None = None,
1293
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1294
+ decoder_input_ids: np.ndarray | tf.Tensor | None = None,
1295
+ decoder_attention_mask: np.ndarray | tf.Tensor | None = None,
1296
+ decoder_position_ids: np.ndarray | tf.Tensor | None = None,
1297
+ head_mask: np.ndarray | tf.Tensor | None = None,
1298
+ decoder_head_mask: np.ndarray | tf.Tensor | None = None,
1299
+ cross_attn_head_mask: np.ndarray | tf.Tensor | None = None,
1300
+ encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,
1301
+ past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
1302
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1303
+ decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None,
1304
+ use_cache: Optional[bool] = None,
1305
+ output_attentions: Optional[bool] = None,
1306
+ output_hidden_states: Optional[bool] = None,
1307
+ return_dict: Optional[bool] = None,
1308
+ training: Optional[bool] = False,
1309
+ **kwargs,
1310
+ ) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:
1311
+ outputs = self.model(
1312
+ input_ids=input_ids,
1313
+ attention_mask=attention_mask,
1314
+ decoder_input_ids=decoder_input_ids,
1315
+ decoder_attention_mask=decoder_attention_mask,
1316
+ decoder_position_ids=decoder_position_ids,
1317
+ head_mask=head_mask,
1318
+ decoder_head_mask=decoder_head_mask,
1319
+ cross_attn_head_mask=cross_attn_head_mask,
1320
+ encoder_outputs=encoder_outputs,
1321
+ past_key_values=past_key_values,
1322
+ inputs_embeds=inputs_embeds,
1323
+ decoder_inputs_embeds=decoder_inputs_embeds,
1324
+ use_cache=use_cache,
1325
+ output_attentions=output_attentions,
1326
+ output_hidden_states=output_hidden_states,
1327
+ return_dict=return_dict,
1328
+ training=training,
1329
+ )
1330
+
1331
+ return outputs
1332
+
1333
+ def serving_output(self, output):
1334
+ pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
1335
+ dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
1336
+ dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
1337
+ cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
1338
+ enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
1339
+ enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
1340
+
1341
+ return TFSeq2SeqModelOutput(
1342
+ last_hidden_state=output.last_hidden_state,
1343
+ past_key_values=pkv,
1344
+ decoder_hidden_states=dec_hs,
1345
+ decoder_attentions=dec_attns,
1346
+ cross_attentions=cross_attns,
1347
+ encoder_last_hidden_state=output.encoder_last_hidden_state,
1348
+ encoder_hidden_states=enc_hs,
1349
+ encoder_attentions=enc_attns,
1350
+ )
1351
+
1352
+ def build(self, input_shape=None):
1353
+ if self.built:
1354
+ return
1355
+ self.built = True
1356
+ if getattr(self, "model", None) is not None:
1357
+ with tf.name_scope(self.model.name):
1358
+ self.model.build(None)
1359
+
1360
+
1361
+ class BiasLayer(keras.layers.Layer):
1362
+ """
1363
+ Bias as a layer. It is used for serialization purposes: `keras.Model.save_weights` stores on a per-layer basis,
1364
+ so all weights have to be registered in a layer.
1365
+ """
1366
+
1367
+ def __init__(self, shape, initializer, trainable, name, **kwargs):
1368
+ super().__init__(name=name, **kwargs)
1369
+ # Note: the name of this variable will NOT be scoped when serialized, i.e. it will not be in the format of
1370
+ # "outer_layer/inner_layer/.../name:0". Instead, it will be "name:0". For further details, see:
1371
+ # https://github.com/huggingface/transformers/pull/18833#issuecomment-1233090214
1372
+ self.bias = self.add_weight(name=name, shape=shape, initializer=initializer, trainable=trainable)
1373
+
1374
+ def call(self, x):
1375
+ return x + self.bias
1376
+
1377
+
1378
+ @add_start_docstrings(
1379
+ "The BART Model with a language modeling head. Can be used for summarization.",
1380
+ BART_START_DOCSTRING,
1381
+ )
1382
+ class TFBartForConditionalGeneration(TFBartPretrainedModel, TFCausalLanguageModelingLoss):
1383
+ _keys_to_ignore_on_load_missing = [r"final_logits_bias"]
1384
+ _requires_load_weight_prefix = True
1385
+
1386
+ def __init__(self, config, load_weight_prefix=None, *inputs, **kwargs):
1387
+ super().__init__(config, *inputs, **kwargs)
1388
+ self.model = TFBartMainLayer(config, load_weight_prefix=load_weight_prefix, name="model")
1389
+ self.use_cache = config.use_cache
1390
+ # final_bias_logits is registered as a buffer in pytorch, so not trainable for the sake of consistency.
1391
+ self.bias_layer = BiasLayer(
1392
+ name="final_logits_bias", shape=[1, config.vocab_size], initializer="zeros", trainable=False
1393
+ )
1394
+
1395
+ def get_decoder(self):
1396
+ return self.model.decoder
1397
+
1398
+ def get_encoder(self):
1399
+ return self.model.encoder
1400
+
1401
+ def get_output_embeddings(self):
1402
+ return self.get_input_embeddings()
1403
+
1404
+ def set_output_embeddings(self, value):
1405
+ self.set_input_embeddings(value)
1406
+
1407
+ def get_bias(self):
1408
+ return {"final_logits_bias": self.bias_layer.bias}
1409
+
1410
+ def set_bias(self, value):
1411
+ # Replaces the existing layers containing bias for correct (de)serialization.
1412
+ vocab_size = value["final_logits_bias"].shape[-1]
1413
+ self.bias_layer = BiasLayer(
1414
+ name="final_logits_bias", shape=[1, vocab_size], initializer="zeros", trainable=False
1415
+ )
1416
+ self.bias_layer.bias.assign(value["final_logits_bias"])
1417
+
1418
+ @add_start_docstrings_to_model_forward(BART_INPUTS_DOCSTRING)
1419
+ @replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
1420
+ @add_end_docstrings(BART_GENERATION_EXAMPLE)
1421
+ @unpack_inputs
1422
+ def call(
1423
+ self,
1424
+ input_ids: TFModelInputType | None = None,
1425
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1426
+ decoder_input_ids: np.ndarray | tf.Tensor | None = None,
1427
+ decoder_attention_mask: np.ndarray | tf.Tensor | None = None,
1428
+ decoder_position_ids: np.ndarray | tf.Tensor | None = None,
1429
+ head_mask: np.ndarray | tf.Tensor | None = None,
1430
+ decoder_head_mask: np.ndarray | tf.Tensor | None = None,
1431
+ cross_attn_head_mask: np.ndarray | tf.Tensor | None = None,
1432
+ encoder_outputs: Optional[TFBaseModelOutput] = None,
1433
+ past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
1434
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1435
+ decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None,
1436
+ use_cache: Optional[bool] = None,
1437
+ output_attentions: Optional[bool] = None,
1438
+ output_hidden_states: Optional[bool] = None,
1439
+ return_dict: Optional[bool] = None,
1440
+ labels: tf.Tensor | None = None,
1441
+ training: Optional[bool] = False,
1442
+ ) -> Union[TFSeq2SeqLMOutput, Tuple[tf.Tensor]]:
1443
+ r"""
1444
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1445
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1446
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1447
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1448
+
1449
+ Returns:
1450
+
1451
+ """
1452
+
1453
+ if labels is not None:
1454
+ labels = tf.where(
1455
+ labels == self.config.pad_token_id,
1456
+ tf.cast(tf.fill(shape_list(labels), -100), labels.dtype),
1457
+ labels,
1458
+ )
1459
+ use_cache = False
1460
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1461
+ decoder_input_ids = shift_tokens_right(
1462
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1463
+ )
1464
+
1465
+ outputs = self.model(
1466
+ input_ids,
1467
+ attention_mask=attention_mask,
1468
+ decoder_input_ids=decoder_input_ids,
1469
+ encoder_outputs=encoder_outputs,
1470
+ decoder_attention_mask=decoder_attention_mask,
1471
+ decoder_position_ids=decoder_position_ids,
1472
+ head_mask=head_mask,
1473
+ decoder_head_mask=decoder_head_mask,
1474
+ cross_attn_head_mask=cross_attn_head_mask,
1475
+ past_key_values=past_key_values,
1476
+ inputs_embeds=inputs_embeds,
1477
+ decoder_inputs_embeds=decoder_inputs_embeds,
1478
+ use_cache=use_cache,
1479
+ output_attentions=output_attentions,
1480
+ output_hidden_states=output_hidden_states,
1481
+ return_dict=return_dict,
1482
+ training=training,
1483
+ )
1484
+ lm_logits = tf.matmul(outputs[0], self.model.shared.weights, transpose_b=True)
1485
+ lm_logits = self.bias_layer(lm_logits)
1486
+ masked_lm_loss = None if labels is None else self.hf_compute_loss(labels, lm_logits)
1487
+
1488
+ if not return_dict:
1489
+ output = (lm_logits,) + outputs[1:]
1490
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1491
+ return TFSeq2SeqLMOutput(
1492
+ loss=masked_lm_loss,
1493
+ logits=lm_logits,
1494
+ past_key_values=outputs.past_key_values, # index 1 of d outputs
1495
+ decoder_hidden_states=outputs.decoder_hidden_states, # index 2 of d outputs
1496
+ decoder_attentions=outputs.decoder_attentions, # index 3 of d outputs
1497
+ cross_attentions=outputs.cross_attentions, # index 4 of d outputs
1498
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state, # index 0 of encoder outputs
1499
+ encoder_hidden_states=outputs.encoder_hidden_states, # 1 of e out
1500
+ encoder_attentions=outputs.encoder_attentions, # 2 of e out
1501
+ )
1502
+
1503
+ def serving_output(self, output):
1504
+ pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
1505
+ dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
1506
+ dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
1507
+ cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
1508
+ enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
1509
+ enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
1510
+
1511
+ return TFSeq2SeqLMOutput(
1512
+ logits=output.logits,
1513
+ past_key_values=pkv,
1514
+ decoder_hidden_states=dec_hs,
1515
+ decoder_attentions=dec_attns,
1516
+ cross_attentions=cross_attns,
1517
+ encoder_last_hidden_state=output.encoder_last_hidden_state,
1518
+ encoder_hidden_states=enc_hs,
1519
+ encoder_attentions=enc_attns,
1520
+ )
1521
+
1522
+ def prepare_inputs_for_generation(
1523
+ self,
1524
+ decoder_input_ids,
1525
+ past_key_values=None,
1526
+ attention_mask=None,
1527
+ decoder_attention_mask=None,
1528
+ head_mask=None,
1529
+ decoder_head_mask=None,
1530
+ cross_attn_head_mask=None,
1531
+ use_cache=None,
1532
+ encoder_outputs=None,
1533
+ **kwargs,
1534
+ ):
1535
+ # cut decoder_input_ids if past_key_values is used
1536
+ if past_key_values is not None:
1537
+ decoder_input_ids = decoder_input_ids[:, -1:]
1538
+
1539
+ if decoder_attention_mask is not None: # xla
1540
+ decoder_position_ids = tf.math.cumsum(decoder_attention_mask, axis=-1, exclusive=True)[:, -1:]
1541
+ elif past_key_values is not None: # no xla + past_key_values
1542
+ decoder_position_ids = past_key_values[0][0].shape[2]
1543
+ else: # no xla + no past_key_values
1544
+ decoder_position_ids = tf.range(decoder_input_ids.shape[1])
1545
+
1546
+ return {
1547
+ "input_ids": None, # encoder_outputs is defined. input_ids not needed
1548
+ "encoder_outputs": encoder_outputs,
1549
+ "past_key_values": past_key_values,
1550
+ "decoder_input_ids": decoder_input_ids,
1551
+ "attention_mask": attention_mask,
1552
+ "decoder_attention_mask": decoder_attention_mask,
1553
+ "decoder_position_ids": decoder_position_ids,
1554
+ "head_mask": head_mask,
1555
+ "decoder_head_mask": decoder_head_mask,
1556
+ "cross_attn_head_mask": cross_attn_head_mask,
1557
+ "use_cache": use_cache, # change this to avoid caching (presumably for debugging)
1558
+ }
1559
+
1560
+ def prepare_decoder_input_ids_from_labels(self, labels: tf.Tensor):
1561
+ return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
1562
+
1563
+ def build(self, input_shape=None):
1564
+ if self.built:
1565
+ return
1566
+ self.built = True
1567
+ if getattr(self, "model", None) is not None:
1568
+ with tf.name_scope(self.model.name):
1569
+ self.model.build(None)
1570
+ if getattr(self, "bias_layer", None) is not None:
1571
+ with tf.name_scope(self.bias_layer.name):
1572
+ self.bias_layer.build(None)
1573
+
1574
+
1575
+ @add_start_docstrings(
1576
+ """
1577
+ Bart model with a sequence classification/head on top (a linear layer on top of the pooled output) e.g. for GLUE
1578
+ tasks.
1579
+ """,
1580
+ BART_START_DOCSTRING,
1581
+ )
1582
+ class TFBartForSequenceClassification(TFBartPretrainedModel, TFSequenceClassificationLoss):
1583
+ def __init__(self, config: BartConfig, load_weight_prefix=None, *inputs, **kwargs):
1584
+ super().__init__(config, *inputs, **kwargs)
1585
+ self.model = TFBartMainLayer(config, load_weight_prefix=load_weight_prefix, name="model")
1586
+ self.classification_head = TFBartClassificationHead(
1587
+ config.d_model, config.num_labels, config.classifier_dropout, name="classification_head"
1588
+ )
1589
+
1590
+ @add_start_docstrings_to_model_forward(BART_INPUTS_DOCSTRING)
1591
+ @replace_return_docstrings(output_type=TFSeq2SeqSequenceClassifierOutput, config_class=_CONFIG_FOR_DOC)
1592
+ @unpack_inputs
1593
+ def call(
1594
+ self,
1595
+ input_ids: TFModelInputType | None = None,
1596
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1597
+ decoder_input_ids: np.ndarray | tf.Tensor | None = None,
1598
+ decoder_attention_mask: np.ndarray | tf.Tensor | None = None,
1599
+ decoder_position_ids: np.ndarray | tf.Tensor | None = None,
1600
+ head_mask: np.ndarray | tf.Tensor | None = None,
1601
+ decoder_head_mask: np.ndarray | tf.Tensor | None = None,
1602
+ cross_attn_head_mask: np.ndarray | tf.Tensor | None = None,
1603
+ encoder_outputs: Optional[TFBaseModelOutput] = None,
1604
+ past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
1605
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1606
+ decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None,
1607
+ use_cache: Optional[bool] = None,
1608
+ output_attentions: Optional[bool] = None,
1609
+ output_hidden_states: Optional[bool] = None,
1610
+ return_dict: Optional[bool] = None,
1611
+ labels: tf.Tensor | None = None,
1612
+ training: Optional[bool] = False,
1613
+ ) -> Union[TFSeq2SeqSequenceClassifierOutput, Tuple[tf.Tensor]]:
1614
+ r"""
1615
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1616
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1617
+ config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1618
+
1619
+ Returns:
1620
+ """
1621
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1622
+ if labels is not None:
1623
+ use_cache = False
1624
+
1625
+ if input_ids is None and inputs_embeds is not None:
1626
+ raise NotImplementedError(
1627
+ f"Passing input embeddings is currently not supported for {self.__class__.__name__}"
1628
+ )
1629
+
1630
+ outputs = self.model(
1631
+ input_ids=input_ids,
1632
+ attention_mask=attention_mask,
1633
+ decoder_input_ids=decoder_input_ids,
1634
+ decoder_attention_mask=decoder_attention_mask,
1635
+ decoder_position_ids=decoder_position_ids,
1636
+ head_mask=head_mask,
1637
+ decoder_head_mask=decoder_head_mask,
1638
+ cross_attn_head_mask=cross_attn_head_mask,
1639
+ encoder_outputs=encoder_outputs,
1640
+ past_key_values=past_key_values,
1641
+ inputs_embeds=inputs_embeds,
1642
+ decoder_inputs_embeds=decoder_inputs_embeds,
1643
+ use_cache=use_cache,
1644
+ output_attentions=output_attentions,
1645
+ output_hidden_states=output_hidden_states,
1646
+ return_dict=return_dict,
1647
+ training=training,
1648
+ )
1649
+
1650
+ last_hidden_state = outputs[0]
1651
+ eos_mask = tf.equal(input_ids, self.config.eos_token_id)
1652
+ # out the rows with False where present. Then verify all the final
1653
+ # entries are True
1654
+ self_masked = tf.reshape(tf.boolean_mask(eos_mask, eos_mask), (tf.shape(input_ids)[0], -1))
1655
+ tf.Assert(tf.reduce_all(self_masked[:, -1]), ["All examples must have the same number of <eos> tokens."])
1656
+
1657
+ masked = tf.reshape(
1658
+ tf.boolean_mask(last_hidden_state, eos_mask),
1659
+ (tf.shape(input_ids)[0], tf.shape(self_masked)[1], tf.shape(last_hidden_state)[-1]),
1660
+ )
1661
+
1662
+ sentence_representation = masked[:, -1, :]
1663
+ logits = self.classification_head(sentence_representation)
1664
+ loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
1665
+
1666
+ if not return_dict:
1667
+ output = (logits,) + outputs[1:]
1668
+ return ((loss,) + output) if loss is not None else output
1669
+
1670
+ return TFSeq2SeqSequenceClassifierOutput(
1671
+ loss=loss,
1672
+ logits=logits,
1673
+ past_key_values=outputs.past_key_values,
1674
+ decoder_hidden_states=outputs.decoder_hidden_states,
1675
+ decoder_attentions=outputs.decoder_attentions,
1676
+ cross_attentions=outputs.cross_attentions,
1677
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1678
+ encoder_hidden_states=outputs.encoder_hidden_states,
1679
+ encoder_attentions=outputs.encoder_attentions,
1680
+ )
1681
+
1682
+ def serving_output(self, output):
1683
+ logits = tf.convert_to_tensor(output.logits)
1684
+ pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
1685
+ dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
1686
+ dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
1687
+ cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
1688
+ enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
1689
+ enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
1690
+
1691
+ return TFSeq2SeqSequenceClassifierOutput(
1692
+ logits=logits,
1693
+ past_key_values=pkv,
1694
+ decoder_hidden_states=dec_hs,
1695
+ decoder_attentions=dec_attns,
1696
+ cross_attentions=cross_attns,
1697
+ encoder_last_hidden_state=output.encoder_last_hidden_state,
1698
+ encoder_hidden_states=enc_hs,
1699
+ encoder_attentions=enc_attns,
1700
+ )
1701
+
1702
+ def build(self, input_shape=None):
1703
+ if self.built:
1704
+ return
1705
+ self.built = True
1706
+ if getattr(self, "model", None) is not None:
1707
+ with tf.name_scope(self.model.name):
1708
+ self.model.build(None)
1709
+ if getattr(self, "classification_head", None) is not None:
1710
+ with tf.name_scope(self.classification_head.name):
1711
+ self.classification_head.build(None)
1712
+
1713
+
1714
+ __all__ = ["TFBartForConditionalGeneration", "TFBartForSequenceClassification", "TFBartModel", "TFBartPretrainedModel"]
lib/python3.12/site-packages/transformers/models/bart/tokenization_bart.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import json
17
+ import os
18
+ from functools import lru_cache
19
+ from typing import List, Optional, Tuple
20
+
21
+ import regex as re
22
+
23
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
24
+ from ...utils import logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
31
+
32
+ # See all BART models at https://huggingface.co/models?filter=bart
33
+
34
+
35
+ @lru_cache()
36
+ def bytes_to_unicode():
37
+ """
38
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
39
+ characters the bpe code barfs on.
40
+
41
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
42
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
43
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
44
+ tables between utf-8 bytes and unicode strings.
45
+ """
46
+ bs = (
47
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
48
+ )
49
+ cs = bs[:]
50
+ n = 0
51
+ for b in range(2**8):
52
+ if b not in bs:
53
+ bs.append(b)
54
+ cs.append(2**8 + n)
55
+ n += 1
56
+ cs = [chr(n) for n in cs]
57
+ return dict(zip(bs, cs))
58
+
59
+
60
+ def get_pairs(word):
61
+ """
62
+ Return set of symbol pairs in a word.
63
+
64
+ Word is represented as tuple of symbols (symbols being variable-length strings).
65
+ """
66
+ pairs = set()
67
+ prev_char = word[0]
68
+ for char in word[1:]:
69
+ pairs.add((prev_char, char))
70
+ prev_char = char
71
+ return pairs
72
+
73
+
74
+ class BartTokenizer(PreTrainedTokenizer):
75
+ """
76
+ Constructs a BART tokenizer, which is smilar to the ROBERTa tokenizer, using byte-level Byte-Pair-Encoding.
77
+
78
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
79
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
80
+
81
+ ```python
82
+ >>> from transformers import BartTokenizer
83
+
84
+ >>> tokenizer = BartTokenizer.from_pretrained("facebook/bart-base")
85
+ >>> tokenizer("Hello world")["input_ids"]
86
+ [0, 31414, 232, 2]
87
+
88
+ >>> tokenizer(" Hello world")["input_ids"]
89
+ [0, 20920, 232, 2]
90
+ ```
91
+
92
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
93
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
94
+
95
+ <Tip>
96
+
97
+ When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
98
+
99
+ </Tip>
100
+
101
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
102
+ this superclass for more information regarding those methods.
103
+
104
+ Args:
105
+ vocab_file (`str`):
106
+ Path to the vocabulary file.
107
+ merges_file (`str`):
108
+ Path to the merges file.
109
+ errors (`str`, *optional*, defaults to `"replace"`):
110
+ Paradigm to follow when decoding bytes to UTF-8. See
111
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
112
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
113
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
114
+
115
+ <Tip>
116
+
117
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
118
+ sequence. The token used is the `cls_token`.
119
+
120
+ </Tip>
121
+
122
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
123
+ The end of sequence token.
124
+
125
+ <Tip>
126
+
127
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
128
+ The token used is the `sep_token`.
129
+
130
+ </Tip>
131
+
132
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
133
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
134
+ sequence classification or for a text and a question for question answering. It is also used as the last
135
+ token of a sequence built with special tokens.
136
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
137
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
138
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
139
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
140
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
141
+ token instead.
142
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
143
+ The token used for padding, for example when batching sequences of different lengths.
144
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
145
+ The token used for masking values. This is the token used when training this model with masked language
146
+ modeling. This is the token which the model will try to predict.
147
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
148
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
149
+ other word. (BART tokenizer detect beginning of words by the preceding space).
150
+ """
151
+
152
+ vocab_files_names = VOCAB_FILES_NAMES
153
+ model_input_names = ["input_ids", "attention_mask"]
154
+
155
+ def __init__(
156
+ self,
157
+ vocab_file,
158
+ merges_file,
159
+ errors="replace",
160
+ bos_token="<s>",
161
+ eos_token="</s>",
162
+ sep_token="</s>",
163
+ cls_token="<s>",
164
+ unk_token="<unk>",
165
+ pad_token="<pad>",
166
+ mask_token="<mask>",
167
+ add_prefix_space=False,
168
+ **kwargs,
169
+ ):
170
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
171
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
172
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
173
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
174
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
175
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
176
+
177
+ # Mask token behave like a normal word, i.e. include the space before it
178
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
179
+
180
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
181
+ self.encoder = json.load(vocab_handle)
182
+ self.decoder = {v: k for k, v in self.encoder.items()}
183
+ self.errors = errors # how to handle errors in decoding
184
+ self.byte_encoder = bytes_to_unicode()
185
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
186
+ with open(merges_file, encoding="utf-8") as merges_handle:
187
+ bpe_merges = merges_handle.read().split("\n")[1:-1]
188
+ bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
189
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
190
+ self.cache = {}
191
+ self.add_prefix_space = add_prefix_space
192
+
193
+ # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
194
+ self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
195
+
196
+ super().__init__(
197
+ errors=errors,
198
+ bos_token=bos_token,
199
+ eos_token=eos_token,
200
+ unk_token=unk_token,
201
+ sep_token=sep_token,
202
+ cls_token=cls_token,
203
+ pad_token=pad_token,
204
+ mask_token=mask_token,
205
+ add_prefix_space=add_prefix_space,
206
+ **kwargs,
207
+ )
208
+
209
+ @property
210
+ def vocab_size(self):
211
+ return len(self.encoder)
212
+
213
+ def get_vocab(self):
214
+ return dict(self.encoder, **self.added_tokens_encoder)
215
+
216
+ def bpe(self, token):
217
+ if token in self.cache:
218
+ return self.cache[token]
219
+ word = tuple(token)
220
+ pairs = get_pairs(word)
221
+
222
+ if not pairs:
223
+ return token
224
+
225
+ while True:
226
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
227
+ if bigram not in self.bpe_ranks:
228
+ break
229
+ first, second = bigram
230
+ new_word = []
231
+ i = 0
232
+ while i < len(word):
233
+ try:
234
+ j = word.index(first, i)
235
+ except ValueError:
236
+ new_word.extend(word[i:])
237
+ break
238
+ else:
239
+ new_word.extend(word[i:j])
240
+ i = j
241
+
242
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
243
+ new_word.append(first + second)
244
+ i += 2
245
+ else:
246
+ new_word.append(word[i])
247
+ i += 1
248
+ new_word = tuple(new_word)
249
+ word = new_word
250
+ if len(word) == 1:
251
+ break
252
+ else:
253
+ pairs = get_pairs(word)
254
+ word = " ".join(word)
255
+ self.cache[token] = word
256
+ return word
257
+
258
+ def _tokenize(self, text):
259
+ """Tokenize a string."""
260
+ bpe_tokens = []
261
+ for token in re.findall(self.pat, text):
262
+ token = "".join(
263
+ self.byte_encoder[b] for b in token.encode("utf-8")
264
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
265
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
266
+ return bpe_tokens
267
+
268
+ def _convert_token_to_id(self, token):
269
+ """Converts a token (str) in an id using the vocab."""
270
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
271
+
272
+ def _convert_id_to_token(self, index):
273
+ """Converts an index (integer) in a token (str) using the vocab."""
274
+ return self.decoder.get(index)
275
+
276
+ def convert_tokens_to_string(self, tokens):
277
+ """Converts a sequence of tokens (string) in a single string."""
278
+ text = "".join(tokens)
279
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
280
+ return text
281
+
282
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
283
+ if not os.path.isdir(save_directory):
284
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
285
+ return
286
+ vocab_file = os.path.join(
287
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
288
+ )
289
+ merge_file = os.path.join(
290
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
291
+ )
292
+
293
+ with open(vocab_file, "w", encoding="utf-8") as f:
294
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
295
+
296
+ index = 0
297
+ with open(merge_file, "w", encoding="utf-8") as writer:
298
+ writer.write("#version: 0.2\n")
299
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
300
+ if index != token_index:
301
+ logger.warning(
302
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
303
+ " Please check that the tokenizer is not corrupted!"
304
+ )
305
+ index = token_index
306
+ writer.write(" ".join(bpe_tokens) + "\n")
307
+ index += 1
308
+
309
+ return vocab_file, merge_file
310
+
311
+ def build_inputs_with_special_tokens(
312
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
313
+ ) -> List[int]:
314
+ """
315
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
316
+ adding special tokens. A BART sequence has the following format:
317
+
318
+ - single sequence: `<s> X </s>`
319
+ - pair of sequences: `<s> A </s></s> B </s>`
320
+
321
+ Args:
322
+ token_ids_0 (`List[int]`):
323
+ List of IDs to which the special tokens will be added.
324
+ token_ids_1 (`List[int]`, *optional*):
325
+ Optional second list of IDs for sequence pairs.
326
+
327
+ Returns:
328
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
329
+ """
330
+ if token_ids_1 is None:
331
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
332
+ cls = [self.cls_token_id]
333
+ sep = [self.sep_token_id]
334
+ return cls + token_ids_0 + sep + sep + token_ids_1 + sep
335
+
336
+ def get_special_tokens_mask(
337
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
338
+ ) -> List[int]:
339
+ """
340
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
341
+ special tokens using the tokenizer `prepare_for_model` method.
342
+
343
+ Args:
344
+ token_ids_0 (`List[int]`):
345
+ List of IDs.
346
+ token_ids_1 (`List[int]`, *optional*):
347
+ Optional second list of IDs for sequence pairs.
348
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
349
+ Whether or not the token list is already formatted with special tokens for the model.
350
+
351
+ Returns:
352
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
353
+ """
354
+ if already_has_special_tokens:
355
+ return super().get_special_tokens_mask(
356
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
357
+ )
358
+
359
+ if token_ids_1 is None:
360
+ return [1] + ([0] * len(token_ids_0)) + [1]
361
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
362
+
363
+ def create_token_type_ids_from_sequences(
364
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
365
+ ) -> List[int]:
366
+ """
367
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. BART does not
368
+ make use of token type ids, therefore a list of zeros is returned.
369
+
370
+ Args:
371
+ token_ids_0 (`List[int]`):
372
+ List of IDs.
373
+ token_ids_1 (`List[int]`, *optional*):
374
+ Optional second list of IDs for sequence pairs.
375
+
376
+ Returns:
377
+ `List[int]`: List of zeros.
378
+ """
379
+ sep = [self.sep_token_id]
380
+ cls = [self.cls_token_id]
381
+
382
+ if token_ids_1 is None:
383
+ return len(cls + token_ids_0 + sep) * [0]
384
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
385
+
386
+ def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
387
+ add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
388
+ if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
389
+ text = " " + text
390
+ return (text, kwargs)
391
+
392
+
393
+ __all__ = ["BartTokenizer"]
lib/python3.12/site-packages/transformers/models/bart/tokenization_bart_fast.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import json
17
+ from typing import List, Optional, Tuple
18
+
19
+ from tokenizers import processors
20
+
21
+ from ...tokenization_utils_base import AddedToken, BatchEncoding
22
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
23
+ from ...utils import logging
24
+ from .tokenization_bart import BartTokenizer
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
31
+
32
+ # See all BART models at https://huggingface.co/models?filter=bart
33
+
34
+
35
+ class BartTokenizerFast(PreTrainedTokenizerFast):
36
+ r"""
37
+ Construct a "fast" BART tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2 tokenizer,
38
+ using byte-level Byte-Pair-Encoding.
39
+
40
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
41
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
42
+
43
+ ```python
44
+ >>> from transformers import BartTokenizerFast
45
+
46
+ >>> tokenizer = BartTokenizerFast.from_pretrained("facebook/bart-base")
47
+ >>> tokenizer("Hello world")["input_ids"]
48
+ [0, 31414, 232, 2]
49
+
50
+ >>> tokenizer(" Hello world")["input_ids"]
51
+ [0, 20920, 232, 2]
52
+ ```
53
+
54
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
55
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
56
+
57
+ <Tip>
58
+
59
+ When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
60
+
61
+ </Tip>
62
+
63
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
64
+ refer to this superclass for more information regarding those methods.
65
+
66
+ Args:
67
+ vocab_file (`str`):
68
+ Path to the vocabulary file.
69
+ merges_file (`str`):
70
+ Path to the merges file.
71
+ errors (`str`, *optional*, defaults to `"replace"`):
72
+ Paradigm to follow when decoding bytes to UTF-8. See
73
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
74
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
75
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
76
+
77
+ <Tip>
78
+
79
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
80
+ sequence. The token used is the `cls_token`.
81
+
82
+ </Tip>
83
+
84
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
85
+ The end of sequence token.
86
+
87
+ <Tip>
88
+
89
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
90
+ The token used is the `sep_token`.
91
+
92
+ </Tip>
93
+
94
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
95
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
96
+ sequence classification or for a text and a question for question answering. It is also used as the last
97
+ token of a sequence built with special tokens.
98
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
99
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
100
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
101
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
102
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
103
+ token instead.
104
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
105
+ The token used for padding, for example when batching sequences of different lengths.
106
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
107
+ The token used for masking values. This is the token used when training this model with masked language
108
+ modeling. This is the token which the model will try to predict.
109
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
110
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
111
+ other word. (BART tokenizer detect beginning of words by the preceding space).
112
+ trim_offsets (`bool`, *optional*, defaults to `True`):
113
+ Whether the post processing step should trim offsets to avoid including whitespaces.
114
+ """
115
+
116
+ vocab_files_names = VOCAB_FILES_NAMES
117
+ model_input_names = ["input_ids", "attention_mask"]
118
+ slow_tokenizer_class = BartTokenizer
119
+
120
+ def __init__(
121
+ self,
122
+ vocab_file=None,
123
+ merges_file=None,
124
+ tokenizer_file=None,
125
+ errors="replace",
126
+ bos_token="<s>",
127
+ eos_token="</s>",
128
+ sep_token="</s>",
129
+ cls_token="<s>",
130
+ unk_token="<unk>",
131
+ pad_token="<pad>",
132
+ mask_token="<mask>",
133
+ add_prefix_space=False,
134
+ trim_offsets=True,
135
+ **kwargs,
136
+ ):
137
+ # we have to specify that this tokens is special otherwise adding it will reset the normalized flag to `False` in `add_special_tokens`
138
+ mask_token = (
139
+ AddedToken(mask_token, lstrip=True, normalized=True, special=True)
140
+ if isinstance(mask_token, str)
141
+ else mask_token
142
+ )
143
+ super().__init__(
144
+ vocab_file,
145
+ merges_file,
146
+ tokenizer_file=tokenizer_file,
147
+ errors=errors,
148
+ bos_token=bos_token,
149
+ eos_token=eos_token,
150
+ sep_token=sep_token,
151
+ cls_token=cls_token,
152
+ unk_token=unk_token,
153
+ pad_token=pad_token,
154
+ mask_token=mask_token,
155
+ add_prefix_space=add_prefix_space,
156
+ trim_offsets=trim_offsets,
157
+ **kwargs,
158
+ )
159
+
160
+ # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
161
+ tokenizer_component = "post_processor"
162
+ tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)
163
+ if tokenizer_component_instance:
164
+ state = json.loads(tokenizer_component_instance.__getstate__())
165
+
166
+ # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
167
+ if "sep" in state:
168
+ state["sep"] = tuple(state["sep"])
169
+ if "cls" in state:
170
+ state["cls"] = tuple(state["cls"])
171
+
172
+ changes_to_apply = False
173
+
174
+ if state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
175
+ state["add_prefix_space"] = add_prefix_space
176
+ changes_to_apply = True
177
+
178
+ if state.get("trim_offsets", trim_offsets) != trim_offsets:
179
+ state["trim_offsets"] = trim_offsets
180
+ changes_to_apply = True
181
+
182
+ if changes_to_apply:
183
+ component_class = getattr(processors, state.pop("type"))
184
+ new_value = component_class(**state)
185
+ setattr(self.backend_tokenizer, tokenizer_component, new_value)
186
+
187
+ @property
188
+ def mask_token(self) -> str:
189
+ """
190
+ `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
191
+ having been set.
192
+
193
+ BART tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
194
+ comprise the space before the *<mask>*.
195
+ """
196
+ if self._mask_token is None:
197
+ if self.verbose:
198
+ logger.error("Using mask_token, but it is not set yet.")
199
+ return None
200
+ return str(self._mask_token)
201
+
202
+ @mask_token.setter
203
+ def mask_token(self, value):
204
+ """
205
+ Overriding the default behavior of the mask token to have it eat the space before it.
206
+
207
+ This is needed to preserve backward compatibility with all the previously used models based on Bart.
208
+ """
209
+ # Mask token behave like a normal word, i.e. include the space before it
210
+ # So we set lstrip to True
211
+ value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
212
+ self._mask_token = value
213
+
214
+ def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
215
+ is_split_into_words = kwargs.get("is_split_into_words", False)
216
+
217
+ if is_split_into_words and not self.add_prefix_space:
218
+ raise ValueError(
219
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
220
+ "to use it with pretokenized inputs."
221
+ )
222
+
223
+ return super()._batch_encode_plus(*args, **kwargs)
224
+
225
+ def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
226
+ is_split_into_words = kwargs.get("is_split_into_words", False)
227
+
228
+ if is_split_into_words and not self.add_prefix_space:
229
+ raise ValueError(
230
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
231
+ "to use it with pretokenized inputs."
232
+ )
233
+
234
+ return super()._encode_plus(*args, **kwargs)
235
+
236
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
237
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
238
+ return tuple(files)
239
+
240
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
241
+ output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
242
+ if token_ids_1 is None:
243
+ return output
244
+
245
+ return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]
246
+
247
+ def create_token_type_ids_from_sequences(
248
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
249
+ ) -> List[int]:
250
+ """
251
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. BART does not
252
+ make use of token type ids, therefore a list of zeros is returned.
253
+
254
+ Args:
255
+ token_ids_0 (`List[int]`):
256
+ List of IDs.
257
+ token_ids_1 (`List[int]`, *optional*):
258
+ Optional second list of IDs for sequence pairs.
259
+
260
+ Returns:
261
+ `List[int]`: List of zeros.
262
+ """
263
+ sep = [self.sep_token_id]
264
+ cls = [self.cls_token_id]
265
+
266
+ if token_ids_1 is None:
267
+ return len(cls + token_ids_0 + sep) * [0]
268
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
269
+
270
+
271
+ __all__ = ["BartTokenizerFast"]
lib/python3.12/site-packages/transformers/models/big_bird/__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_big_bird import *
22
+ from .modeling_big_bird import *
23
+ from .modeling_flax_big_bird import *
24
+ from .tokenization_big_bird import *
25
+ from .tokenization_big_bird_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__)
lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (787 Bytes). View file
 
lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/configuration_big_bird.cpython-312.pyc ADDED
Binary file (7.52 kB). View file
 
lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/tokenization_big_bird.cpython-312.pyc ADDED
Binary file (15.8 kB). View file
 
lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/tokenization_big_bird_fast.cpython-312.pyc ADDED
Binary file (10.9 kB). View file
 
lib/python3.12/site-packages/transformers/models/big_bird/configuration_big_bird.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """BigBird model 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 BigBirdConfig(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`BigBirdModel`]. It is used to instantiate an
31
+ BigBird model according to the specified arguments, defining the model architecture. Instantiating a configuration
32
+ with the defaults will yield a similar configuration to that of the BigBird
33
+ [google/bigbird-roberta-base](https://huggingface.co/google/bigbird-roberta-base) architecture.
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 50358):
41
+ Vocabulary size of the BigBird model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`BigBirdModel`].
43
+ hidden_size (`int`, *optional*, defaults to 768):
44
+ Dimension of the encoder layers and the pooler layer.
45
+ num_hidden_layers (`int`, *optional*, defaults to 12):
46
+ Number of hidden layers in the Transformer encoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 12):
48
+ Number of attention heads for each attention layer in the Transformer encoder.
49
+ intermediate_size (`int`, *optional*, defaults to 3072):
50
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
51
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
52
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
53
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
54
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
55
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
56
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
57
+ The dropout ratio for the attention probabilities.
58
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
59
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
60
+ just in case (e.g., 1024 or 2048 or 4096).
61
+ type_vocab_size (`int`, *optional*, defaults to 2):
62
+ The vocabulary size of the `token_type_ids` passed when calling [`BigBirdModel`].
63
+ initializer_range (`float`, *optional*, defaults to 0.02):
64
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
65
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
66
+ The epsilon used by the layer normalization layers.
67
+ is_decoder (`bool`, *optional*, defaults to `False`):
68
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
69
+ use_cache (`bool`, *optional*, defaults to `True`):
70
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
71
+ relevant if `config.is_decoder=True`.
72
+ attention_type (`str`, *optional*, defaults to `"block_sparse"`)
73
+ Whether to use block sparse attention (with n complexity) as introduced in paper or original attention
74
+ layer (with n^2 complexity). Possible values are `"original_full"` and `"block_sparse"`.
75
+ use_bias (`bool`, *optional*, defaults to `True`)
76
+ Whether to use bias in query, key, value.
77
+ rescale_embeddings (`bool`, *optional*, defaults to `False`)
78
+ Whether to rescale embeddings with (hidden_size ** 0.5).
79
+ block_size (`int`, *optional*, defaults to 64)
80
+ Size of each block. Useful only when `attention_type == "block_sparse"`.
81
+ num_random_blocks (`int`, *optional*, defaults to 3)
82
+ Each query is going to attend these many number of random blocks. Useful only when `attention_type ==
83
+ "block_sparse"`.
84
+ classifier_dropout (`float`, *optional*):
85
+ The dropout ratio for the classification head.
86
+
87
+ Example:
88
+
89
+ ```python
90
+ >>> from transformers import BigBirdConfig, BigBirdModel
91
+
92
+ >>> # Initializing a BigBird google/bigbird-roberta-base style configuration
93
+ >>> configuration = BigBirdConfig()
94
+
95
+ >>> # Initializing a model (with random weights) from the google/bigbird-roberta-base style configuration
96
+ >>> model = BigBirdModel(configuration)
97
+
98
+ >>> # Accessing the model configuration
99
+ >>> configuration = model.config
100
+ ```"""
101
+
102
+ model_type = "big_bird"
103
+
104
+ def __init__(
105
+ self,
106
+ vocab_size=50358,
107
+ hidden_size=768,
108
+ num_hidden_layers=12,
109
+ num_attention_heads=12,
110
+ intermediate_size=3072,
111
+ hidden_act="gelu_new",
112
+ hidden_dropout_prob=0.1,
113
+ attention_probs_dropout_prob=0.1,
114
+ max_position_embeddings=4096,
115
+ type_vocab_size=2,
116
+ initializer_range=0.02,
117
+ layer_norm_eps=1e-12,
118
+ use_cache=True,
119
+ pad_token_id=0,
120
+ bos_token_id=1,
121
+ eos_token_id=2,
122
+ sep_token_id=66,
123
+ attention_type="block_sparse",
124
+ use_bias=True,
125
+ rescale_embeddings=False,
126
+ block_size=64,
127
+ num_random_blocks=3,
128
+ classifier_dropout=None,
129
+ **kwargs,
130
+ ):
131
+ super().__init__(
132
+ pad_token_id=pad_token_id,
133
+ bos_token_id=bos_token_id,
134
+ eos_token_id=eos_token_id,
135
+ sep_token_id=sep_token_id,
136
+ **kwargs,
137
+ )
138
+
139
+ self.vocab_size = vocab_size
140
+ self.max_position_embeddings = max_position_embeddings
141
+ self.hidden_size = hidden_size
142
+ self.num_hidden_layers = num_hidden_layers
143
+ self.num_attention_heads = num_attention_heads
144
+ self.intermediate_size = intermediate_size
145
+ self.hidden_act = hidden_act
146
+ self.hidden_dropout_prob = hidden_dropout_prob
147
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
148
+ self.initializer_range = initializer_range
149
+ self.type_vocab_size = type_vocab_size
150
+ self.layer_norm_eps = layer_norm_eps
151
+ self.use_cache = use_cache
152
+
153
+ self.rescale_embeddings = rescale_embeddings
154
+ self.attention_type = attention_type
155
+ self.use_bias = use_bias
156
+ self.block_size = block_size
157
+ self.num_random_blocks = num_random_blocks
158
+ self.classifier_dropout = classifier_dropout
159
+
160
+
161
+ class BigBirdOnnxConfig(OnnxConfig):
162
+ @property
163
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
164
+ if self.task == "multiple-choice":
165
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
166
+ else:
167
+ dynamic_axis = {0: "batch", 1: "sequence"}
168
+ return OrderedDict(
169
+ [
170
+ ("input_ids", dynamic_axis),
171
+ ("attention_mask", dynamic_axis),
172
+ ]
173
+ )
174
+
175
+
176
+ __all__ = ["BigBirdConfig", "BigBirdOnnxConfig"]
lib/python3.12/site-packages/transformers/models/big_bird/modeling_big_bird.py ADDED
The diff for this file is too large to render. See raw diff
 
lib/python3.12/site-packages/transformers/models/big_bird/modeling_flax_big_bird.py ADDED
The diff for this file is too large to render. See raw diff
 
lib/python3.12/site-packages/transformers/models/big_bird/tokenization_big_bird.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Tokenization classes for BigBird."""
16
+
17
+ import os
18
+ import re
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
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
31
+
32
+
33
+ class BigBirdTokenizer(PreTrainedTokenizer):
34
+ """
35
+ Construct a BigBird tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
36
+
37
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
38
+ this superclass for more information regarding those methods.
39
+
40
+ Args:
41
+ vocab_file (`str`):
42
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
43
+ contains the vocabulary necessary to instantiate a tokenizer.
44
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
45
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
46
+ token instead.
47
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
48
+ The begin of sequence token.
49
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
50
+ The end of sequence token.
51
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
52
+ The token used for padding, for example when batching sequences of different lengths.
53
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
54
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
55
+ sequence classification or for a text and a question for question answering. It is also used as the last
56
+ token of a sequence built with special tokens.
57
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
58
+ The token used for masking values. This is the token used when training this model with masked language
59
+ modeling. This is the token which the model will try to predict.
60
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
61
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
62
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
63
+ sp_model_kwargs (`dict`, *optional*):
64
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
65
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
66
+ to set:
67
+
68
+ - `enable_sampling`: Enable subword regularization.
69
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
70
+
71
+ - `nbest_size = {0,1}`: No sampling is performed.
72
+ - `nbest_size > 1`: samples from the nbest_size results.
73
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
74
+ using forward-filtering-and-backward-sampling algorithm.
75
+
76
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
77
+ BPE-dropout.
78
+ """
79
+
80
+ vocab_files_names = VOCAB_FILES_NAMES
81
+ model_input_names = ["input_ids", "attention_mask"]
82
+ prefix_tokens: List[int] = []
83
+
84
+ def __init__(
85
+ self,
86
+ vocab_file,
87
+ unk_token="<unk>",
88
+ bos_token="<s>",
89
+ eos_token="</s>",
90
+ pad_token="<pad>",
91
+ sep_token="[SEP]",
92
+ mask_token="[MASK]",
93
+ cls_token="[CLS]",
94
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
95
+ **kwargs,
96
+ ) -> None:
97
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
98
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
99
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
100
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
101
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
102
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
103
+
104
+ # Mask token behave like a normal word, i.e. include the space before it
105
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
106
+
107
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
108
+
109
+ self.vocab_file = vocab_file
110
+
111
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
112
+ self.sp_model.Load(vocab_file)
113
+
114
+ super().__init__(
115
+ bos_token=bos_token,
116
+ eos_token=eos_token,
117
+ unk_token=unk_token,
118
+ pad_token=pad_token,
119
+ sep_token=sep_token,
120
+ mask_token=mask_token,
121
+ cls_token=cls_token,
122
+ sp_model_kwargs=self.sp_model_kwargs,
123
+ **kwargs,
124
+ )
125
+
126
+ @property
127
+ def vocab_size(self):
128
+ return self.sp_model.get_piece_size()
129
+
130
+ def get_vocab(self):
131
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
132
+ vocab.update(self.added_tokens_encoder)
133
+ return vocab
134
+
135
+ def __getstate__(self):
136
+ state = self.__dict__.copy()
137
+ state["sp_model"] = None
138
+ return state
139
+
140
+ def __setstate__(self, d):
141
+ self.__dict__ = d
142
+
143
+ # for backward compatibility
144
+ if not hasattr(self, "sp_model_kwargs"):
145
+ self.sp_model_kwargs = {}
146
+
147
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
148
+ self.sp_model.Load(self.vocab_file)
149
+
150
+ def _tokenize(self, text: str) -> List[str]:
151
+ """Take as input a string and return a list of strings (tokens) for words/sub-words"""
152
+ return self.sp_model.encode(text, out_type=str)
153
+
154
+ def _convert_token_to_id(self, token):
155
+ """Converts a token (str) in an id using the vocab."""
156
+ return self.sp_model.piece_to_id(token)
157
+
158
+ def _convert_id_to_token(self, index):
159
+ """Converts an index (integer) in a token (str) using the vocab."""
160
+ token = self.sp_model.IdToPiece(index)
161
+ return token
162
+
163
+ # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.convert_tokens_to_string
164
+ def convert_tokens_to_string(self, tokens):
165
+ """Converts a sequence of tokens (string) in a single string."""
166
+ current_sub_tokens = []
167
+ out_string = ""
168
+ prev_is_special = False
169
+ for token in tokens:
170
+ # make sure that special tokens are not decoded using sentencepiece model
171
+ if token in self.all_special_tokens:
172
+ if not prev_is_special:
173
+ out_string += " "
174
+ out_string += self.sp_model.decode(current_sub_tokens) + token
175
+ prev_is_special = True
176
+ current_sub_tokens = []
177
+ else:
178
+ current_sub_tokens.append(token)
179
+ prev_is_special = False
180
+ out_string += self.sp_model.decode(current_sub_tokens)
181
+ return out_string.strip()
182
+
183
+ def _decode(
184
+ self,
185
+ token_ids: List[int],
186
+ skip_special_tokens: bool = False,
187
+ clean_up_tokenization_spaces: Optional[bool] = None,
188
+ spaces_between_special_tokens: bool = True,
189
+ **kwargs,
190
+ ) -> str:
191
+ self._decode_use_source_tokenizer = kwargs.pop("use_source_tokenizer", False)
192
+
193
+ filtered_tokens = self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)
194
+
195
+ # To avoid mixing byte-level and unicode for byte-level BPT
196
+ # we need to build string separately for added tokens and byte-level tokens
197
+ # cf. https://github.com/huggingface/transformers/issues/1133
198
+ sub_texts = []
199
+ current_sub_text = []
200
+ for token in filtered_tokens:
201
+ if skip_special_tokens and token in self.all_special_ids:
202
+ continue
203
+ if token in self.added_tokens_encoder:
204
+ if current_sub_text:
205
+ sub_texts.append(self.convert_tokens_to_string(current_sub_text))
206
+ current_sub_text = []
207
+ sub_texts.append(token)
208
+ else:
209
+ current_sub_text.append(token)
210
+ if current_sub_text:
211
+ sub_texts.append(self.convert_tokens_to_string(current_sub_text))
212
+
213
+ # Mimic the behavior of the Rust tokenizer:
214
+ # No space before [MASK] and [SEP]
215
+ if spaces_between_special_tokens:
216
+ text = re.sub(r" (\[(MASK|SEP)\])", r"\1", " ".join(sub_texts))
217
+ else:
218
+ text = "".join(sub_texts)
219
+
220
+ clean_up_tokenization_spaces = (
221
+ clean_up_tokenization_spaces
222
+ if clean_up_tokenization_spaces is not None
223
+ else self.clean_up_tokenization_spaces
224
+ )
225
+ if clean_up_tokenization_spaces:
226
+ clean_text = self.clean_up_tokenization(text)
227
+ return clean_text
228
+ else:
229
+ return text
230
+
231
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
232
+ if not os.path.isdir(save_directory):
233
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
234
+ return
235
+ out_vocab_file = os.path.join(
236
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
237
+ )
238
+
239
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
240
+ copyfile(self.vocab_file, out_vocab_file)
241
+ elif not os.path.isfile(self.vocab_file):
242
+ with open(out_vocab_file, "wb") as fi:
243
+ content_spiece_model = self.sp_model.serialized_model_proto()
244
+ fi.write(content_spiece_model)
245
+
246
+ return (out_vocab_file,)
247
+
248
+ def build_inputs_with_special_tokens(
249
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
250
+ ) -> List[int]:
251
+ """
252
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
253
+ adding special tokens. A Big Bird sequence has the following format:
254
+
255
+ - single sequence: `[CLS] X [SEP]`
256
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
257
+
258
+ Args:
259
+ token_ids_0 (`List[int]`):
260
+ List of IDs to which the special tokens will be added.
261
+ token_ids_1 (`List[int]`, *optional*):
262
+ Optional second list of IDs for sequence pairs.
263
+
264
+ Returns:
265
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
266
+ """
267
+ if token_ids_1 is None:
268
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
269
+ cls = [self.cls_token_id]
270
+ sep = [self.sep_token_id]
271
+ return cls + token_ids_0 + sep + token_ids_1 + sep
272
+
273
+ def get_special_tokens_mask(
274
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
275
+ ) -> List[int]:
276
+ """
277
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
278
+ special tokens using the tokenizer `prepare_for_model` method.
279
+
280
+ Args:
281
+ token_ids_0 (`List[int]`):
282
+ List of IDs.
283
+ token_ids_1 (`List[int]`, *optional*):
284
+ Optional second list of IDs for sequence pairs.
285
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
286
+ Whether or not the token list is already formatted with special tokens for the model.
287
+
288
+ Returns:
289
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
290
+ """
291
+ if already_has_special_tokens:
292
+ return super().get_special_tokens_mask(
293
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
294
+ )
295
+
296
+ if token_ids_1 is None:
297
+ return [1] + ([0] * len(token_ids_0)) + [1]
298
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
299
+
300
+ def create_token_type_ids_from_sequences(
301
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
302
+ ) -> List[int]:
303
+ """
304
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence
305
+ pair mask has the following format: :: 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second
306
+ sequence | If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
307
+
308
+ Args:
309
+ token_ids_0 (`List[int]`):
310
+ List of IDs.
311
+ token_ids_1 (`List[int]`, *optional*):
312
+ Optional second list of IDs for sequence pairs.
313
+
314
+ Returns:
315
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
316
+ """
317
+ sep = [self.sep_token_id]
318
+ cls = [self.cls_token_id]
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
+
324
+ __all__ = ["BigBirdTokenizer"]
lib/python3.12/site-packages/transformers/models/big_bird/tokenization_big_bird_fast.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 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 Big Bird 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_big_bird import BigBirdTokenizer
28
+ else:
29
+ BigBirdTokenizer = 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 BigBirdTokenizerFast(PreTrainedTokenizerFast):
39
+ """
40
+ Construct a "fast" BigBird tokenizer (backed by HuggingFace's *tokenizers* library). Based on
41
+ [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models). This
42
+ tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should refer to
43
+ this superclass for more information regarding those methods
44
+
45
+ Args:
46
+ vocab_file (`str`):
47
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
48
+ contains the vocabulary necessary to instantiate a tokenizer.
49
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
50
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
51
+
52
+ <Tip>
53
+
54
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
55
+ sequence. The token used is the `cls_token`.
56
+
57
+ </Tip>
58
+
59
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
60
+ The end of sequence token. .. note:: When building a sequence using special tokens, this is not the token
61
+ that is used for the end of sequence. The token used is the `sep_token`.
62
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
63
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
64
+ token instead.
65
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
66
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
67
+ sequence classification or for a text and a question for question answering. It is also used as the last
68
+ token of a sequence built with special tokens.
69
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
70
+ The token used for padding, for example when batching sequences of different lengths.
71
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
72
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
73
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
74
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
75
+ The token used for masking values. This is the token used when training this model with masked language
76
+ modeling. This is the token which the model will try to predict.
77
+ """
78
+
79
+ vocab_files_names = VOCAB_FILES_NAMES
80
+ slow_tokenizer_class = BigBirdTokenizer
81
+ model_input_names = ["input_ids", "attention_mask"]
82
+ prefix_tokens: List[int] = []
83
+
84
+ def __init__(
85
+ self,
86
+ vocab_file=None,
87
+ tokenizer_file=None,
88
+ unk_token="<unk>",
89
+ bos_token="<s>",
90
+ eos_token="</s>",
91
+ pad_token="<pad>",
92
+ sep_token="[SEP]",
93
+ mask_token="[MASK]",
94
+ cls_token="[CLS]",
95
+ **kwargs,
96
+ ):
97
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
98
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
99
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
100
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
101
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
102
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
103
+
104
+ # Mask token behave like a normal word, i.e. include the space before it
105
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
106
+
107
+ super().__init__(
108
+ vocab_file,
109
+ tokenizer_file=tokenizer_file,
110
+ bos_token=bos_token,
111
+ eos_token=eos_token,
112
+ unk_token=unk_token,
113
+ sep_token=sep_token,
114
+ pad_token=pad_token,
115
+ cls_token=cls_token,
116
+ mask_token=mask_token,
117
+ **kwargs,
118
+ )
119
+
120
+ self.vocab_file = vocab_file
121
+
122
+ @property
123
+ def can_save_slow_tokenizer(self) -> bool:
124
+ return os.path.isfile(self.vocab_file) if self.vocab_file else False
125
+
126
+ def build_inputs_with_special_tokens(
127
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
128
+ ) -> List[int]:
129
+ """
130
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
131
+ adding special tokens. An BigBird sequence has the following format:
132
+
133
+ - single sequence: `[CLS] X [SEP]`
134
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
135
+
136
+ Args:
137
+ token_ids_0 (`List[int]`):
138
+ List of IDs to which the special tokens will be added
139
+ token_ids_1 (`List[int]`, *optional*):
140
+ Optional second list of IDs for sequence pairs.
141
+
142
+ Returns:
143
+ `List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
144
+ """
145
+ sep = [self.sep_token_id]
146
+ cls = [self.cls_token_id]
147
+ if token_ids_1 is None:
148
+ return cls + token_ids_0 + sep
149
+ return cls + token_ids_0 + sep + token_ids_1 + sep
150
+
151
+ def get_special_tokens_mask(
152
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
153
+ ) -> List[int]:
154
+ """
155
+ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
156
+ special tokens using the tokenizer `prepare_for_model` method.
157
+
158
+ Args:
159
+ token_ids_0 (`List[int]`):
160
+ List of ids.
161
+ token_ids_1 (`List[int]`, *optional*):
162
+ Optional second list of IDs for sequence pairs.
163
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
164
+ Set to True if the token list is already formatted with special tokens for the model
165
+
166
+ Returns:
167
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
168
+ """
169
+
170
+ if already_has_special_tokens:
171
+ if token_ids_1 is not None:
172
+ raise ValueError(
173
+ "You should not supply a second sequence if the provided sequence of "
174
+ "ids is already formatted with special tokens for the model."
175
+ )
176
+ return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_0]
177
+
178
+ if token_ids_1 is None:
179
+ return [1] + ([0] * len(token_ids_0)) + [1]
180
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
181
+
182
+ def create_token_type_ids_from_sequences(
183
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
184
+ ) -> List[int]:
185
+ """
186
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
187
+ sequence pair mask has the following format:
188
+
189
+ ```
190
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
191
+ | first sequence | second sequence |
192
+ ```
193
+
194
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
195
+
196
+ Args:
197
+ token_ids_0 (`List[int]`):
198
+ List of ids.
199
+ token_ids_1 (`List[int]`, *optional*):
200
+ Optional second list of IDs for sequence pairs.
201
+
202
+ Returns:
203
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
204
+ """
205
+ sep = [self.sep_token_id]
206
+ cls = [self.cls_token_id]
207
+
208
+ if token_ids_1 is None:
209
+ return len(cls + token_ids_0 + sep) * [0]
210
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
211
+
212
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
213
+ if not self.can_save_slow_tokenizer:
214
+ raise ValueError(
215
+ "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
216
+ "tokenizer."
217
+ )
218
+
219
+ if not os.path.isdir(save_directory):
220
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
221
+ return
222
+ out_vocab_file = os.path.join(
223
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
224
+ )
225
+
226
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
227
+ copyfile(self.vocab_file, out_vocab_file)
228
+
229
+ return (out_vocab_file,)
230
+
231
+
232
+ __all__ = ["BigBirdTokenizerFast"]
lib/python3.12/site-packages/transformers/models/blip/__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_blip import *
22
+ from .image_processing_blip import *
23
+ from .image_processing_blip_fast import *
24
+ from .modeling_blip import *
25
+ from .modeling_tf_blip import *
26
+ from .processing_blip 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__)
lib/python3.12/site-packages/transformers/models/blip/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (799 Bytes). View file
 
lib/python3.12/site-packages/transformers/models/blip/__pycache__/configuration_blip.cpython-312.pyc ADDED
Binary file (14.5 kB). View file
 
lib/python3.12/site-packages/transformers/models/blip/__pycache__/image_processing_blip.cpython-312.pyc ADDED
Binary file (14.7 kB). View file
 
lib/python3.12/site-packages/transformers/models/blip/__pycache__/image_processing_blip_fast.cpython-312.pyc ADDED
Binary file (1.12 kB). View file
 
lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_blip.cpython-312.pyc ADDED
Binary file (75.9 kB). View file
 
lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_blip_text.cpython-312.pyc ADDED
Binary file (46.8 kB). View file
 
lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip.cpython-312.pyc ADDED
Binary file (80.5 kB). View file
 
lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip_text.cpython-312.pyc ADDED
Binary file (55 kB). View file
 
lib/python3.12/site-packages/transformers/models/blip/__pycache__/processing_blip.cpython-312.pyc ADDED
Binary file (6.19 kB). View file
 
lib/python3.12/site-packages/transformers/models/blip/configuration_blip.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Blip 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 BlipTextConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`BlipTextModel`]. It is used to instantiate a BLIP
27
+ text model according to the specified arguments, defining the model architecture. Instantiating a configuration
28
+ with the defaults will yield a similar configuration to that of the `BlipText` used by the [base
29
+ architectures](https://huggingface.co/Salesforce/blip-vqa-base).
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 30524):
37
+ Vocabulary size of the `Blip` text model. Defines the number of different tokens that can be represented by
38
+ the `inputs_ids` passed when calling [`BlipModel`].
39
+ hidden_size (`int`, *optional*, defaults to 768):
40
+ Dimensionality of the encoder layers and the pooler layer.
41
+ encoder_hidden_size (`int`, *optional*, defaults to 768):
42
+ Dimensionality of the encoder layers from the vision model.
43
+ intermediate_size (`int`, *optional*, defaults to 3072):
44
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
45
+ num_hidden_layers (`int`, *optional*, defaults to 12):
46
+ Number of hidden layers in the Transformer encoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 8):
48
+ Number of attention heads for each attention layer in the Transformer encoder.
49
+ max_position_embeddings (`int`, *optional*, defaults to 512):
50
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
51
+ just in case (e.g., 512 or 1024 or 2048).
52
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
53
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
54
+ `"relu"`, `"selu"` and `"gelu_new"` `"gelu"` are supported.
55
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
56
+ The epsilon used by the layer normalization layers.
57
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
58
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
59
+ attention_dropout (`float`, *optional*, defaults to 0.0):
60
+ The dropout ratio for the attention probabilities.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ bos_token_id (`int`, *optional*, defaults to 30522):
64
+ The id of the `beginning-of-sequence` token.
65
+ eos_token_id (`int`, *optional*, defaults to 2):
66
+ The id of the `end-of-sequence` token.
67
+ pad_token_id (`int`, *optional*, defaults to 0):
68
+ The id of the `padding` token.
69
+ sep_token_id (`int`, *optional*, defaults to 102):
70
+ The id of the `separator` token.
71
+ is_decoder (`bool`, *optional*, defaults to `True`):
72
+ Whether the model is used as a decoder.
73
+ use_cache (`bool`, *optional*, defaults to `True`):
74
+ Whether or not the model should return the last key/values attentions (not used by all models).
75
+ label_smoothing (float, *optional*):
76
+ A float in [0.0, 1.0]. Specifies the amount of smoothing when computing the loss, where 0.0 means no smoothing. The targets
77
+ become a mixture of the original ground truth and a uniform distribution as described in
78
+ `Rethinking the Inception Architecture for Computer Vision <https://arxiv.org/abs/1512.00567>`__. Default: :math:`0.0`.
79
+
80
+ Example:
81
+
82
+ ```python
83
+ >>> from transformers import BlipTextConfig, BlipTextModel
84
+
85
+ >>> # Initializing a BlipTextConfig with Salesforce/blip-vqa-base style configuration
86
+ >>> configuration = BlipTextConfig()
87
+
88
+ >>> # Initializing a BlipTextModel (with random weights) from the Salesforce/blip-vqa-base style configuration
89
+ >>> model = BlipTextModel(configuration)
90
+
91
+ >>> # Accessing the model configuration
92
+ >>> configuration = model.config
93
+ ```"""
94
+
95
+ model_type = "blip_text_model"
96
+ base_config_key = "text_config"
97
+
98
+ def __init__(
99
+ self,
100
+ vocab_size=30524,
101
+ hidden_size=768,
102
+ encoder_hidden_size=768,
103
+ intermediate_size=3072,
104
+ projection_dim=768,
105
+ num_hidden_layers=12,
106
+ num_attention_heads=8,
107
+ max_position_embeddings=512,
108
+ hidden_act="gelu",
109
+ layer_norm_eps=1e-12,
110
+ hidden_dropout_prob=0.0,
111
+ attention_probs_dropout_prob=0.0,
112
+ initializer_range=0.02,
113
+ bos_token_id=30522,
114
+ eos_token_id=2,
115
+ pad_token_id=0,
116
+ sep_token_id=102,
117
+ is_decoder=True,
118
+ use_cache=True,
119
+ label_smoothing=0.0,
120
+ **kwargs,
121
+ ):
122
+ super().__init__(
123
+ pad_token_id=pad_token_id,
124
+ bos_token_id=bos_token_id,
125
+ eos_token_id=eos_token_id,
126
+ sep_token_id=sep_token_id,
127
+ **kwargs,
128
+ )
129
+
130
+ self.vocab_size = vocab_size
131
+ self.hidden_size = hidden_size
132
+ self.encoder_hidden_size = encoder_hidden_size
133
+ self.intermediate_size = intermediate_size
134
+ self.projection_dim = projection_dim
135
+ self.hidden_dropout_prob = hidden_dropout_prob
136
+ self.num_hidden_layers = num_hidden_layers
137
+ self.num_attention_heads = num_attention_heads
138
+ self.max_position_embeddings = max_position_embeddings
139
+ self.layer_norm_eps = layer_norm_eps
140
+ self.hidden_act = hidden_act
141
+ self.initializer_range = initializer_range
142
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
143
+ self.is_decoder = is_decoder
144
+ self.use_cache = use_cache
145
+ self.label_smoothing = label_smoothing
146
+
147
+
148
+ class BlipVisionConfig(PretrainedConfig):
149
+ r"""
150
+ This is the configuration class to store the configuration of a [`BlipVisionModel`]. It is used to instantiate a
151
+ BLIP vision model according to the specified arguments, defining the model architecture. Instantiating a
152
+ configuration defaults will yield a similar configuration to that of the Blip-base
153
+ [Salesforce/blip-vqa-base](https://huggingface.co/Salesforce/blip-vqa-base) architecture.
154
+
155
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
156
+ documentation from [`PretrainedConfig`] for more information.
157
+
158
+
159
+ Args:
160
+ hidden_size (`int`, *optional*, defaults to 768):
161
+ Dimensionality of the encoder layers and the pooler layer.
162
+ intermediate_size (`int`, *optional*, defaults to 3072):
163
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
164
+ num_hidden_layers (`int`, *optional*, defaults to 12):
165
+ Number of hidden layers in the Transformer encoder.
166
+ num_attention_heads (`int`, *optional*, defaults to 12):
167
+ Number of attention heads for each attention layer in the Transformer encoder.
168
+ image_size (`int`, *optional*, defaults to 384):
169
+ The size (resolution) of each image.
170
+ patch_size (`int`, *optional*, defaults to 16):
171
+ The size (resolution) of each patch.
172
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
173
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
174
+ `"relu"`, `"selu"` and `"gelu_new"` `"gelu"` are supported.
175
+ layer_norm_eps (`float`, *optional*, defaults to 1e-5):
176
+ The epsilon used by the layer normalization layers.
177
+ attention_dropout (`float`, *optional*, defaults to 0.0):
178
+ The dropout ratio for the attention probabilities.
179
+ initializer_range (`float`, *optional*, defaults to 1e-10):
180
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
181
+
182
+ Example:
183
+
184
+ ```python
185
+ >>> from transformers import BlipVisionConfig, BlipVisionModel
186
+
187
+ >>> # Initializing a BlipVisionConfig with Salesforce/blip-vqa-base style configuration
188
+ >>> configuration = BlipVisionConfig()
189
+
190
+ >>> # Initializing a BlipVisionModel (with random weights) from the Salesforce/blip-vqa-base style configuration
191
+ >>> model = BlipVisionModel(configuration)
192
+
193
+ >>> # Accessing the model configuration
194
+ >>> configuration = model.config
195
+ ```"""
196
+
197
+ model_type = "blip_vision_model"
198
+ base_config_key = "vision_config"
199
+
200
+ def __init__(
201
+ self,
202
+ hidden_size=768,
203
+ intermediate_size=3072,
204
+ projection_dim=512,
205
+ num_hidden_layers=12,
206
+ num_attention_heads=12,
207
+ image_size=384,
208
+ patch_size=16,
209
+ hidden_act="gelu",
210
+ layer_norm_eps=1e-5,
211
+ attention_dropout=0.0,
212
+ initializer_range=1e-10,
213
+ **kwargs,
214
+ ):
215
+ super().__init__(**kwargs)
216
+
217
+ self.hidden_size = hidden_size
218
+ self.intermediate_size = intermediate_size
219
+ self.projection_dim = projection_dim
220
+ self.num_hidden_layers = num_hidden_layers
221
+ self.num_attention_heads = num_attention_heads
222
+ self.patch_size = patch_size
223
+ self.image_size = image_size
224
+ self.initializer_range = initializer_range
225
+ self.attention_dropout = attention_dropout
226
+ self.layer_norm_eps = layer_norm_eps
227
+ self.hidden_act = hidden_act
228
+
229
+
230
+ class BlipConfig(PretrainedConfig):
231
+ r"""
232
+ [`BlipConfig`] is the configuration class to store the configuration of a [`BlipModel`]. It is used to instantiate
233
+ a BLIP model according to the specified arguments, defining the text model and vision model configs. Instantiating
234
+ a configuration with the defaults will yield a similar configuration to that of the BLIP-base
235
+ [Salesforce/blip-vqa-base](https://huggingface.co/Salesforce/blip-vqa-base) architecture.
236
+
237
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
238
+ documentation from [`PretrainedConfig`] for more information.
239
+
240
+ Args:
241
+ text_config (`dict`, *optional*):
242
+ Dictionary of configuration options used to initialize [`BlipTextConfig`].
243
+ vision_config (`dict`, *optional*):
244
+ Dictionary of configuration options used to initialize [`BlipVisionConfig`].
245
+ projection_dim (`int`, *optional*, defaults to 512):
246
+ Dimensionality of text and vision projection layers.
247
+ logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
248
+ The initial value of the *logit_scale* parameter. Default is used as per the original BLIP implementation.
249
+ image_text_hidden_size (`int`, *optional*, defaults to 256):
250
+ Dimensionality of the hidden state of the image-text fusion layer.
251
+ label_smoothing (float, optional, *optional*, defaults to 0.0):
252
+ A float in [0.0, 1.0]. Specifies the amount of smoothing when computing the loss, where 0.0 means no smoothing. The targets
253
+ become a mixture of the original ground truth and a uniform distribution as described in
254
+ `Rethinking the Inception Architecture for Computer Vision <https://arxiv.org/abs/1512.00567>`__. Default: :math:`0.0`.
255
+ kwargs (*optional*):
256
+ Dictionary of keyword arguments.
257
+
258
+ Example:
259
+
260
+ ```python
261
+ >>> from transformers import BlipConfig, BlipModel
262
+
263
+ >>> # Initializing a BlipConfig with Salesforce/blip-vqa-base style configuration
264
+ >>> configuration = BlipConfig()
265
+
266
+ >>> # Initializing a BlipPModel (with random weights) from the Salesforce/blip-vqa-base style configuration
267
+ >>> model = BlipModel(configuration)
268
+
269
+ >>> # Accessing the model configuration
270
+ >>> configuration = model.config
271
+
272
+ >>> # We can also initialize a BlipConfig from a BlipTextConfig and a BlipVisionConfig
273
+
274
+ >>> # Initializing a BLIPText and BLIPVision configuration
275
+ >>> config_text = BlipTextConfig()
276
+ >>> config_vision = BlipVisionConfig()
277
+
278
+ >>> config = BlipConfig.from_text_vision_configs(config_text, config_vision)
279
+ ```"""
280
+
281
+ model_type = "blip"
282
+ sub_configs = {"text_config": BlipTextConfig, "vision_config": BlipVisionConfig}
283
+
284
+ def __init__(
285
+ self,
286
+ text_config=None,
287
+ vision_config=None,
288
+ projection_dim=512,
289
+ logit_scale_init_value=2.6592,
290
+ image_text_hidden_size=256,
291
+ label_smoothing=0.0,
292
+ **kwargs,
293
+ ):
294
+ super().__init__(**kwargs)
295
+
296
+ if text_config is None:
297
+ text_config = {}
298
+ logger.info("`text_config` is `None`. Initializing the `BlipTextConfig` with default values.")
299
+
300
+ if vision_config is None:
301
+ vision_config = {}
302
+ logger.info("`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.")
303
+
304
+ self.text_config = BlipTextConfig(**text_config)
305
+ self.vision_config = BlipVisionConfig(**vision_config)
306
+
307
+ self.text_config.encoder_hidden_size = self.vision_config.hidden_size
308
+
309
+ self.projection_dim = projection_dim
310
+ self.logit_scale_init_value = logit_scale_init_value
311
+ self.initializer_factor = 1.0
312
+ self.initializer_range = 0.02
313
+ self.image_text_hidden_size = image_text_hidden_size
314
+ self.label_smoothing = label_smoothing
315
+
316
+ @classmethod
317
+ def from_text_vision_configs(cls, text_config: BlipTextConfig, vision_config: BlipVisionConfig, **kwargs):
318
+ r"""
319
+ Instantiate a [`BlipConfig`] (or a derived class) from blip text model configuration and blip vision model
320
+ configuration.
321
+
322
+ Returns:
323
+ [`BlipConfig`]: An instance of a configuration object
324
+ """
325
+
326
+ return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
327
+
328
+
329
+ __all__ = ["BlipConfig", "BlipTextConfig", "BlipVisionConfig"]
lib/python3.12/site-packages/transformers/models/blip/image_processing_blip.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 BLIP."""
16
+
17
+ from typing import Dict, List, Optional, Union
18
+
19
+ import numpy as np
20
+
21
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
22
+ from ...image_transforms import convert_to_rgb, resize, to_channel_dimension_format
23
+ from ...image_utils import (
24
+ OPENAI_CLIP_MEAN,
25
+ OPENAI_CLIP_STD,
26
+ ChannelDimension,
27
+ ImageInput,
28
+ PILImageResampling,
29
+ infer_channel_dimension_format,
30
+ is_scaled_image,
31
+ make_flat_list_of_images,
32
+ to_numpy_array,
33
+ valid_images,
34
+ validate_preprocess_arguments,
35
+ )
36
+ from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
37
+
38
+
39
+ if is_vision_available():
40
+ import PIL
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ class BlipImageProcessor(BaseImageProcessor):
47
+ r"""
48
+ Constructs a BLIP image processor.
49
+
50
+ Args:
51
+ do_resize (`bool`, *optional*, defaults to `True`):
52
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
53
+ `do_resize` parameter in the `preprocess` method.
54
+ size (`dict`, *optional*, defaults to `{"height": 384, "width": 384}`):
55
+ Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
56
+ method.
57
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
58
+ Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`. Can be
59
+ overridden by the `resample` parameter in the `preprocess` method.
60
+ do_rescale (`bool`, *optional*, defaults to `True`):
61
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
62
+ `do_rescale` parameter in the `preprocess` method.
63
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
64
+ Scale factor to use if rescaling the image. Only has an effect if `do_rescale` is set to `True`. Can be
65
+ overridden by the `rescale_factor` parameter in the `preprocess` method.
66
+ do_normalize (`bool`, *optional*, defaults to `True`):
67
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
68
+ method. Can be overridden by the `do_normalize` parameter in the `preprocess` method.
69
+ image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
70
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
71
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be
72
+ overridden by the `image_mean` parameter in the `preprocess` method.
73
+ image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
74
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
75
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
76
+ Can be overridden by the `image_std` parameter in the `preprocess` method.
77
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
78
+ Whether to convert the image to RGB.
79
+ """
80
+
81
+ model_input_names = ["pixel_values"]
82
+
83
+ def __init__(
84
+ self,
85
+ do_resize: bool = True,
86
+ size: Dict[str, int] = None,
87
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
88
+ do_rescale: bool = True,
89
+ rescale_factor: Union[int, float] = 1 / 255,
90
+ do_normalize: bool = True,
91
+ image_mean: Optional[Union[float, List[float]]] = None,
92
+ image_std: Optional[Union[float, List[float]]] = None,
93
+ do_convert_rgb: bool = True,
94
+ **kwargs,
95
+ ) -> None:
96
+ super().__init__(**kwargs)
97
+ size = size if size is not None else {"height": 384, "width": 384}
98
+ size = get_size_dict(size, default_to_square=True)
99
+
100
+ self.do_resize = do_resize
101
+ self.size = size
102
+ self.resample = resample
103
+ self.do_rescale = do_rescale
104
+ self.rescale_factor = rescale_factor
105
+ self.do_normalize = do_normalize
106
+ self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
107
+ self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
108
+ self.do_convert_rgb = do_convert_rgb
109
+
110
+ # Copied from transformers.models.vit.image_processing_vit.ViTImageProcessor.resize with PILImageResampling.BILINEAR->PILImageResampling.BICUBIC
111
+ def resize(
112
+ self,
113
+ image: np.ndarray,
114
+ size: Dict[str, int],
115
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
116
+ data_format: Optional[Union[str, ChannelDimension]] = None,
117
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
118
+ **kwargs,
119
+ ) -> np.ndarray:
120
+ """
121
+ Resize an image to `(size["height"], size["width"])`.
122
+
123
+ Args:
124
+ image (`np.ndarray`):
125
+ Image to resize.
126
+ size (`Dict[str, int]`):
127
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
128
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
129
+ `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BICUBIC`.
130
+ data_format (`ChannelDimension` or `str`, *optional*):
131
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
132
+ image is used. Can be one of:
133
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
134
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
135
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
136
+ input_data_format (`ChannelDimension` or `str`, *optional*):
137
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
138
+ from the input image. Can be one of:
139
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
140
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
141
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
142
+
143
+ Returns:
144
+ `np.ndarray`: The resized image.
145
+ """
146
+ size = get_size_dict(size)
147
+ if "height" not in size or "width" not in size:
148
+ raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
149
+ output_size = (size["height"], size["width"])
150
+ return resize(
151
+ image,
152
+ size=output_size,
153
+ resample=resample,
154
+ data_format=data_format,
155
+ input_data_format=input_data_format,
156
+ **kwargs,
157
+ )
158
+
159
+ @filter_out_non_signature_kwargs()
160
+ def preprocess(
161
+ self,
162
+ images: ImageInput,
163
+ do_resize: Optional[bool] = None,
164
+ size: Optional[Dict[str, int]] = None,
165
+ resample: PILImageResampling = None,
166
+ do_rescale: Optional[bool] = None,
167
+ rescale_factor: Optional[float] = None,
168
+ do_normalize: Optional[bool] = None,
169
+ image_mean: Optional[Union[float, List[float]]] = None,
170
+ image_std: Optional[Union[float, List[float]]] = None,
171
+ return_tensors: Optional[Union[str, TensorType]] = None,
172
+ do_convert_rgb: Optional[bool] = None,
173
+ data_format: ChannelDimension = ChannelDimension.FIRST,
174
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
175
+ ) -> PIL.Image.Image:
176
+ """
177
+ Preprocess an image or batch of images.
178
+
179
+ Args:
180
+ images (`ImageInput`):
181
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
182
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
183
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
184
+ Whether to resize the image.
185
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
186
+ Controls the size of the image after `resize`. The shortest edge of the image is resized to
187
+ `size["shortest_edge"]` whilst preserving the aspect ratio. If the longest edge of this resized image
188
+ is > `int(size["shortest_edge"] * (1333 / 800))`, then the image is resized again to make the longest
189
+ edge equal to `int(size["shortest_edge"] * (1333 / 800))`.
190
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
191
+ Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`.
192
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
193
+ Whether to rescale the image values between [0 - 1].
194
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
195
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
196
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
197
+ Whether to normalize the image.
198
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
199
+ Image mean to normalize the image by if `do_normalize` is set to `True`.
200
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
201
+ Image standard deviation to normalize the image by if `do_normalize` is set to `True`.
202
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
203
+ Whether to convert the image to RGB.
204
+ return_tensors (`str` or `TensorType`, *optional*):
205
+ The type of tensors to return. Can be one of:
206
+ - Unset: Return a list of `np.ndarray`.
207
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
208
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
209
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
210
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
211
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
212
+ The channel dimension format for the output image. Can be one of:
213
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
214
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
215
+ - Unset: Use the channel dimension format of the input image.
216
+ input_data_format (`ChannelDimension` or `str`, *optional*):
217
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
218
+ from the input image. Can be one of:
219
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
220
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
221
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
222
+ """
223
+ do_resize = do_resize if do_resize is not None else self.do_resize
224
+ resample = resample if resample is not None else self.resample
225
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
226
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
227
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
228
+ image_mean = image_mean if image_mean is not None else self.image_mean
229
+ image_std = image_std if image_std is not None else self.image_std
230
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
231
+
232
+ size = size if size is not None else self.size
233
+ size = get_size_dict(size, default_to_square=False)
234
+ images = make_flat_list_of_images(images)
235
+
236
+ if not valid_images(images):
237
+ raise ValueError(
238
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
239
+ "torch.Tensor, tf.Tensor or jax.ndarray."
240
+ )
241
+
242
+ validate_preprocess_arguments(
243
+ do_rescale=do_rescale,
244
+ rescale_factor=rescale_factor,
245
+ do_normalize=do_normalize,
246
+ image_mean=image_mean,
247
+ image_std=image_std,
248
+ do_resize=do_resize,
249
+ size=size,
250
+ resample=resample,
251
+ )
252
+ # PIL RGBA images are converted to RGB
253
+ if do_convert_rgb:
254
+ images = [convert_to_rgb(image) for image in images]
255
+
256
+ # All transformations expect numpy arrays.
257
+ images = [to_numpy_array(image) for image in images]
258
+
259
+ if do_rescale and is_scaled_image(images[0]):
260
+ logger.warning_once(
261
+ "It looks like you are trying to rescale already rescaled images. If the input"
262
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
263
+ )
264
+
265
+ if input_data_format is None:
266
+ # We assume that all images have the same channel dimension format.
267
+ input_data_format = infer_channel_dimension_format(images[0])
268
+
269
+ if do_resize:
270
+ images = [
271
+ self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
272
+ for image in images
273
+ ]
274
+
275
+ if do_rescale:
276
+ images = [
277
+ self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
278
+ for image in images
279
+ ]
280
+
281
+ if do_normalize:
282
+ images = [
283
+ self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
284
+ for image in images
285
+ ]
286
+
287
+ images = [
288
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
289
+ ]
290
+
291
+ encoded_outputs = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors)
292
+
293
+ return encoded_outputs
294
+
295
+
296
+ __all__ = ["BlipImageProcessor"]
lib/python3.12/site-packages/transformers/models/blip/image_processing_blip_fast.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Fast Image processor class for BLIP."""
16
+
17
+ from ...image_processing_utils_fast import BASE_IMAGE_PROCESSOR_FAST_DOCSTRING, BaseImageProcessorFast
18
+ from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, PILImageResampling
19
+ from ...utils import add_start_docstrings
20
+
21
+
22
+ @add_start_docstrings(
23
+ "Constructs a fast BLIP image processor.",
24
+ BASE_IMAGE_PROCESSOR_FAST_DOCSTRING,
25
+ )
26
+ class BlipImageProcessorFast(BaseImageProcessorFast):
27
+ # To be checked against the slow image processor
28
+ # None values left after checking can be removed
29
+ resample = PILImageResampling.BICUBIC
30
+ image_mean = OPENAI_CLIP_MEAN
31
+ image_std = OPENAI_CLIP_STD
32
+ size = {"height": 384, "width": 384}
33
+ do_resize = True
34
+ do_rescale = True
35
+ do_normalize = True
36
+ do_convert_rgb = True
37
+
38
+
39
+ __all__ = ["BlipImageProcessorFast"]
lib/python3.12/site-packages/transformers/models/blip/modeling_blip.py ADDED
@@ -0,0 +1,1605 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Salesforce Team 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 BLIP model."""
16
+
17
+ import warnings
18
+ from dataclasses import dataclass
19
+ from typing import Any, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn.functional import normalize
25
+
26
+ from ...activations import ACT2FN
27
+ from ...generation import GenerationMixin
28
+ from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...utils import (
31
+ ModelOutput,
32
+ add_start_docstrings,
33
+ add_start_docstrings_to_model_forward,
34
+ logging,
35
+ replace_return_docstrings,
36
+ torch_int,
37
+ )
38
+ from .configuration_blip import BlipConfig, BlipTextConfig, BlipVisionConfig
39
+ from .modeling_blip_text import BlipTextLMHeadModel, BlipTextModel
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+ _CHECKPOINT_FOR_DOC = "Salesforce/blip-vqa-base"
45
+
46
+
47
+ # Copied from transformers.models.clip.modeling_clip.contrastive_loss
48
+ def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
49
+ return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
50
+
51
+
52
+ # Copied from transformers.models.clip.modeling_clip.clip_loss with clip->blip
53
+ def blip_loss(similarity: torch.Tensor) -> torch.Tensor:
54
+ caption_loss = contrastive_loss(similarity)
55
+ image_loss = contrastive_loss(similarity.t())
56
+ return (caption_loss + image_loss) / 2.0
57
+
58
+
59
+ @dataclass
60
+ class BlipForConditionalGenerationModelOutput(ModelOutput):
61
+ """
62
+ Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
63
+ last hidden states. This class also adds the loss term from the text decoder.
64
+
65
+ Args:
66
+ loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
67
+ Languge modeling loss from the text decoder.
68
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`, *optional*):
69
+ Prediction scores of the language modeling head of the text decoder model.
70
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*):
71
+ The image embeddings obtained after applying the Vision Transformer model to the input image.
72
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
73
+ Sequence of hidden-states at the output of the last layer of the model.
74
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):
75
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
76
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
77
+
78
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
79
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed):
80
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
81
+ sequence_length)`.
82
+
83
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
84
+ heads.
85
+ """
86
+
87
+ loss: Optional[Tuple[torch.FloatTensor]] = None
88
+ logits: Optional[Tuple[torch.FloatTensor]] = None
89
+ image_embeds: Optional[torch.FloatTensor] = None
90
+ last_hidden_state: Optional[torch.FloatTensor] = None
91
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
92
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
93
+
94
+ @property
95
+ def decoder_logits(self):
96
+ warnings.warn(
97
+ "`decoder_logits` attribute is deprecated and will be removed in version 5 of Transformers."
98
+ " Please use the `logits` attribute to retrieve the final output instead.",
99
+ FutureWarning,
100
+ )
101
+ return self.logits
102
+
103
+
104
+ @dataclass
105
+ class BlipTextVisionModelOutput(ModelOutput):
106
+ """
107
+ Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
108
+ last hidden states. This class also adds the loss term from the text decoder.
109
+
110
+ Args:
111
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
112
+ Languge modeling loss from the text decoder.
113
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
114
+ The image embeddings obtained by applying the projection layer to the pooler_output.
115
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
116
+ Sequence of hidden-states at the output of the last layer of the model.
117
+ 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 model at the output of each layer plus the optional initial embedding outputs.
122
+ 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 after the attention softmax, used to compute the weighted average in the self-attention
127
+ heads.
128
+ """
129
+
130
+ loss: Optional[torch.FloatTensor] = None
131
+ image_embeds: Optional[torch.FloatTensor] = None
132
+ last_hidden_state: Optional[torch.FloatTensor] = None
133
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
134
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
135
+
136
+
137
+ @dataclass
138
+ class BlipImageTextMatchingModelOutput(ModelOutput):
139
+ """
140
+ Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
141
+ last hidden states. This class also adds the loss term from the text decoder as well as the image-text similarity
142
+ scores.
143
+
144
+ Args:
145
+ itm_score (`torch.FloatTensor`):
146
+ The image-text similarity scores.
147
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
148
+ Languge modeling loss from the text decoder.
149
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
150
+ The image embeddings obtained by applying the projection layer to the pooler_output.
151
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
152
+ Sequence of hidden-states at the output of the last layer of the model.
153
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
154
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
155
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
156
+
157
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
158
+ vision_pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*):
159
+ Last layer hidden-state of the vision of the vision-only branch of the model.
160
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
161
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
162
+ sequence_length)`.
163
+
164
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
165
+ heads.
166
+ question_embeds (`torch.FloatTensor`):
167
+ The question embeddings obtained by the text projection layer.
168
+ """
169
+
170
+ itm_score: Optional[torch.FloatTensor] = None
171
+ loss: Optional[torch.FloatTensor] = None
172
+ image_embeds: Optional[torch.FloatTensor] = None
173
+ last_hidden_state: Optional[torch.FloatTensor] = None
174
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
175
+ vision_pooler_output: Optional[torch.FloatTensor] = None
176
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
177
+ question_embeds: Optional[Tuple[torch.FloatTensor]] = None
178
+
179
+
180
+ @dataclass
181
+ class BlipOutput(ModelOutput):
182
+ """
183
+ Args:
184
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
185
+ Contrastive loss for image-text similarity.
186
+ logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
187
+ The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
188
+ similarity scores.
189
+ logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
190
+ The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
191
+ similarity scores.
192
+ text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
193
+ The text embeddings obtained by applying the projection layer to the pooled output of [`BlipTextModel`].
194
+ image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
195
+ The image embeddings obtained by applying the projection layer to the pooled output of [`BlipVisionModel`].
196
+ text_model_output(`BaseModelOutputWithPooling`):
197
+ The output of the [`BlipTextModel`].
198
+ vision_model_output(`BaseModelOutputWithPooling`):
199
+ The output of the [`BlipVisionModel`].
200
+ """
201
+
202
+ loss: Optional[torch.FloatTensor] = None
203
+ logits_per_image: Optional[torch.FloatTensor] = None
204
+ logits_per_text: Optional[torch.FloatTensor] = None
205
+ text_embeds: Optional[torch.FloatTensor] = None
206
+ image_embeds: Optional[torch.FloatTensor] = None
207
+ text_model_output: BaseModelOutputWithPooling = None
208
+ vision_model_output: BaseModelOutputWithPooling = None
209
+
210
+ def to_tuple(self) -> Tuple[Any]:
211
+ return tuple(
212
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
213
+ for k in self.keys()
214
+ )
215
+
216
+
217
+ class BlipVisionEmbeddings(nn.Module):
218
+ def __init__(self, config: BlipVisionConfig):
219
+ super().__init__()
220
+ self.config = config
221
+ self.embed_dim = config.hidden_size
222
+ self.image_size = config.image_size
223
+ self.patch_size = config.patch_size
224
+
225
+ self.class_embedding = nn.Parameter(torch.randn(1, 1, self.embed_dim))
226
+
227
+ self.patch_embedding = nn.Conv2d(
228
+ in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
229
+ )
230
+
231
+ self.num_patches = (self.image_size // self.patch_size) ** 2
232
+ self.num_positions = self.num_patches + 1
233
+
234
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
235
+
236
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
237
+ """
238
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
239
+ images. This method is also adapted to support torch.jit tracing.
240
+
241
+ Adapted from:
242
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
243
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
244
+ """
245
+
246
+ num_patches = embeddings.shape[1] - 1
247
+ num_positions = self.position_embedding.shape[1] - 1
248
+
249
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
250
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
251
+ return self.position_embedding
252
+
253
+ class_pos_embed = self.position_embedding[:, :1]
254
+ patch_pos_embed = self.position_embedding[:, 1:]
255
+
256
+ dim = embeddings.shape[-1]
257
+
258
+ new_height = height // self.patch_size
259
+ new_width = width // self.patch_size
260
+
261
+ sqrt_num_positions = torch_int(num_positions**0.5)
262
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
263
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
264
+
265
+ patch_pos_embed = nn.functional.interpolate(
266
+ patch_pos_embed,
267
+ size=(new_height, new_width),
268
+ mode="bicubic",
269
+ align_corners=False,
270
+ )
271
+
272
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
273
+
274
+ return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
275
+
276
+ def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
277
+ batch_size, _, height, width = pixel_values.shape
278
+ target_dtype = self.patch_embedding.weight.dtype
279
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
280
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
281
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
282
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
283
+ if interpolate_pos_encoding:
284
+ position_embedding = self.interpolate_pos_encoding(embeddings, height, width)
285
+ else:
286
+ position_embedding = self.position_embedding
287
+ embeddings = embeddings + position_embedding[:, : embeddings.size(1), :].to(target_dtype)
288
+ return embeddings
289
+
290
+
291
+ # Copied from transformers.models.clip.modeling_clip.CLIPTextEmbeddings with CLIP->Blip
292
+ class BlipTextEmbeddings(nn.Module):
293
+ def __init__(self, config: BlipTextConfig):
294
+ super().__init__()
295
+ embed_dim = config.hidden_size
296
+
297
+ self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
298
+ self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
299
+
300
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
301
+ self.register_buffer(
302
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
303
+ )
304
+
305
+ def forward(
306
+ self,
307
+ input_ids: Optional[torch.LongTensor] = None,
308
+ position_ids: Optional[torch.LongTensor] = None,
309
+ inputs_embeds: Optional[torch.FloatTensor] = None,
310
+ ) -> torch.Tensor:
311
+ seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
312
+ max_position_embedding = self.position_embedding.weight.shape[0]
313
+
314
+ if seq_length > max_position_embedding:
315
+ raise ValueError(
316
+ f"Sequence length must be less than max_position_embeddings (got `sequence length`: "
317
+ f"{seq_length} and max_position_embeddings: {max_position_embedding}"
318
+ )
319
+
320
+ if position_ids is None:
321
+ position_ids = self.position_ids[:, :seq_length]
322
+
323
+ if inputs_embeds is None:
324
+ inputs_embeds = self.token_embedding(input_ids)
325
+
326
+ position_embeddings = self.position_embedding(position_ids)
327
+ embeddings = inputs_embeds + position_embeddings
328
+
329
+ return embeddings
330
+
331
+
332
+ class BlipAttention(nn.Module):
333
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
334
+
335
+ def __init__(self, config):
336
+ super().__init__()
337
+ self.config = config
338
+ self.embed_dim = config.hidden_size
339
+ self.num_heads = config.num_attention_heads
340
+ self.head_dim = self.embed_dim // self.num_heads
341
+ if self.head_dim * self.num_heads != self.embed_dim:
342
+ raise ValueError(
343
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
344
+ f" {self.num_heads})."
345
+ )
346
+ self.scale = self.head_dim**-0.5
347
+ self.dropout = nn.Dropout(config.attention_dropout)
348
+
349
+ self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim)
350
+
351
+ self.projection = nn.Linear(self.embed_dim, self.embed_dim)
352
+
353
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
354
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
355
+
356
+ def forward(
357
+ self,
358
+ hidden_states: torch.Tensor,
359
+ head_mask: Optional[torch.Tensor] = None,
360
+ output_attentions: Optional[bool] = False,
361
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
362
+ """Input shape: Batch x Time x Channel"""
363
+
364
+ bsz, tgt_len, embed_dim = hidden_states.size()
365
+
366
+ mixed_qkv = (
367
+ self.qkv(hidden_states)
368
+ .reshape(bsz, tgt_len, 3, self.num_heads, embed_dim // self.num_heads)
369
+ .permute(2, 0, 3, 1, 4)
370
+ )
371
+ query_states, key_states, value_states = mixed_qkv[0], mixed_qkv[1], mixed_qkv[2]
372
+
373
+ # Take the dot product between "query" and "key" to get the raw attention scores.
374
+ attention_scores = torch.matmul(query_states, key_states.transpose(-1, -2))
375
+
376
+ attention_scores = attention_scores * self.scale
377
+
378
+ # Normalize the attention scores to probabilities.
379
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
380
+
381
+ # This is actually dropping out entire tokens to attend to, which might
382
+ # seem a bit unusual, but is taken from the original Transformer paper.
383
+ attention_probs = self.dropout(attention_probs)
384
+
385
+ # Mask heads if we want to
386
+ if head_mask is not None:
387
+ attention_probs = attention_probs * head_mask
388
+
389
+ context_layer = torch.matmul(attention_probs, value_states).permute(0, 2, 1, 3)
390
+
391
+ new_context_layer_shape = context_layer.size()[:-2] + (self.embed_dim,)
392
+ context_layer = context_layer.reshape(new_context_layer_shape)
393
+
394
+ output = self.projection(context_layer)
395
+
396
+ outputs = (output, attention_probs) if output_attentions else (output, None)
397
+
398
+ return outputs
399
+
400
+
401
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Blip
402
+ class BlipMLP(nn.Module):
403
+ def __init__(self, config):
404
+ super().__init__()
405
+ self.config = config
406
+ self.activation_fn = ACT2FN[config.hidden_act]
407
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
408
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
409
+
410
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
411
+ hidden_states = self.fc1(hidden_states)
412
+ hidden_states = self.activation_fn(hidden_states)
413
+ hidden_states = self.fc2(hidden_states)
414
+ return hidden_states
415
+
416
+
417
+ class BlipEncoderLayer(nn.Module):
418
+ def __init__(self, config: BlipConfig):
419
+ super().__init__()
420
+ self.embed_dim = config.hidden_size
421
+ self.self_attn = BlipAttention(config)
422
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
423
+ self.mlp = BlipMLP(config)
424
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
425
+
426
+ def forward(
427
+ self,
428
+ hidden_states: torch.Tensor,
429
+ attention_mask: torch.Tensor,
430
+ output_attentions: Optional[bool] = False,
431
+ ) -> Tuple[torch.FloatTensor]:
432
+ """
433
+ Args:
434
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
435
+ attention_mask (`torch.FloatTensor`): attention mask of size
436
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
437
+ `(config.encoder_attention_heads,)`.
438
+ output_attentions (`bool`, *optional*):
439
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
440
+ returned tensors for more detail.
441
+ """
442
+ residual = hidden_states
443
+
444
+ hidden_states = self.layer_norm1(hidden_states)
445
+ hidden_states, attn_weights = self.self_attn(
446
+ hidden_states=hidden_states,
447
+ head_mask=attention_mask,
448
+ output_attentions=output_attentions,
449
+ )
450
+ hidden_states = hidden_states + residual
451
+ residual = hidden_states
452
+ hidden_states = self.layer_norm2(hidden_states)
453
+ hidden_states = self.mlp(hidden_states)
454
+
455
+ hidden_states = hidden_states + residual
456
+
457
+ outputs = (hidden_states,)
458
+
459
+ if output_attentions:
460
+ outputs += (attn_weights,)
461
+
462
+ return outputs
463
+
464
+
465
+ class BlipPreTrainedModel(PreTrainedModel):
466
+ """
467
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
468
+ models.
469
+ """
470
+
471
+ config_class = BlipConfig
472
+ base_model_prefix = "blip"
473
+ supports_gradient_checkpointing = True
474
+ _no_split_modules = ["BlipEncoderLayer", "BlipTextEmbeddings"]
475
+ _skip_keys_device_placement = ["past_key_value"]
476
+
477
+ def _init_weights(self, module):
478
+ """Initialize the weights"""
479
+ factor = self.config.initializer_range
480
+ if isinstance(module, nn.Conv2d) or isinstance(module, nn.Embedding) or isinstance(module, nn.Linear):
481
+ module.weight.data.normal_(mean=0.0, std=factor)
482
+ if hasattr(module, "bias") and module.bias is not None:
483
+ module.bias.data.zero_()
484
+
485
+ if isinstance(module, BlipVisionEmbeddings):
486
+ if hasattr(self.config, "vision_config"):
487
+ factor = self.config.vision_config.initializer_range
488
+ nn.init.trunc_normal_(
489
+ module.position_embedding,
490
+ mean=0.0,
491
+ std=factor,
492
+ )
493
+
494
+ nn.init.trunc_normal_(
495
+ module.class_embedding,
496
+ mean=0.0,
497
+ std=factor,
498
+ )
499
+
500
+ elif isinstance(module, nn.LayerNorm):
501
+ module.bias.data.zero_()
502
+ module.weight.data.fill_(1.0)
503
+ elif isinstance(module, nn.Linear) and module.bias is not None:
504
+ module.bias.data.zero_()
505
+
506
+
507
+ BLIP_START_DOCSTRING = r"""
508
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
509
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
510
+ etc.)
511
+
512
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
513
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
514
+ and behavior.
515
+
516
+ Parameters:
517
+ config ([`BlipConfig`]): Model configuration class with all the parameters of the model.
518
+ Initializing with a config file does not load the weights associated with the model, only the
519
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
520
+ """
521
+
522
+ BLIP_TEXT_INPUTS_DOCSTRING = r"""
523
+ Args:
524
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
525
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
526
+ it.
527
+
528
+ Indices can be obtained using [`AutoProcessor`]. See [`BlipProcessor.__call__`] for details.
529
+
530
+ [What are input IDs?](../glossary#input-ids)
531
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
532
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
533
+
534
+ - 1 for tokens that are **not masked**,
535
+ - 0 for tokens that are **masked**.
536
+
537
+ [What are attention masks?](../glossary#attention-mask)
538
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
539
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
540
+ config.max_position_embeddings - 1]`.
541
+
542
+ [What are position IDs?](../glossary#position-ids)
543
+ output_attentions (`bool`, *optional*):
544
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
545
+ tensors for more detail.
546
+ output_hidden_states (`bool`, *optional*):
547
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
548
+ more detail.
549
+ return_dict (`bool`, *optional*):
550
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
551
+ """
552
+
553
+ BLIP_VISION_INPUTS_DOCSTRING = r"""
554
+ Args:
555
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
556
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
557
+ [`BlipImageProcessor`]. See [`BlipImageProcessor.__call__`] for details.
558
+ output_attentions (`bool`, *optional*):
559
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
560
+ tensors for more detail.
561
+ output_hidden_states (`bool`, *optional*):
562
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
563
+ more detail.
564
+ return_dict (`bool`, *optional*):
565
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
566
+ interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
567
+ Whether to interpolate the pre-trained position encodings.
568
+ """
569
+
570
+ BLIP_INPUTS_DOCSTRING = r"""
571
+ Args:
572
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
573
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
574
+ it.
575
+
576
+ Indices can be obtained using [`AutoProcessor`]. See [`BlipProcessor.__call__`] for details.
577
+
578
+ [What are input IDs?](../glossary#input-ids)
579
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
580
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
581
+
582
+ - 1 for tokens that are **not masked**,
583
+ - 0 for tokens that are **masked**.
584
+
585
+ [What are attention masks?](../glossary#attention-mask)
586
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
587
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
588
+ config.max_position_embeddings - 1]`.
589
+
590
+ [What are position IDs?](../glossary#position-ids)
591
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
592
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
593
+ [`BlipImageProcessor`]. See [`BlipImageProcessor.__call__`] for details.
594
+ return_loss (`bool`, *optional*):
595
+ Whether or not to return the contrastive loss.
596
+ output_attentions (`bool`, *optional*):
597
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
598
+ tensors for more detail.
599
+ output_hidden_states (`bool`, *optional*):
600
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
601
+ more detail.
602
+ return_dict (`bool`, *optional*):
603
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
604
+ interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
605
+ Whether to interpolate the pre-trained position encodings.
606
+ """
607
+
608
+
609
+ class BlipEncoder(nn.Module):
610
+ """
611
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
612
+ [`BlipEncoderLayer`].
613
+
614
+ Args:
615
+ config (`BlipConfig`):
616
+ The corresponding vision configuration for the `BlipEncoder`.
617
+ """
618
+
619
+ def __init__(self, config: BlipConfig):
620
+ super().__init__()
621
+ self.config = config
622
+ self.layers = nn.ModuleList([BlipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
623
+ self.gradient_checkpointing = False
624
+
625
+ def forward(
626
+ self,
627
+ inputs_embeds,
628
+ attention_mask: Optional[torch.Tensor] = None,
629
+ output_attentions: Optional[bool] = None,
630
+ output_hidden_states: Optional[bool] = None,
631
+ return_dict: Optional[bool] = None,
632
+ ) -> Union[Tuple, BaseModelOutput]:
633
+ r"""
634
+ Args:
635
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
636
+ Embedded representation of the inputs. Should be float, not int tokens.
637
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
638
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
639
+
640
+ - 1 for tokens that are **not masked**,
641
+ - 0 for tokens that are **masked**.
642
+
643
+ [What are attention masks?](../glossary#attention-mask)
644
+ output_attentions (`bool`, *optional*):
645
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
646
+ returned tensors for more detail.
647
+ output_hidden_states (`bool`, *optional*):
648
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
649
+ for more detail.
650
+ return_dict (`bool`, *optional*):
651
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
652
+ """
653
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
654
+ output_hidden_states = (
655
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
656
+ )
657
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
658
+
659
+ encoder_states = () if output_hidden_states else None
660
+ all_attentions = () if output_attentions else None
661
+
662
+ hidden_states = inputs_embeds
663
+ for idx, encoder_layer in enumerate(self.layers):
664
+ if output_hidden_states:
665
+ encoder_states = encoder_states + (hidden_states,)
666
+ if self.gradient_checkpointing and self.training:
667
+ layer_outputs = self._gradient_checkpointing_func(
668
+ encoder_layer.__call__,
669
+ hidden_states,
670
+ attention_mask,
671
+ output_attentions,
672
+ )
673
+ else:
674
+ layer_outputs = encoder_layer(
675
+ hidden_states,
676
+ attention_mask,
677
+ output_attentions=output_attentions,
678
+ )
679
+
680
+ hidden_states = layer_outputs[0]
681
+
682
+ if output_attentions:
683
+ all_attentions = all_attentions + (layer_outputs[1],)
684
+
685
+ if output_hidden_states:
686
+ encoder_states = encoder_states + (hidden_states,)
687
+
688
+ if not return_dict:
689
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
690
+ return BaseModelOutput(
691
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
692
+ )
693
+
694
+
695
+ class BlipVisionModel(BlipPreTrainedModel):
696
+ main_input_name = "pixel_values"
697
+ config_class = BlipVisionConfig
698
+
699
+ def __init__(self, config: BlipVisionConfig):
700
+ super().__init__(config)
701
+ self.config = config
702
+ embed_dim = config.hidden_size
703
+
704
+ self.embeddings = BlipVisionEmbeddings(config)
705
+ self.encoder = BlipEncoder(config)
706
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
707
+
708
+ self.post_init()
709
+
710
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
711
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=BlipVisionConfig)
712
+ def forward(
713
+ self,
714
+ pixel_values: Optional[torch.FloatTensor] = None,
715
+ output_attentions: Optional[bool] = None,
716
+ output_hidden_states: Optional[bool] = None,
717
+ return_dict: Optional[bool] = None,
718
+ interpolate_pos_encoding: bool = False,
719
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
720
+ r"""
721
+ Returns:
722
+
723
+ """
724
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
725
+ output_hidden_states = (
726
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
727
+ )
728
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
729
+
730
+ if pixel_values is None:
731
+ raise ValueError("You have to specify pixel_values")
732
+
733
+ hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
734
+
735
+ encoder_outputs = self.encoder(
736
+ inputs_embeds=hidden_states,
737
+ output_attentions=output_attentions,
738
+ output_hidden_states=output_hidden_states,
739
+ return_dict=return_dict,
740
+ )
741
+
742
+ last_hidden_state = encoder_outputs[0]
743
+ last_hidden_state = self.post_layernorm(last_hidden_state)
744
+
745
+ pooled_output = last_hidden_state[:, 0, :]
746
+ pooled_output = self.post_layernorm(pooled_output)
747
+
748
+ if not return_dict:
749
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
750
+
751
+ return BaseModelOutputWithPooling(
752
+ last_hidden_state=last_hidden_state,
753
+ pooler_output=pooled_output,
754
+ hidden_states=encoder_outputs.hidden_states,
755
+ attentions=encoder_outputs.attentions,
756
+ )
757
+
758
+ def get_input_embeddings(self):
759
+ return self.embeddings
760
+
761
+
762
+ @add_start_docstrings(
763
+ """
764
+ This model is going to be deprecated in future versions. Please use `BlipForConditionalGeneration`, `BlipForQuestionAnswering` or `BlipForImageTextRetrieval` depending on your usecase.
765
+ """,
766
+ BLIP_START_DOCSTRING,
767
+ )
768
+ class BlipModel(BlipPreTrainedModel):
769
+ config_class = BlipConfig
770
+
771
+ def __init__(self, config: BlipConfig):
772
+ super().__init__(config)
773
+
774
+ if not isinstance(config.text_config, BlipTextConfig):
775
+ raise TypeError(
776
+ "config.text_config is expected to be of type BlipTextConfig but is of type"
777
+ f" {type(config.text_config)}."
778
+ )
779
+
780
+ if not isinstance(config.vision_config, BlipVisionConfig):
781
+ raise TypeError(
782
+ "config.vision_config is expected to be of type BlipVisionConfig but is of type"
783
+ f" {type(config.vision_config)}."
784
+ )
785
+
786
+ text_config = config.text_config
787
+ vision_config = config.vision_config
788
+
789
+ self.projection_dim = config.projection_dim
790
+ self.text_embed_dim = text_config.hidden_size
791
+ self.vision_embed_dim = vision_config.hidden_size
792
+
793
+ self.text_model = BlipTextModel(text_config)
794
+ self.vision_model = BlipVisionModel(vision_config)
795
+
796
+ self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
797
+ self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
798
+ self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
799
+
800
+ logger.warning(
801
+ "`BlipModel` is going to be deprecated in future release, please use `BlipForConditionalGeneration`, `BlipForQuestionAnswering` or `BlipForImageTextRetrieval` depending on your usecase."
802
+ )
803
+
804
+ # Initialize weights and apply final processing
805
+ self.post_init()
806
+
807
+ def get_input_embeddings(self):
808
+ return self.text_model.get_input_embeddings()
809
+
810
+ def set_input_embeddings(self, value):
811
+ self.text_model.set_input_embeddings(value)
812
+
813
+ @add_start_docstrings_to_model_forward(BLIP_TEXT_INPUTS_DOCSTRING)
814
+ def get_text_features(
815
+ self,
816
+ input_ids: Optional[torch.Tensor] = None,
817
+ attention_mask: Optional[torch.Tensor] = None,
818
+ position_ids: Optional[torch.Tensor] = None,
819
+ return_dict: Optional[bool] = None,
820
+ ) -> torch.FloatTensor:
821
+ r"""
822
+ Returns:
823
+ text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
824
+ applying the projection layer to the pooled output of [`BlipTextModel`].
825
+
826
+ Examples:
827
+
828
+ ```python
829
+ >>> from transformers import AutoProcessor, BlipModel
830
+
831
+ >>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
832
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
833
+
834
+ >>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
835
+ >>> text_features = model.get_text_features(**inputs)
836
+ ```"""
837
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
838
+
839
+ text_outputs = self.text_model(
840
+ input_ids=input_ids,
841
+ attention_mask=attention_mask,
842
+ position_ids=position_ids,
843
+ return_dict=return_dict,
844
+ )
845
+
846
+ pooled_output = text_outputs[1]
847
+ text_features = self.text_projection(pooled_output)
848
+
849
+ return text_features
850
+
851
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
852
+ def get_image_features(
853
+ self,
854
+ pixel_values: Optional[torch.FloatTensor] = None,
855
+ return_dict: Optional[bool] = None,
856
+ interpolate_pos_encoding: bool = False,
857
+ ) -> torch.FloatTensor:
858
+ r"""
859
+ Returns:
860
+ image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
861
+ applying the projection layer to the pooled output of [`BlipVisionModel`].
862
+
863
+ Examples:
864
+
865
+ ```python
866
+ >>> from PIL import Image
867
+ >>> import requests
868
+ >>> from transformers import AutoProcessor, BlipModel
869
+
870
+ >>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
871
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
872
+
873
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
874
+ >>> image = Image.open(requests.get(url, stream=True).raw)
875
+
876
+ >>> inputs = processor(images=image, return_tensors="pt")
877
+
878
+ >>> image_features = model.get_image_features(**inputs)
879
+ ```"""
880
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
881
+
882
+ vision_outputs = self.vision_model(
883
+ pixel_values=pixel_values,
884
+ return_dict=return_dict,
885
+ interpolate_pos_encoding=interpolate_pos_encoding,
886
+ )
887
+
888
+ pooled_output = vision_outputs[1] # pooled_output
889
+ image_features = self.visual_projection(pooled_output)
890
+
891
+ return image_features
892
+
893
+ @add_start_docstrings_to_model_forward(BLIP_INPUTS_DOCSTRING)
894
+ def get_multimodal_features(
895
+ self,
896
+ input_ids: Optional[torch.LongTensor] = None,
897
+ pixel_values: Optional[torch.FloatTensor] = None,
898
+ attention_mask: Optional[torch.Tensor] = None,
899
+ return_dict: Optional[bool] = None,
900
+ interpolate_pos_encoding: bool = False,
901
+ ) -> torch.FloatTensor:
902
+ r"""
903
+ Returns:
904
+ multimodal_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The multimodal embeddings
905
+ obtained by applying the image embeddings to the text encoder using the cross-attention mechanism.
906
+
907
+ Examples:
908
+ ```python
909
+ >>> from PIL import Image
910
+ >>> import requests
911
+ >>> from transformers import AutoProcessor, BlipModel
912
+
913
+ >>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
914
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
915
+
916
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
917
+ >>> image = Image.open(requests.get(url, stream=True).raw)
918
+ >>> texts = ["a photo of a cat", "a photo of a dog"]
919
+ >>> inputs = processor(images=image, text=texts, padding=True, return_tensors="pt")
920
+
921
+ >>> multimodal_features = model.get_multimodal_features(**inputs)
922
+ ```"""
923
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
924
+ vision_outputs = self.vision_model(
925
+ pixel_values=pixel_values,
926
+ output_attentions=True,
927
+ output_hidden_states=True,
928
+ return_dict=return_dict,
929
+ interpolate_pos_encoding=interpolate_pos_encoding,
930
+ )
931
+
932
+ image_embeds = vision_outputs[0]
933
+ image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long)
934
+
935
+ text_outputs = self.text_model(
936
+ input_ids=input_ids,
937
+ attention_mask=attention_mask,
938
+ encoder_hidden_states=image_embeds,
939
+ encoder_attention_mask=image_atts,
940
+ return_dict=return_dict,
941
+ )
942
+
943
+ pooled_output = text_outputs[1] # pooled_output
944
+ multimodal_features = self.text_projection(pooled_output)
945
+
946
+ return multimodal_features
947
+
948
+ @add_start_docstrings_to_model_forward(BLIP_INPUTS_DOCSTRING)
949
+ @replace_return_docstrings(output_type=BlipOutput, config_class=BlipConfig)
950
+ def forward(
951
+ self,
952
+ input_ids: Optional[torch.LongTensor] = None,
953
+ pixel_values: Optional[torch.FloatTensor] = None,
954
+ attention_mask: Optional[torch.Tensor] = None,
955
+ position_ids: Optional[torch.LongTensor] = None,
956
+ return_loss: Optional[bool] = None,
957
+ output_attentions: Optional[bool] = None,
958
+ output_hidden_states: Optional[bool] = None,
959
+ return_dict: Optional[bool] = None,
960
+ interpolate_pos_encoding: bool = False,
961
+ ) -> Union[Tuple, BlipOutput]:
962
+ r"""
963
+ Returns:
964
+
965
+ Examples:
966
+
967
+ ```python
968
+ >>> from PIL import Image
969
+ >>> import requests
970
+ >>> from transformers import AutoProcessor, BlipModel
971
+
972
+ >>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
973
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
974
+
975
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
976
+ >>> image = Image.open(requests.get(url, stream=True).raw)
977
+
978
+ >>> inputs = processor(
979
+ ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
980
+ ... )
981
+
982
+ >>> outputs = model(**inputs)
983
+ >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
984
+ >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
985
+ ```"""
986
+ # Use BLIP model's config for some fields (if specified) instead of those of vision & text components.
987
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
988
+ output_hidden_states = (
989
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
990
+ )
991
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
992
+
993
+ vision_outputs = self.vision_model(
994
+ pixel_values=pixel_values,
995
+ output_attentions=output_attentions,
996
+ output_hidden_states=output_hidden_states,
997
+ return_dict=return_dict,
998
+ interpolate_pos_encoding=interpolate_pos_encoding,
999
+ )
1000
+
1001
+ text_outputs = self.text_model(
1002
+ input_ids=input_ids,
1003
+ attention_mask=attention_mask,
1004
+ position_ids=position_ids,
1005
+ output_attentions=output_attentions,
1006
+ output_hidden_states=output_hidden_states,
1007
+ return_dict=return_dict,
1008
+ )
1009
+
1010
+ image_embeds = vision_outputs[1]
1011
+ image_embeds = self.visual_projection(image_embeds)
1012
+
1013
+ text_embeds = text_outputs[1]
1014
+ text_embeds = self.text_projection(text_embeds)
1015
+
1016
+ # normalized features
1017
+ image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
1018
+ text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
1019
+
1020
+ # cosine similarity as logits
1021
+ logit_scale = self.logit_scale.exp().to(device=text_embeds.device)
1022
+ image_embeds = image_embeds.to(device=text_embeds.device, dtype=text_embeds.dtype)
1023
+ logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
1024
+ logits_per_image = logits_per_text.t()
1025
+
1026
+ loss = None
1027
+ if return_loss:
1028
+ loss = blip_loss(logits_per_text)
1029
+
1030
+ if not return_dict:
1031
+ output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
1032
+ return ((loss,) + output) if loss is not None else output
1033
+
1034
+ return BlipOutput(
1035
+ loss=loss,
1036
+ logits_per_image=logits_per_image,
1037
+ logits_per_text=logits_per_text,
1038
+ text_embeds=text_embeds,
1039
+ image_embeds=image_embeds,
1040
+ text_model_output=text_outputs,
1041
+ vision_model_output=vision_outputs,
1042
+ )
1043
+
1044
+
1045
+ @add_start_docstrings(
1046
+ """
1047
+ BLIP Model for image captioning. The model consists of a vision encoder and a text decoder. One can optionally pass
1048
+ `input_ids` to the model, which serve as a text prompt, to make the text decoder continue the prompt. Otherwise,
1049
+ the decoder starts generating text from the [BOS] (beginning-of-sequence) token. will start generating the caption
1050
+ from the text input. If no text input is provided, the decoder will start with the [BOS] token only.
1051
+ """,
1052
+ BLIP_START_DOCSTRING,
1053
+ )
1054
+ class BlipForConditionalGeneration(BlipPreTrainedModel, GenerationMixin):
1055
+ config_class = BlipConfig
1056
+ _tied_weights_keys = ["text_decoder.cls.predictions.decoder.bias"]
1057
+ main_input_name = "pixel_values"
1058
+
1059
+ def __init__(self, config: BlipConfig):
1060
+ super().__init__(config)
1061
+
1062
+ self.vision_model = BlipVisionModel(config.vision_config)
1063
+
1064
+ self.text_decoder = BlipTextLMHeadModel(config.text_config)
1065
+
1066
+ self.decoder_input_ids = config.text_config.bos_token_id
1067
+ self.decoder_pad_token_id = config.text_config.pad_token_id
1068
+
1069
+ # Initialize weights and apply final processing
1070
+ self.post_init()
1071
+
1072
+ def get_input_embeddings(self):
1073
+ return self.text_decoder.get_input_embeddings()
1074
+
1075
+ def set_input_embeddings(self, value):
1076
+ self.text_decoder.set_input_embeddings(value)
1077
+
1078
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
1079
+ @replace_return_docstrings(output_type=BlipForConditionalGenerationModelOutput, config_class=BlipVisionConfig)
1080
+ def forward(
1081
+ self,
1082
+ pixel_values: torch.FloatTensor,
1083
+ input_ids: Optional[torch.LongTensor] = None,
1084
+ attention_mask: Optional[torch.LongTensor] = None,
1085
+ output_attentions: Optional[bool] = None,
1086
+ output_hidden_states: Optional[bool] = None,
1087
+ labels: Optional[torch.LongTensor] = None,
1088
+ return_dict: Optional[bool] = None,
1089
+ interpolate_pos_encoding: bool = False,
1090
+ ) -> Union[Tuple, BlipForConditionalGenerationModelOutput]:
1091
+ r"""
1092
+ Returns:
1093
+
1094
+ Examples:
1095
+
1096
+ ```python
1097
+ >>> from PIL import Image
1098
+ >>> import requests
1099
+ >>> from transformers import AutoProcessor, BlipForConditionalGeneration
1100
+
1101
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
1102
+ >>> model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
1103
+
1104
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1105
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1106
+ >>> text = "A picture of"
1107
+
1108
+ >>> inputs = processor(images=image, text=text, return_tensors="pt")
1109
+
1110
+ >>> outputs = model(**inputs)
1111
+ ```"""
1112
+
1113
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1114
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1115
+ output_hidden_states = (
1116
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1117
+ )
1118
+
1119
+ vision_outputs = self.vision_model(
1120
+ pixel_values=pixel_values,
1121
+ output_attentions=output_attentions,
1122
+ output_hidden_states=output_hidden_states,
1123
+ return_dict=return_dict,
1124
+ interpolate_pos_encoding=interpolate_pos_encoding,
1125
+ )
1126
+
1127
+ image_embeds = vision_outputs[0]
1128
+
1129
+ outputs = self.text_decoder(
1130
+ input_ids=input_ids,
1131
+ attention_mask=attention_mask,
1132
+ encoder_hidden_states=image_embeds,
1133
+ labels=labels,
1134
+ return_dict=return_dict,
1135
+ reduction="mean",
1136
+ )
1137
+
1138
+ if not return_dict:
1139
+ outputs = (outputs[0], outputs[1]) if labels is not None else (outputs[0],)
1140
+ outputs += (image_embeds, vision_outputs[0]) + vision_outputs[2:]
1141
+ return tuple(output for output in outputs if output is not None)
1142
+
1143
+ return BlipForConditionalGenerationModelOutput(
1144
+ loss=outputs.loss,
1145
+ logits=outputs.logits,
1146
+ image_embeds=image_embeds,
1147
+ last_hidden_state=vision_outputs.last_hidden_state,
1148
+ hidden_states=vision_outputs.hidden_states,
1149
+ attentions=vision_outputs.attentions,
1150
+ )
1151
+
1152
+ @torch.no_grad()
1153
+ def generate(
1154
+ self,
1155
+ pixel_values: torch.FloatTensor,
1156
+ input_ids: Optional[torch.LongTensor] = None,
1157
+ attention_mask: Optional[torch.LongTensor] = None,
1158
+ interpolate_pos_encoding: bool = False,
1159
+ **generate_kwargs,
1160
+ ) -> torch.LongTensor:
1161
+ r"""
1162
+ Overrides *generate* function to be able to use the model as a conditional generator
1163
+
1164
+ Parameters:
1165
+ pixel_values (*torch.FloatTensor* of shape *(batch_size, num_channels, image_height, image_width)*:
1166
+ Input image to be processed
1167
+ input_ids (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
1168
+ The sequence used as a prompt for the generation.
1169
+ attention_mask (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
1170
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1171
+
1172
+
1173
+ Examples:
1174
+ ```python
1175
+ >>> from PIL import Image
1176
+ >>> import requests
1177
+ >>> from transformers import AutoProcessor, BlipForConditionalGeneration
1178
+
1179
+ >>> model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
1180
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
1181
+
1182
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1183
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1184
+
1185
+ >>> inputs = processor(images=image, return_tensors="pt")
1186
+
1187
+ >>> outputs = model.generate(**inputs)
1188
+ >>> print(processor.decode(outputs[0], skip_special_tokens=True))
1189
+ two cats sleeping on a couch
1190
+ ```
1191
+ """
1192
+
1193
+ batch_size = pixel_values.shape[0]
1194
+ vision_outputs = self.vision_model(
1195
+ pixel_values=pixel_values,
1196
+ interpolate_pos_encoding=interpolate_pos_encoding,
1197
+ )
1198
+
1199
+ image_embeds = vision_outputs[0]
1200
+
1201
+ image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
1202
+
1203
+ if isinstance(input_ids, list):
1204
+ input_ids = torch.LongTensor(input_ids)
1205
+ elif input_ids is None:
1206
+ input_ids = (
1207
+ torch.LongTensor([[self.decoder_input_ids, self.config.text_config.eos_token_id]])
1208
+ .repeat(batch_size, 1)
1209
+ .to(image_embeds.device)
1210
+ )
1211
+
1212
+ input_ids[:, 0] = self.config.text_config.bos_token_id
1213
+ attention_mask = attention_mask[:, :-1] if attention_mask is not None else None
1214
+
1215
+ outputs = self.text_decoder.generate(
1216
+ input_ids=input_ids[:, :-1],
1217
+ eos_token_id=self.config.text_config.sep_token_id,
1218
+ pad_token_id=self.config.text_config.pad_token_id,
1219
+ attention_mask=attention_mask,
1220
+ encoder_hidden_states=image_embeds,
1221
+ encoder_attention_mask=image_attention_mask,
1222
+ **generate_kwargs,
1223
+ )
1224
+
1225
+ return outputs
1226
+
1227
+
1228
+ @add_start_docstrings(
1229
+ """
1230
+ BLIP Model for visual question answering. The model consists of a vision encoder, a text encoder as well as a text
1231
+ decoder. The vision encoder will encode the input image, the text encoder will encode the input question together
1232
+ with the encoding of the image, and the text decoder will output the answer to the question.
1233
+ """,
1234
+ BLIP_START_DOCSTRING,
1235
+ )
1236
+ class BlipForQuestionAnswering(BlipPreTrainedModel, GenerationMixin):
1237
+ config_class = BlipConfig
1238
+ _tied_weights_keys = ["text_decoder.cls.predictions.decoder.bias"]
1239
+
1240
+ def __init__(self, config: BlipConfig):
1241
+ super().__init__(config)
1242
+
1243
+ self.vision_model = BlipVisionModel(config.vision_config)
1244
+
1245
+ self.text_encoder = BlipTextModel(config.text_config, add_pooling_layer=False)
1246
+
1247
+ self.text_decoder = BlipTextLMHeadModel(config.text_config)
1248
+
1249
+ self.decoder_pad_token_id = config.text_config.pad_token_id
1250
+ self.decoder_start_token_id = config.text_config.bos_token_id
1251
+
1252
+ # Initialize weights and apply final processing
1253
+ self.post_init()
1254
+
1255
+ def set_input_embeddings(self, value):
1256
+ self.text_encoder.set_input_embeddings(value)
1257
+
1258
+ def get_input_embeddings(self):
1259
+ # This will return shared embeddings if they are shared else specific to encoder.
1260
+ return self.text_encoder.get_input_embeddings()
1261
+
1262
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
1263
+ @replace_return_docstrings(output_type=BlipTextVisionModelOutput, config_class=BlipVisionConfig)
1264
+ def forward(
1265
+ self,
1266
+ input_ids: torch.LongTensor,
1267
+ pixel_values: torch.FloatTensor,
1268
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1269
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1270
+ attention_mask: Optional[torch.LongTensor] = None,
1271
+ output_attentions: Optional[bool] = None,
1272
+ output_hidden_states: Optional[bool] = None,
1273
+ labels: Optional[torch.LongTensor] = None,
1274
+ return_dict: Optional[bool] = None,
1275
+ interpolate_pos_encoding: bool = False,
1276
+ ) -> Union[Tuple, BlipTextVisionModelOutput]:
1277
+ r"""
1278
+ Returns:
1279
+
1280
+ Examples:
1281
+
1282
+ ```python
1283
+ >>> from PIL import Image
1284
+ >>> import requests
1285
+ >>> from transformers import AutoProcessor, BlipForQuestionAnswering
1286
+
1287
+ >>> model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
1288
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")
1289
+
1290
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1291
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1292
+
1293
+ >>> # training
1294
+ >>> text = "How many cats are in the picture?"
1295
+ >>> label = "2"
1296
+ >>> inputs = processor(images=image, text=text, return_tensors="pt")
1297
+ >>> labels = processor(text=label, return_tensors="pt").input_ids
1298
+
1299
+ >>> inputs["labels"] = labels
1300
+ >>> outputs = model(**inputs)
1301
+ >>> loss = outputs.loss
1302
+ >>> loss.backward()
1303
+
1304
+ >>> # inference
1305
+ >>> text = "How many cats are in the picture?"
1306
+ >>> inputs = processor(images=image, text=text, return_tensors="pt")
1307
+ >>> outputs = model.generate(**inputs)
1308
+ >>> print(processor.decode(outputs[0], skip_special_tokens=True))
1309
+ 2
1310
+ ```"""
1311
+ if labels is None and decoder_input_ids is None:
1312
+ raise ValueError(
1313
+ "Either `decoder_input_ids` or `labels` should be passed when calling `forward` with"
1314
+ " `BlipForQuestionAnswering`. if you are training the model make sure that `labels` is passed, if you"
1315
+ " are using the model for inference make sure that `decoder_input_ids` is passed or call `generate`"
1316
+ )
1317
+
1318
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1319
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1320
+ output_hidden_states = (
1321
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1322
+ )
1323
+
1324
+ vision_outputs = self.vision_model(
1325
+ pixel_values=pixel_values,
1326
+ output_attentions=output_attentions,
1327
+ output_hidden_states=output_hidden_states,
1328
+ return_dict=return_dict,
1329
+ interpolate_pos_encoding=interpolate_pos_encoding,
1330
+ )
1331
+
1332
+ image_embeds = vision_outputs[0]
1333
+ image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long)
1334
+
1335
+ question_embeds = self.text_encoder(
1336
+ input_ids=input_ids,
1337
+ attention_mask=attention_mask,
1338
+ encoder_hidden_states=image_embeds,
1339
+ encoder_attention_mask=image_attention_mask,
1340
+ return_dict=return_dict,
1341
+ )
1342
+
1343
+ if labels is not None and decoder_input_ids is None:
1344
+ # labels are already shifted right, see: https://github.com/huggingface/transformers/pull/23153
1345
+ decoder_input_ids = labels
1346
+
1347
+ question_embeds = question_embeds[0] if not return_dict else question_embeds.last_hidden_state
1348
+
1349
+ answer_output = self.text_decoder(
1350
+ input_ids=decoder_input_ids,
1351
+ attention_mask=decoder_attention_mask,
1352
+ encoder_hidden_states=question_embeds,
1353
+ encoder_attention_mask=attention_mask,
1354
+ labels=labels,
1355
+ return_dict=return_dict,
1356
+ reduction="mean",
1357
+ )
1358
+
1359
+ if labels is not None:
1360
+ decoder_loss = answer_output.loss.mean() if return_dict else answer_output[0].mean()
1361
+ else:
1362
+ decoder_loss = None
1363
+
1364
+ if not return_dict:
1365
+ outputs = (decoder_loss, image_embeds, vision_outputs[0]) + vision_outputs[2:]
1366
+ return tuple(output for output in outputs if output is not None)
1367
+
1368
+ return BlipTextVisionModelOutput(
1369
+ loss=decoder_loss,
1370
+ image_embeds=image_embeds,
1371
+ last_hidden_state=vision_outputs.last_hidden_state,
1372
+ hidden_states=vision_outputs.hidden_states,
1373
+ attentions=vision_outputs.attentions,
1374
+ )
1375
+
1376
+ @torch.no_grad()
1377
+ def generate(
1378
+ self,
1379
+ input_ids: torch.LongTensor,
1380
+ pixel_values: torch.FloatTensor,
1381
+ attention_mask: Optional[torch.LongTensor] = None,
1382
+ interpolate_pos_encoding: bool = False,
1383
+ **generate_kwargs,
1384
+ ) -> torch.LongTensor:
1385
+ r"""
1386
+ Overrides *generate* function to be able to use the model as a conditional generator
1387
+
1388
+ Parameters:
1389
+ input_ids (*torch.LongTensor* of shape *(batch_size, sequence_length)*):
1390
+ The sequence used as a prompt for the generation.
1391
+ pixel_values (*torch.FloatTensor* of shape *(batch_size, num_channels, image_height, image_width)*:
1392
+ Input image to be processed
1393
+ attention_mask (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
1394
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`. `1` for
1395
+ tokens that are NOT MASKED, `0` for MASKED tokens.
1396
+ **generate_kwargs:
1397
+ Additional arguments passed to the *generate* function of the decoder
1398
+
1399
+
1400
+ Examples:
1401
+ ```python
1402
+ >>> from PIL import Image
1403
+ >>> import requests
1404
+ >>> from transformers import AutoProcessor, BlipForQuestionAnswering
1405
+
1406
+ >>> model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
1407
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")
1408
+
1409
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1410
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1411
+ >>> text = "How many cats are in the picture?"
1412
+
1413
+ >>> inputs = processor(images=image, text=text, return_tensors="pt")
1414
+
1415
+ >>> outputs = model.generate(**inputs)
1416
+ >>> print(processor.decode(outputs[0], skip_special_tokens=True))
1417
+ 2
1418
+ ```
1419
+ """
1420
+ vision_outputs = self.vision_model(
1421
+ pixel_values=pixel_values,
1422
+ interpolate_pos_encoding=interpolate_pos_encoding,
1423
+ )
1424
+
1425
+ image_embeds = vision_outputs[0]
1426
+
1427
+ image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
1428
+
1429
+ if isinstance(input_ids, list):
1430
+ input_ids = torch.LongTensor(input_ids)
1431
+
1432
+ question_outputs = self.text_encoder(
1433
+ input_ids=input_ids,
1434
+ attention_mask=attention_mask,
1435
+ encoder_hidden_states=image_embeds,
1436
+ encoder_attention_mask=image_attention_mask,
1437
+ return_dict=False,
1438
+ )
1439
+
1440
+ question_embeds = question_outputs[0]
1441
+
1442
+ question_attention_mask = torch.ones(
1443
+ question_embeds.size()[:-1], dtype=torch.long, device=question_embeds.device
1444
+ )
1445
+
1446
+ bos_ids = torch.full(
1447
+ (question_embeds.size(0), 1), fill_value=self.decoder_start_token_id, device=question_embeds.device
1448
+ )
1449
+
1450
+ outputs = self.text_decoder.generate(
1451
+ input_ids=bos_ids,
1452
+ eos_token_id=self.config.text_config.sep_token_id,
1453
+ pad_token_id=self.config.text_config.pad_token_id,
1454
+ encoder_hidden_states=question_embeds,
1455
+ encoder_attention_mask=question_attention_mask,
1456
+ **generate_kwargs,
1457
+ )
1458
+
1459
+ return outputs
1460
+
1461
+
1462
+ @add_start_docstrings(
1463
+ """
1464
+ BLIP Model with a vision and text projector, and a classification head on top. The model is used in the context of
1465
+ image-text retrieval. Given an image and a text, the model returns the probability of the text being relevant to
1466
+ the image.
1467
+ """,
1468
+ BLIP_START_DOCSTRING,
1469
+ )
1470
+ class BlipForImageTextRetrieval(BlipPreTrainedModel):
1471
+ config_class = BlipConfig
1472
+
1473
+ def __init__(self, config: BlipConfig):
1474
+ super().__init__(config)
1475
+
1476
+ self.vision_model = BlipVisionModel(config.vision_config)
1477
+
1478
+ self.text_encoder = BlipTextModel(config.text_config, add_pooling_layer=False)
1479
+
1480
+ # vision projection layer
1481
+ self.vision_proj = nn.Linear(config.vision_config.hidden_size, config.image_text_hidden_size)
1482
+
1483
+ # text projection layer
1484
+ self.text_proj = nn.Linear(config.text_config.hidden_size, config.image_text_hidden_size)
1485
+
1486
+ # image text matching head
1487
+ self.itm_head = nn.Linear(config.text_config.hidden_size, 2)
1488
+
1489
+ self.decoder_pad_token_id = (
1490
+ config.text_config.pad_token_id
1491
+ if not hasattr(config, "decoder_pad_token_id")
1492
+ else config.decoder_pad_token_id
1493
+ )
1494
+ self.decoder_start_token_id = (
1495
+ config.text_config.bos_token_id
1496
+ if not hasattr(config, "decoder_start_token_id")
1497
+ else config.decoder_start_token_id
1498
+ )
1499
+
1500
+ # Initialize weights and apply final processing
1501
+ self.post_init()
1502
+
1503
+ def get_input_embeddings(self):
1504
+ return self.text_encoder.get_input_embeddings()
1505
+
1506
+ def set_input_embeddings(self, value):
1507
+ self.text_encoder.set_input_embeddings(value)
1508
+
1509
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
1510
+ @replace_return_docstrings(output_type=BlipTextVisionModelOutput, config_class=BlipVisionConfig)
1511
+ def forward(
1512
+ self,
1513
+ input_ids: torch.LongTensor,
1514
+ pixel_values: torch.FloatTensor,
1515
+ use_itm_head: Optional[bool] = True,
1516
+ attention_mask: Optional[torch.LongTensor] = None,
1517
+ output_attentions: Optional[bool] = None,
1518
+ output_hidden_states: Optional[bool] = None,
1519
+ return_dict: Optional[bool] = None,
1520
+ interpolate_pos_encoding: bool = False,
1521
+ ) -> Union[Tuple, BlipTextVisionModelOutput]:
1522
+ r"""
1523
+ Returns:
1524
+
1525
+ Examples:
1526
+
1527
+ ```python
1528
+ >>> from PIL import Image
1529
+ >>> import requests
1530
+ >>> from transformers import AutoProcessor, BlipForImageTextRetrieval
1531
+
1532
+ >>> model = BlipForImageTextRetrieval.from_pretrained("Salesforce/blip-itm-base-coco")
1533
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-itm-base-coco")
1534
+
1535
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1536
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1537
+ >>> text = "an image of a cat"
1538
+
1539
+ >>> inputs = processor(images=image, text=text, return_tensors="pt")
1540
+ >>> outputs = model(**inputs)
1541
+ ```
1542
+ """
1543
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1544
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1545
+ output_hidden_states = (
1546
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1547
+ )
1548
+
1549
+ vision_outputs = self.vision_model(
1550
+ pixel_values=pixel_values,
1551
+ output_attentions=output_attentions,
1552
+ output_hidden_states=output_hidden_states,
1553
+ return_dict=return_dict,
1554
+ interpolate_pos_encoding=interpolate_pos_encoding,
1555
+ )
1556
+
1557
+ image_embeds = vision_outputs[0]
1558
+ image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long)
1559
+
1560
+ if use_itm_head:
1561
+ question_embeds = self.text_encoder(
1562
+ input_ids=input_ids,
1563
+ attention_mask=attention_mask,
1564
+ encoder_hidden_states=image_embeds,
1565
+ encoder_attention_mask=image_atts,
1566
+ return_dict=return_dict,
1567
+ )
1568
+ question_embeds = question_embeds[0] if not return_dict else question_embeds.last_hidden_state
1569
+
1570
+ output = self.itm_head(question_embeds[:, 0, :])
1571
+ else:
1572
+ question_embeds = self.text_encoder(
1573
+ input_ids=input_ids,
1574
+ attention_mask=attention_mask,
1575
+ return_dict=return_dict,
1576
+ )
1577
+ question_embeds = question_embeds[0] if not return_dict else question_embeds.last_hidden_state
1578
+
1579
+ image_feat = normalize(self.vision_proj(image_embeds[:, 0, :]), dim=-1)
1580
+ text_feat = normalize(self.text_proj(question_embeds[:, 0, :]), dim=-1)
1581
+
1582
+ output = image_feat @ text_feat.t()
1583
+
1584
+ if not return_dict:
1585
+ outputs = (output, vision_outputs[0]) + vision_outputs[2:] + (question_embeds,)
1586
+ return tuple(output for output in outputs if output is not None)
1587
+
1588
+ return BlipImageTextMatchingModelOutput(
1589
+ itm_score=output,
1590
+ last_hidden_state=vision_outputs.last_hidden_state,
1591
+ hidden_states=vision_outputs.hidden_states,
1592
+ attentions=vision_outputs.attentions,
1593
+ question_embeds=question_embeds,
1594
+ )
1595
+
1596
+
1597
+ __all__ = [
1598
+ "BlipModel",
1599
+ "BlipPreTrainedModel",
1600
+ "BlipForConditionalGeneration",
1601
+ "BlipForQuestionAnswering",
1602
+ "BlipVisionModel",
1603
+ "BlipTextModel",
1604
+ "BlipForImageTextRetrieval",
1605
+ ]
lib/python3.12/site-packages/transformers/models/blip/modeling_blip_text.py ADDED
@@ -0,0 +1,958 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Salesforce Team Authors and The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the BSD-3-clause license (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
+ # https://opensource.org/licenses/BSD-3-Clause
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
+
17
+ import math
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ import torch
21
+ import torch.utils.checkpoint
22
+ from torch import Tensor, device, nn
23
+ from torch.nn import CrossEntropyLoss
24
+
25
+ from ...activations import ACT2FN
26
+ from ...generation import GenerationMixin
27
+ from ...modeling_outputs import (
28
+ BaseModelOutputWithPastAndCrossAttentions,
29
+ BaseModelOutputWithPoolingAndCrossAttentions,
30
+ CausalLMOutputWithCrossAttentions,
31
+ )
32
+ from ...modeling_utils import (
33
+ PreTrainedModel,
34
+ apply_chunking_to_forward,
35
+ find_pruneable_heads_and_indices,
36
+ prune_linear_layer,
37
+ )
38
+ from ...utils import logging
39
+ from .configuration_blip import BlipTextConfig
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+
45
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L52
46
+ class BlipTextEmbeddings(nn.Module):
47
+ """Construct the embeddings from word and position embeddings."""
48
+
49
+ def __init__(self, config):
50
+ super().__init__()
51
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
52
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
53
+
54
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
55
+ # any TensorFlow checkpoint file
56
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
57
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
58
+
59
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
60
+ self.register_buffer(
61
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
62
+ )
63
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
64
+
65
+ self.config = config
66
+
67
+ def forward(
68
+ self,
69
+ input_ids: Optional[torch.LongTensor] = None,
70
+ position_ids: Optional[torch.LongTensor] = None,
71
+ inputs_embeds: Optional[torch.FloatTensor] = None,
72
+ past_key_values_length: int = 0,
73
+ ) -> torch.Tensor:
74
+ if input_ids is not None:
75
+ input_shape = input_ids.size()
76
+ else:
77
+ input_shape = inputs_embeds.size()[:-1]
78
+
79
+ seq_length = input_shape[1]
80
+
81
+ if position_ids is None:
82
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
83
+
84
+ if inputs_embeds is None:
85
+ inputs_embeds = self.word_embeddings(input_ids)
86
+
87
+ embeddings = inputs_embeds
88
+
89
+ if self.position_embedding_type == "absolute":
90
+ position_embeddings = self.position_embeddings(position_ids)
91
+ embeddings += position_embeddings
92
+ embeddings = self.LayerNorm(embeddings)
93
+ embeddings = self.dropout(embeddings)
94
+ return embeddings
95
+
96
+
97
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L97
98
+ class BlipTextSelfAttention(nn.Module):
99
+ def __init__(self, config, is_cross_attention):
100
+ super().__init__()
101
+ self.config = config
102
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
103
+ raise ValueError(
104
+ "The hidden size (%d) is not a multiple of the number of attention heads (%d)"
105
+ % (config.hidden_size, config.num_attention_heads)
106
+ )
107
+
108
+ self.num_attention_heads = config.num_attention_heads
109
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
110
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
111
+
112
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
113
+ if is_cross_attention:
114
+ self.key = nn.Linear(config.encoder_hidden_size, self.all_head_size)
115
+ self.value = nn.Linear(config.encoder_hidden_size, self.all_head_size)
116
+ else:
117
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
118
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
119
+
120
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
121
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
122
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
123
+ self.max_position_embeddings = config.max_position_embeddings
124
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
125
+
126
+ def save_attn_gradients(self, attn_gradients):
127
+ self.attn_gradients = attn_gradients
128
+
129
+ def get_attn_gradients(self):
130
+ return self.attn_gradients
131
+
132
+ def save_attention_map(self, attention_map):
133
+ self.attention_map = attention_map
134
+
135
+ def get_attention_map(self):
136
+ return self.attention_map
137
+
138
+ def transpose_for_scores(self, x):
139
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
140
+ x = x.view(*new_x_shape)
141
+ return x.permute(0, 2, 1, 3)
142
+
143
+ def forward(
144
+ self,
145
+ hidden_states: torch.Tensor,
146
+ attention_mask: Optional[torch.FloatTensor] = None,
147
+ head_mask: Optional[torch.FloatTensor] = None,
148
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
149
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
150
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
151
+ output_attentions: Optional[bool] = False,
152
+ ) -> Tuple[torch.Tensor]:
153
+ mixed_query_layer = self.query(hidden_states)
154
+
155
+ # If this is instantiated as a cross-attention module, the keys
156
+ # and values come from an encoder; the attention mask needs to be
157
+ # such that the encoder's padding tokens are not attended to.
158
+ is_cross_attention = encoder_hidden_states is not None
159
+
160
+ if is_cross_attention:
161
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
162
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
163
+ attention_mask = encoder_attention_mask
164
+ elif past_key_value is not None:
165
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
166
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
167
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
168
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
169
+ else:
170
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
171
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
172
+
173
+ query_layer = self.transpose_for_scores(mixed_query_layer)
174
+
175
+ past_key_value = (key_layer, value_layer)
176
+
177
+ # Take the dot product between "query" and "key" to get the raw attention scores.
178
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
179
+
180
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
181
+ seq_length = hidden_states.size()[1]
182
+ position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
183
+ position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
184
+ distance = position_ids_l - position_ids_r
185
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
186
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
187
+
188
+ if self.position_embedding_type == "relative_key":
189
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
190
+ attention_scores = attention_scores + relative_position_scores
191
+ elif self.position_embedding_type == "relative_key_query":
192
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
193
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
194
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
195
+
196
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
197
+ if attention_mask is not None:
198
+ # Apply the attention mask is (precomputed for all layers in BlipTextModel forward() function)
199
+ attention_scores = attention_scores + attention_mask.to(attention_scores.device)
200
+
201
+ # Normalize the attention scores to probabilities.
202
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
203
+
204
+ # This is actually dropping out entire tokens to attend to, which might
205
+ # seem a bit unusual, but is taken from the original Transformer paper.
206
+ attention_probs_dropped = self.dropout(attention_probs)
207
+
208
+ # Mask heads if we want to
209
+ if head_mask is not None:
210
+ attention_probs_dropped = attention_probs_dropped * head_mask
211
+
212
+ context_layer = torch.matmul(attention_probs_dropped, value_layer)
213
+
214
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
215
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
216
+ context_layer = context_layer.view(*new_context_layer_shape)
217
+
218
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
219
+
220
+ outputs = outputs + (past_key_value,)
221
+ return outputs
222
+
223
+
224
+ # Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert -> BlipText
225
+ class BlipTextSelfOutput(nn.Module):
226
+ def __init__(self, config):
227
+ super().__init__()
228
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
229
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
230
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
231
+
232
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
233
+ hidden_states = self.dense(hidden_states)
234
+ hidden_states = self.dropout(hidden_states)
235
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
236
+ return hidden_states
237
+
238
+
239
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#242
240
+ class BlipTextAttention(nn.Module):
241
+ def __init__(self, config, is_cross_attention=False):
242
+ super().__init__()
243
+ self.self = BlipTextSelfAttention(config, is_cross_attention)
244
+ self.output = BlipTextSelfOutput(config)
245
+ self.pruned_heads = set()
246
+
247
+ def prune_heads(self, heads):
248
+ if len(heads) == 0:
249
+ return
250
+ heads, index = find_pruneable_heads_and_indices(
251
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
252
+ )
253
+
254
+ # Prune linear layers
255
+ self.self.query = prune_linear_layer(self.self.query, index)
256
+ self.self.key = prune_linear_layer(self.self.key, index)
257
+ self.self.value = prune_linear_layer(self.self.value, index)
258
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
259
+
260
+ # Update hyper params and store pruned heads
261
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
262
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
263
+ self.pruned_heads = self.pruned_heads.union(heads)
264
+
265
+ def forward(
266
+ self,
267
+ hidden_states: torch.Tensor,
268
+ attention_mask: Optional[torch.FloatTensor] = None,
269
+ head_mask: Optional[torch.FloatTensor] = None,
270
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
271
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
272
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
273
+ output_attentions: Optional[bool] = False,
274
+ ) -> Tuple[torch.Tensor]:
275
+ self_outputs = self.self(
276
+ hidden_states,
277
+ attention_mask,
278
+ head_mask,
279
+ encoder_hidden_states,
280
+ encoder_attention_mask,
281
+ past_key_value,
282
+ output_attentions,
283
+ )
284
+ attention_output = self.output(self_outputs[0], hidden_states)
285
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
286
+ return outputs
287
+
288
+
289
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert -> BlipText
290
+ class BlipTextIntermediate(nn.Module):
291
+ def __init__(self, config):
292
+ super().__init__()
293
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
294
+ if isinstance(config.hidden_act, str):
295
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
296
+ else:
297
+ self.intermediate_act_fn = config.hidden_act
298
+
299
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
300
+ hidden_states = self.dense(hidden_states)
301
+ hidden_states = self.intermediate_act_fn(hidden_states)
302
+ return hidden_states
303
+
304
+
305
+ # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert -> BlipText
306
+ class BlipTextOutput(nn.Module):
307
+ def __init__(self, config):
308
+ super().__init__()
309
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
310
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
311
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
312
+
313
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
314
+ hidden_states = self.dense(hidden_states)
315
+ hidden_states = self.dropout(hidden_states)
316
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
317
+ return hidden_states
318
+
319
+
320
+ class BlipTextLayer(nn.Module):
321
+ def __init__(self, config, layer_num):
322
+ super().__init__()
323
+ self.config = config
324
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
325
+ self.seq_len_dim = 1
326
+ self.attention = BlipTextAttention(config)
327
+ self.layer_num = layer_num
328
+ if self.config.is_decoder:
329
+ self.crossattention = BlipTextAttention(config, is_cross_attention=self.config.is_decoder)
330
+ self.intermediate = BlipTextIntermediate(config)
331
+ self.output = BlipTextOutput(config)
332
+
333
+ def forward(
334
+ self,
335
+ hidden_states: torch.Tensor,
336
+ attention_mask: Optional[torch.FloatTensor] = None,
337
+ head_mask: Optional[torch.FloatTensor] = None,
338
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
339
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
340
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
341
+ output_attentions: Optional[bool] = False,
342
+ ) -> Tuple[torch.Tensor]:
343
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
344
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
345
+ self_attention_outputs = self.attention(
346
+ hidden_states,
347
+ attention_mask,
348
+ head_mask,
349
+ output_attentions=output_attentions,
350
+ past_key_value=self_attn_past_key_value,
351
+ )
352
+ attention_output = self_attention_outputs[0]
353
+
354
+ outputs = self_attention_outputs[1:-1]
355
+ present_key_value = self_attention_outputs[-1]
356
+
357
+ if encoder_hidden_states is not None:
358
+ cross_attention_outputs = self.crossattention(
359
+ attention_output,
360
+ attention_mask,
361
+ head_mask,
362
+ encoder_hidden_states,
363
+ encoder_attention_mask,
364
+ output_attentions=output_attentions,
365
+ )
366
+ attention_output = cross_attention_outputs[0]
367
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
368
+ layer_output = apply_chunking_to_forward(
369
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
370
+ )
371
+ outputs = (layer_output,) + outputs
372
+
373
+ outputs = outputs + (present_key_value,)
374
+
375
+ return outputs
376
+
377
+ def feed_forward_chunk(self, attention_output):
378
+ intermediate_output = self.intermediate(attention_output)
379
+ layer_output = self.output(intermediate_output, attention_output)
380
+ return layer_output
381
+
382
+
383
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L386
384
+ class BlipTextEncoder(nn.Module):
385
+ def __init__(self, config):
386
+ super().__init__()
387
+ self.config = config
388
+ self.layer = nn.ModuleList([BlipTextLayer(config, i) for i in range(config.num_hidden_layers)])
389
+ self.gradient_checkpointing = False
390
+
391
+ def forward(
392
+ self,
393
+ hidden_states: torch.Tensor,
394
+ attention_mask: Optional[torch.FloatTensor] = None,
395
+ head_mask: Optional[torch.FloatTensor] = None,
396
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
397
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
398
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
399
+ use_cache: Optional[bool] = None,
400
+ output_attentions: Optional[bool] = False,
401
+ output_hidden_states: Optional[bool] = False,
402
+ return_dict: Optional[bool] = True,
403
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
404
+ if self.gradient_checkpointing and self.training:
405
+ if use_cache:
406
+ logger.warning(
407
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
408
+ )
409
+ use_cache = False
410
+ all_hidden_states = () if output_hidden_states else None
411
+ all_self_attentions = () if output_attentions else None
412
+ all_cross_attentions = () if output_attentions and self.config.is_decoder else None
413
+
414
+ next_decoder_cache = () if use_cache else None
415
+
416
+ for i in range(self.config.num_hidden_layers):
417
+ layer_module = self.layer[i]
418
+ if output_hidden_states:
419
+ all_hidden_states = all_hidden_states + (hidden_states,)
420
+
421
+ layer_head_mask = head_mask[i] if head_mask is not None else None
422
+ past_key_value = past_key_values[i] if past_key_values is not None else None
423
+
424
+ if self.gradient_checkpointing and self.training:
425
+ layer_outputs = self._gradient_checkpointing_func(
426
+ layer_module.__call__,
427
+ hidden_states,
428
+ attention_mask,
429
+ layer_head_mask,
430
+ encoder_hidden_states,
431
+ encoder_attention_mask,
432
+ past_key_value,
433
+ output_attentions,
434
+ )
435
+ else:
436
+ layer_outputs = layer_module(
437
+ hidden_states,
438
+ attention_mask,
439
+ layer_head_mask,
440
+ encoder_hidden_states,
441
+ encoder_attention_mask,
442
+ past_key_value,
443
+ output_attentions,
444
+ )
445
+
446
+ hidden_states = layer_outputs[0]
447
+ if use_cache:
448
+ next_decoder_cache += (layer_outputs[-1],)
449
+ if output_attentions:
450
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
451
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
452
+
453
+ if output_hidden_states:
454
+ all_hidden_states = all_hidden_states + (hidden_states,)
455
+
456
+ if not return_dict:
457
+ return tuple(
458
+ v
459
+ for v in [
460
+ hidden_states,
461
+ next_decoder_cache,
462
+ all_hidden_states,
463
+ all_self_attentions,
464
+ all_cross_attentions,
465
+ ]
466
+ if v is not None
467
+ )
468
+ return BaseModelOutputWithPastAndCrossAttentions(
469
+ last_hidden_state=hidden_states,
470
+ past_key_values=next_decoder_cache,
471
+ hidden_states=all_hidden_states,
472
+ attentions=all_self_attentions,
473
+ cross_attentions=all_cross_attentions,
474
+ )
475
+
476
+
477
+ # Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->BlipText
478
+ class BlipTextPooler(nn.Module):
479
+ def __init__(self, config):
480
+ super().__init__()
481
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
482
+ self.activation = nn.Tanh()
483
+
484
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
485
+ # We "pool" the model by simply taking the hidden state corresponding
486
+ # to the first token.
487
+ first_token_tensor = hidden_states[:, 0]
488
+ pooled_output = self.dense(first_token_tensor)
489
+ pooled_output = self.activation(pooled_output)
490
+ return pooled_output
491
+
492
+
493
+ # Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->BlipText
494
+ class BlipTextPredictionHeadTransform(nn.Module):
495
+ def __init__(self, config):
496
+ super().__init__()
497
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
498
+ if isinstance(config.hidden_act, str):
499
+ self.transform_act_fn = ACT2FN[config.hidden_act]
500
+ else:
501
+ self.transform_act_fn = config.hidden_act
502
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
503
+
504
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
505
+ hidden_states = self.dense(hidden_states)
506
+ hidden_states = self.transform_act_fn(hidden_states)
507
+ hidden_states = self.LayerNorm(hidden_states)
508
+ return hidden_states
509
+
510
+
511
+ # Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->BlipText
512
+ class BlipTextLMPredictionHead(nn.Module):
513
+ def __init__(self, config):
514
+ super().__init__()
515
+ self.transform = BlipTextPredictionHeadTransform(config)
516
+
517
+ # The output weights are the same as the input embeddings, but there is
518
+ # an output-only bias for each token.
519
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
520
+
521
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
522
+
523
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
524
+ self.decoder.bias = self.bias
525
+
526
+ def _tie_weights(self):
527
+ self.decoder.bias = self.bias
528
+
529
+ def forward(self, hidden_states):
530
+ hidden_states = self.transform(hidden_states)
531
+ hidden_states = self.decoder(hidden_states)
532
+ return hidden_states
533
+
534
+
535
+ # Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->BlipText
536
+ class BlipTextOnlyMLMHead(nn.Module):
537
+ def __init__(self, config):
538
+ super().__init__()
539
+ self.predictions = BlipTextLMPredictionHead(config)
540
+
541
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
542
+ prediction_scores = self.predictions(sequence_output)
543
+ return prediction_scores
544
+
545
+
546
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L548
547
+ class BlipTextPreTrainedModel(PreTrainedModel):
548
+ """
549
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
550
+ models.
551
+ """
552
+
553
+ config_class = BlipTextConfig
554
+ base_model_prefix = "bert"
555
+ _no_split_modules = []
556
+
557
+ def _init_weights(self, module):
558
+ """Initialize the weights"""
559
+ if isinstance(module, (nn.Linear, nn.Embedding)):
560
+ # Slightly different from the TF version which uses truncated_normal for initialization
561
+ # cf https://github.com/pytorch/pytorch/pull/5617
562
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
563
+ elif isinstance(module, nn.LayerNorm):
564
+ module.bias.data.zero_()
565
+ module.weight.data.fill_(1.0)
566
+ if isinstance(module, nn.Linear) and module.bias is not None:
567
+ module.bias.data.zero_()
568
+
569
+
570
+ # Adapted from https://github.com/salesforce/BLIP/blob/3a29b7410476bf5f2ba0955827390eb6ea1f4f9d/models/med.py#L571
571
+ class BlipTextModel(BlipTextPreTrainedModel):
572
+ """
573
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
574
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
575
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
576
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. argument and `is_decoder` set to `True`; an
577
+ `encoder_hidden_states` is then expected as an input to the forward pass.
578
+ """
579
+
580
+ def __init__(self, config, add_pooling_layer=True):
581
+ super().__init__(config)
582
+ self.config = config
583
+
584
+ self.embeddings = BlipTextEmbeddings(config)
585
+ self.encoder = BlipTextEncoder(config)
586
+ self.pooler = BlipTextPooler(config) if add_pooling_layer else None
587
+
588
+ self.post_init()
589
+
590
+ def get_input_embeddings(self):
591
+ return self.embeddings.word_embeddings
592
+
593
+ def set_input_embeddings(self, value):
594
+ self.embeddings.word_embeddings = value
595
+
596
+ # Copied from transformers.models.bert.modeling_bert.BertModel._prune_heads
597
+ def _prune_heads(self, heads_to_prune):
598
+ """
599
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
600
+ class PreTrainedModel
601
+ """
602
+ for layer, heads in heads_to_prune.items():
603
+ self.encoder.layer[layer].attention.prune_heads(heads)
604
+
605
+ def get_extended_attention_mask(
606
+ self, attention_mask: Tensor, input_shape: Tuple[int], device: device, is_decoder: bool
607
+ ) -> Tensor:
608
+ """
609
+ Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
610
+
611
+ Arguments:
612
+ attention_mask (`torch.Tensor`):
613
+ Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
614
+ input_shape (`Tuple[int]`):
615
+ The shape of the input to the model.
616
+ device (`torch.device`):
617
+ The device of the input to the model.
618
+
619
+ Returns:
620
+ `torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`.
621
+ """
622
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
623
+ # ourselves in which case we just need to make it broadcastable to all heads.
624
+ if attention_mask.dim() == 3:
625
+ extended_attention_mask = attention_mask[:, None, :, :]
626
+ elif attention_mask.dim() == 2:
627
+ # Provided a padding mask of dimensions [batch_size, seq_length]
628
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
629
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
630
+ if is_decoder:
631
+ batch_size, seq_length = input_shape
632
+
633
+ seq_ids = torch.arange(seq_length, device=device)
634
+ causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None]
635
+ # in case past_key_values are used we need to add a prefix ones mask to the causal mask
636
+ # causal and attention masks must have same type with pytorch version < 1.3
637
+ causal_mask = causal_mask.to(attention_mask.dtype)
638
+
639
+ if causal_mask.shape[1] < attention_mask.shape[1]:
640
+ prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
641
+ causal_mask = torch.cat(
642
+ [
643
+ torch.ones(
644
+ (batch_size, seq_length, prefix_seq_len), device=device, dtype=causal_mask.dtype
645
+ ),
646
+ causal_mask,
647
+ ],
648
+ axis=-1,
649
+ )
650
+
651
+ extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
652
+ else:
653
+ extended_attention_mask = attention_mask[:, None, None, :]
654
+ else:
655
+ raise ValueError(
656
+ "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
657
+ input_shape, attention_mask.shape
658
+ )
659
+ )
660
+
661
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
662
+ # masked positions, this operation will create a tensor which is 0.0 for
663
+ # positions we want to attend and -10000.0 for masked positions.
664
+ # Since we are adding it to the raw scores before the softmax, this is
665
+ # effectively the same as removing these entirely.
666
+ extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
667
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
668
+ return extended_attention_mask
669
+
670
+ def forward(
671
+ self,
672
+ input_ids: Optional[torch.Tensor] = None,
673
+ attention_mask: Optional[torch.Tensor] = None,
674
+ position_ids: Optional[torch.Tensor] = None,
675
+ head_mask: Optional[torch.Tensor] = None,
676
+ inputs_embeds: Optional[torch.Tensor] = None,
677
+ encoder_embeds: Optional[torch.Tensor] = None,
678
+ encoder_hidden_states: Optional[torch.Tensor] = None,
679
+ encoder_attention_mask: Optional[torch.Tensor] = None,
680
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
681
+ use_cache: Optional[bool] = None,
682
+ output_attentions: Optional[bool] = None,
683
+ output_hidden_states: Optional[bool] = None,
684
+ return_dict: Optional[bool] = None,
685
+ is_decoder: Optional[bool] = False,
686
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
687
+ r"""
688
+ encoder_hidden_states (`torch.FloatTensor`, *optional*):
689
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
690
+ the model is configured as a decoder.
691
+ encoder_attention_mask (`torch.FloatTensor`, *optional*):
692
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
693
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
694
+ - 1 for tokens that are **not masked**,
695
+ - 0 for tokens that are **masked**.
696
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*):
697
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
698
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
699
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
700
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
701
+ use_cache (`bool`, *optional*):
702
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
703
+ `past_key_values`).
704
+ """
705
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
706
+ output_hidden_states = (
707
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
708
+ )
709
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
710
+
711
+ if is_decoder:
712
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
713
+ else:
714
+ use_cache = False
715
+
716
+ if input_ids is not None and inputs_embeds is not None:
717
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
718
+ elif input_ids is not None:
719
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
720
+ input_shape = input_ids.size()
721
+ batch_size, seq_length = input_shape
722
+ device = input_ids.device
723
+ elif inputs_embeds is not None:
724
+ input_shape = inputs_embeds.size()[:-1]
725
+ batch_size, seq_length = input_shape
726
+ device = inputs_embeds.device
727
+ elif encoder_embeds is not None:
728
+ input_shape = encoder_embeds.size()[:-1]
729
+ batch_size, seq_length = input_shape
730
+ device = encoder_embeds.device
731
+ else:
732
+ raise ValueError("You have to specify either input_ids or inputs_embeds or encoder_embeds")
733
+
734
+ # past_key_values_length
735
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
736
+
737
+ if attention_mask is None:
738
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length))).to(device)
739
+
740
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
741
+ # ourselves in which case we just need to make it broadcastable to all heads.
742
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
743
+ attention_mask, input_shape, device, is_decoder
744
+ )
745
+
746
+ # If a 2D or 3D attention mask is provided for the cross-attention
747
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
748
+ if encoder_hidden_states is not None:
749
+ if isinstance(encoder_hidden_states, list):
750
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size()
751
+ else:
752
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
753
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
754
+
755
+ if isinstance(encoder_attention_mask, list):
756
+ encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask]
757
+ elif encoder_attention_mask is None:
758
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
759
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
760
+ else:
761
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
762
+ else:
763
+ encoder_extended_attention_mask = None
764
+
765
+ # Prepare head mask if needed
766
+ # 1.0 in head_mask indicate we keep the head
767
+ # attention_probs has shape bsz x n_heads x N x N
768
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
769
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
770
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
771
+
772
+ if encoder_embeds is None:
773
+ embedding_output = self.embeddings(
774
+ input_ids=input_ids,
775
+ position_ids=position_ids,
776
+ inputs_embeds=inputs_embeds,
777
+ past_key_values_length=past_key_values_length,
778
+ )
779
+ else:
780
+ embedding_output = encoder_embeds
781
+
782
+ encoder_outputs = self.encoder(
783
+ embedding_output,
784
+ attention_mask=extended_attention_mask,
785
+ head_mask=head_mask,
786
+ encoder_hidden_states=encoder_hidden_states,
787
+ encoder_attention_mask=encoder_extended_attention_mask,
788
+ past_key_values=past_key_values,
789
+ use_cache=use_cache,
790
+ output_attentions=output_attentions,
791
+ output_hidden_states=output_hidden_states,
792
+ return_dict=return_dict,
793
+ )
794
+ sequence_output = encoder_outputs[0]
795
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
796
+
797
+ if not return_dict:
798
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
799
+
800
+ return BaseModelOutputWithPoolingAndCrossAttentions(
801
+ last_hidden_state=sequence_output,
802
+ pooler_output=pooled_output,
803
+ past_key_values=encoder_outputs.past_key_values,
804
+ hidden_states=encoder_outputs.hidden_states,
805
+ attentions=encoder_outputs.attentions,
806
+ cross_attentions=encoder_outputs.cross_attentions,
807
+ )
808
+
809
+
810
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L811
811
+ class BlipTextLMHeadModel(BlipTextPreTrainedModel, GenerationMixin):
812
+ def __init__(self, config):
813
+ super().__init__(config)
814
+
815
+ self.bert = BlipTextModel(config, add_pooling_layer=False)
816
+ self.cls = BlipTextOnlyMLMHead(config)
817
+ self.label_smoothing = config.label_smoothing
818
+
819
+ def get_input_embeddings(self):
820
+ return self.bert.get_input_embeddings()
821
+
822
+ def set_input_embeddings(self, new_embeddings):
823
+ self.bert.set_input_embeddings(new_embeddings)
824
+
825
+ def get_output_embeddings(self):
826
+ return self.cls.predictions.decoder
827
+
828
+ def set_output_embeddings(self, new_embeddings):
829
+ self.cls.predictions.decoder = new_embeddings
830
+ self.cls.predictions.bias = new_embeddings.bias
831
+
832
+ def forward(
833
+ self,
834
+ input_ids: Optional[torch.Tensor] = None,
835
+ attention_mask: Optional[torch.Tensor] = None,
836
+ position_ids: Optional[torch.Tensor] = None,
837
+ head_mask: Optional[torch.Tensor] = None,
838
+ inputs_embeds: Optional[torch.Tensor] = None,
839
+ encoder_hidden_states: Optional[torch.Tensor] = None,
840
+ encoder_attention_mask: Optional[torch.Tensor] = None,
841
+ labels: Optional[torch.Tensor] = None,
842
+ past_key_values: Optional[List[torch.Tensor]] = None,
843
+ use_cache: Optional[bool] = None,
844
+ output_attentions: Optional[bool] = None,
845
+ output_hidden_states: Optional[bool] = None,
846
+ return_dict: Optional[bool] = None,
847
+ return_logits: Optional[bool] = False,
848
+ is_decoder: Optional[bool] = True,
849
+ reduction: Optional[str] = "mean",
850
+ ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
851
+ r"""
852
+ encoder_hidden_states (`torch.FloatTensor`, *optional*): Sequence of
853
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is
854
+ configured as a decoder.
855
+ encoder_attention_mask (`torch.FloatTensor`, *optional*):
856
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
857
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
858
+ - 1 for tokens that are **not masked**,
859
+ - 0 for tokens that are **masked**.
860
+ labels (`torch.LongTensor`, *optional*):
861
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
862
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
863
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
864
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*):
865
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
866
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
867
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
868
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
869
+ use_cache (`bool`, *optional*):
870
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
871
+ `past_key_values`).
872
+ """
873
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
874
+ if labels is not None:
875
+ use_cache = False
876
+
877
+ outputs = self.bert(
878
+ input_ids,
879
+ attention_mask=attention_mask,
880
+ position_ids=position_ids,
881
+ head_mask=head_mask,
882
+ inputs_embeds=inputs_embeds,
883
+ encoder_hidden_states=encoder_hidden_states,
884
+ encoder_attention_mask=encoder_attention_mask,
885
+ past_key_values=past_key_values,
886
+ use_cache=use_cache,
887
+ output_attentions=output_attentions,
888
+ output_hidden_states=output_hidden_states,
889
+ return_dict=return_dict,
890
+ is_decoder=is_decoder,
891
+ )
892
+
893
+ sequence_output = outputs[0]
894
+ prediction_scores = self.cls(sequence_output)
895
+
896
+ if return_logits:
897
+ return prediction_scores[:, :-1, :].contiguous()
898
+
899
+ lm_loss = None
900
+ if labels is not None:
901
+ # we are doing next-token prediction; shift prediction scores and input ids by one
902
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
903
+ labels = labels[:, 1:].contiguous().to(shifted_prediction_scores.device)
904
+ loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=self.label_smoothing)
905
+ lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
906
+ if reduction == "none":
907
+ lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1)
908
+
909
+ if not return_dict:
910
+ output = (prediction_scores,) + outputs[2:]
911
+ return ((lm_loss,) + output) if lm_loss is not None else output
912
+
913
+ return CausalLMOutputWithCrossAttentions(
914
+ loss=lm_loss,
915
+ logits=prediction_scores,
916
+ past_key_values=outputs.past_key_values,
917
+ hidden_states=outputs.hidden_states,
918
+ attentions=outputs.attentions,
919
+ cross_attentions=outputs.cross_attentions,
920
+ )
921
+
922
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
923
+ # Overwrite -- hardcoded key return (`is_decoder=True`)
924
+
925
+ input_shape = input_ids.shape
926
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
927
+ if attention_mask is None:
928
+ attention_mask = input_ids.new_ones(input_shape)
929
+
930
+ # cut decoder_input_ids if past_key_values is used
931
+ if past_key_values is not None:
932
+ past_length = past_key_values[0][0].shape[2]
933
+
934
+ # Some generation methods already pass only the last input ID
935
+ if input_ids.shape[1] > past_length:
936
+ remove_prefix_length = past_length
937
+ else:
938
+ # Default to old behavior: keep only final ID
939
+ remove_prefix_length = input_ids.shape[1] - 1
940
+
941
+ input_ids = input_ids[:, remove_prefix_length:]
942
+
943
+ return {
944
+ "input_ids": input_ids,
945
+ "attention_mask": attention_mask,
946
+ "past_key_values": past_key_values,
947
+ "encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None),
948
+ "encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None),
949
+ "is_decoder": True,
950
+ }
951
+
952
+ def _reorder_cache(self, past_key_values, beam_idx):
953
+ reordered_past = ()
954
+ for layer_past in past_key_values:
955
+ reordered_past += (
956
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
957
+ )
958
+ return reordered_past
lib/python3.12/site-packages/transformers/models/blip/modeling_tf_blip.py ADDED
@@ -0,0 +1,1709 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Salesforce Team 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
+ """TensorFlow BLIP model."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import warnings
20
+ from dataclasses import dataclass
21
+ from typing import Any, Optional, Tuple, Union
22
+
23
+ import tensorflow as tf
24
+
25
+ from ...modeling_tf_outputs import TFBaseModelOutput, TFBaseModelOutputWithPooling
26
+ from ...modeling_tf_utils import (
27
+ TFPreTrainedModel,
28
+ get_initializer,
29
+ get_tf_activation,
30
+ keras,
31
+ keras_serializable,
32
+ shape_list,
33
+ unpack_inputs,
34
+ )
35
+ from ...tf_utils import check_embeddings_within_bounds, stable_softmax
36
+ from ...utils import (
37
+ ModelOutput,
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ logging,
41
+ replace_return_docstrings,
42
+ )
43
+ from .configuration_blip import BlipConfig, BlipTextConfig, BlipVisionConfig
44
+ from .modeling_tf_blip_text import BLIP_TEXT_INPUTS_DOCSTRING, TFBlipTextLMHeadModel, TFBlipTextModel
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+ _CHECKPOINT_FOR_DOC = "Salesforce/blip-vqa-base"
50
+
51
+
52
+ # Copied from transformers.models.clip.modeling_tf_clip.contrastive_loss
53
+ def contrastive_loss(logits: tf.Tensor) -> tf.Tensor:
54
+ return tf.math.reduce_mean(
55
+ keras.metrics.sparse_categorical_crossentropy(
56
+ y_true=tf.range(shape_list(logits)[0]), y_pred=logits, from_logits=True
57
+ )
58
+ )
59
+
60
+
61
+ # Copied from transformers.models.clip.modeling_tf_clip.clip_loss with clip->blip
62
+ def blip_loss(similarity: tf.Tensor) -> tf.Tensor:
63
+ caption_loss = contrastive_loss(similarity)
64
+ image_loss = contrastive_loss(tf.transpose(similarity))
65
+ return (caption_loss + image_loss) / 2.0
66
+
67
+
68
+ @dataclass
69
+ class TFBlipForConditionalGenerationModelOutput(ModelOutput):
70
+ """
71
+ Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
72
+ last hidden states. This class also adds the loss term from the text decoder.
73
+
74
+ Args:
75
+ loss (`tf.Tensor`, *optional*, returned when `labels` is provided, `tf.Tensor` of shape `(1,)`):
76
+ Languge modeling loss from the text decoder.
77
+ logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`, *optional*):
78
+ Prediction scores of the language modeling head of the text decoder model.
79
+ image_embeds (`tf.Tensor` of shape `(batch_size, output_dim)`, *optional*):
80
+ The image embeddings obtained after applying the Vision Transformer model to the input image.
81
+ last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
82
+ Sequence of hidden-states at the output of the last layer of the model.
83
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True`):
84
+ Tuple of `tf.Tensor` (one for the output of the embeddings, if the model has an embedding layer, + one for
85
+ the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
86
+
87
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
88
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed):
89
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
90
+ sequence_length)`.
91
+
92
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
93
+ heads.`
94
+ """
95
+
96
+ loss: Tuple[tf.Tensor] | None = None
97
+ logits: Tuple[tf.Tensor] | None = None
98
+ image_embeds: tf.Tensor | None = None
99
+ last_hidden_state: Optional[tf.Tensor] = None
100
+ hidden_states: Tuple[tf.Tensor, ...] | None = None
101
+ attentions: Tuple[tf.Tensor, ...] | None = None
102
+
103
+ @property
104
+ def decoder_logits(self):
105
+ warnings.warn(
106
+ "`decoder_logits` attribute is deprecated and will be removed in version 5 of Transformers."
107
+ " Please use the `logits` attribute to retrieve the final output instead.",
108
+ FutureWarning,
109
+ )
110
+ return self.logits
111
+
112
+
113
+ @dataclass
114
+ class TFBlipTextVisionModelOutput(ModelOutput):
115
+ """
116
+ Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
117
+ last hidden states. This class also adds the loss term from the text decoder.
118
+
119
+ Args:
120
+ loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
121
+ Languge modeling loss from the text decoder.
122
+ image_embeds (`tf.Tensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
123
+ The image embeddings obtained by applying the projection layer to the pooler_output.
124
+ last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
125
+ Sequence of hidden-states at the output of the last layer of the model.
126
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
127
+ Tuple of `tf.Tensor` (one for the output of the embeddings, if the model has an embedding layer, + one for
128
+ the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
129
+
130
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
131
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
132
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
133
+ sequence_length)`.
134
+
135
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
136
+ heads.
137
+ """
138
+
139
+ loss: tf.Tensor | None = None
140
+ image_embeds: tf.Tensor | None = None
141
+ last_hidden_state: Optional[tf.Tensor] = None
142
+ hidden_states: Tuple[tf.Tensor, ...] | None = None
143
+ attentions: Tuple[tf.Tensor, ...] | None = None
144
+
145
+
146
+ @dataclass
147
+ class TFBlipImageTextMatchingModelOutput(ModelOutput):
148
+ """
149
+ Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
150
+ last hidden states. This class also adds the loss term from the text decoder as well as the image-text similarity
151
+ scores.
152
+
153
+ Args:
154
+ itm_score (`tf.Tensor`):
155
+ The image-text similarity scores.
156
+ loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
157
+ Languge modeling loss from the text decoder.
158
+ image_embeds (`tf.Tensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
159
+ The image embeddings obtained by applying the projection layer to the pooler_output.
160
+ last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
161
+ Sequence of hidden-states at the output of the last layer of the model.
162
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
163
+ Tuple of `tf.Tensor` (one for the output of the embeddings, if the model has an embedding layer, + one for
164
+ the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
165
+
166
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
167
+ vision_pooler_output (`tf.Tensor` of shape `(batch_size, hidden_size)`, *optional*):
168
+ Last layer hidden-state of the vision of the vision-only branch of the model.
169
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
170
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
171
+ sequence_length)`.
172
+
173
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
174
+ heads.
175
+ question_embeds (`tf.Tensor`):
176
+ The question embeddings obtained by the text projection layer.
177
+ """
178
+
179
+ itm_score: tf.Tensor | None = None
180
+ loss: tf.Tensor | None = None
181
+ image_embeds: tf.Tensor | None = None
182
+ last_hidden_state: Optional[tf.Tensor] = None
183
+ hidden_states: Tuple[tf.Tensor, ...] | None = None
184
+ vision_pooler_output: tf.Tensor | None = None
185
+ attentions: Tuple[tf.Tensor, ...] | None = None
186
+ question_embeds: Tuple[tf.Tensor] | None = None
187
+
188
+
189
+ @dataclass
190
+ class TFBlipOutput(ModelOutput):
191
+ """
192
+ Args:
193
+ loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
194
+ Contrastive loss for image-text similarity.
195
+ logits_per_image:(`tf.Tensor` of shape `(image_batch_size, text_batch_size)`):
196
+ The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
197
+ similarity scores.
198
+ logits_per_text:(`tf.Tensor` of shape `(text_batch_size, image_batch_size)`):
199
+ The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
200
+ similarity scores.
201
+ text_embeds(`tf.Tensor` of shape `(batch_size, output_dim`):
202
+ The text embeddings obtained by applying the projection layer to the pooled output of [`BlipTextModel`].
203
+ image_embeds(`tf.Tensor` of shape `(batch_size, output_dim`):
204
+ The image embeddings obtained by applying the projection layer to the pooled output of [`BlipVisionModel`].
205
+ text_model_output(`BaseModelOutputWithPooling`):
206
+ The output of the [`BlipTextModel`].
207
+ vision_model_output(`BaseModelOutputWithPooling`):
208
+ The output of the [`BlipVisionModel`].
209
+ """
210
+
211
+ loss: tf.Tensor | None = None
212
+ logits_per_image: Optional[tf.Tensor] = None
213
+ logits_per_text: Optional[tf.Tensor] = None
214
+ text_embeds: Optional[tf.Tensor] = None
215
+ image_embeds: Optional[tf.Tensor] = None
216
+ text_model_output: TFBaseModelOutputWithPooling = None
217
+ vision_model_output: TFBaseModelOutputWithPooling = None
218
+
219
+ def to_tuple(self) -> Tuple[Any]:
220
+ return tuple(
221
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
222
+ for k in self.keys()
223
+ )
224
+
225
+
226
+ class TFBlipVisionEmbeddings(keras.layers.Layer):
227
+ def __init__(self, config: BlipVisionConfig, **kwargs):
228
+ super().__init__(**kwargs)
229
+ self.config = config
230
+ self.embed_dim = config.hidden_size
231
+ self.image_size = config.image_size
232
+ self.patch_size = config.patch_size
233
+
234
+ self.patch_embedding = keras.layers.Conv2D(
235
+ filters=self.embed_dim,
236
+ kernel_size=self.patch_size,
237
+ strides=self.patch_size,
238
+ kernel_initializer=get_initializer(self.config.initializer_range),
239
+ data_format="channels_last",
240
+ name="patch_embedding",
241
+ )
242
+
243
+ self.num_patches = (self.image_size // self.patch_size) ** 2
244
+ self.num_positions = self.num_patches + 1
245
+
246
+ def build(self, input_shape=None):
247
+ self.class_embedding = self.add_weight(
248
+ shape=(1, 1, self.embed_dim),
249
+ initializer=get_initializer(self.config.initializer_range),
250
+ trainable=True,
251
+ name="class_embedding",
252
+ )
253
+
254
+ self.position_embedding = self.add_weight(
255
+ shape=(1, self.num_positions, self.embed_dim),
256
+ initializer=get_initializer(self.config.initializer_range),
257
+ trainable=True,
258
+ name="position_embedding",
259
+ )
260
+
261
+ if self.built:
262
+ return
263
+ self.built = True
264
+ if getattr(self, "patch_embedding", None) is not None:
265
+ with tf.name_scope(self.patch_embedding.name):
266
+ self.patch_embedding.build([None, None, None, 3])
267
+
268
+ def call(self, pixel_values: tf.Tensor) -> tf.Tensor:
269
+ # Input is channels-first, we transpose. PyTorch transposes after the conv because PyTorch
270
+ # likes channels-first convs.
271
+ batch_size = tf.shape(pixel_values)[0]
272
+ pixel_values = tf.transpose(pixel_values, perm=(0, 2, 3, 1))
273
+ patch_embeds = self.patch_embedding(pixel_values)
274
+ patch_embeds = tf.reshape(patch_embeds, (batch_size, self.num_patches, -1))
275
+
276
+ class_embeds = tf.broadcast_to(self.class_embedding, (batch_size, 1, self.embed_dim))
277
+ embeddings = tf.concat([class_embeds, patch_embeds], axis=1)
278
+ embeddings = embeddings + self.position_embedding[:, : tf.shape(embeddings)[1], :]
279
+ return embeddings
280
+
281
+
282
+ # Copied from transformers.models.clip.modeling_tf_clip.TFCLIPTextEmbeddings with CLIP->Blip
283
+ class TFBlipTextEmbeddings(keras.layers.Layer):
284
+ def __init__(self, config: BlipTextConfig, **kwargs):
285
+ super().__init__(**kwargs)
286
+
287
+ self.embed_dim = config.hidden_size
288
+
289
+ self.config = config
290
+
291
+ def build(self, input_shape: tf.TensorShape = None):
292
+ with tf.name_scope("token_embedding"):
293
+ self.weight = self.add_weight(
294
+ shape=(self.config.vocab_size, self.embed_dim),
295
+ initializer=get_initializer(self.config.initializer_factor * self.config.initializer_range),
296
+ trainable=True,
297
+ name="weight",
298
+ )
299
+
300
+ with tf.name_scope("position_embedding"):
301
+ self.position_embedding = self.add_weight(
302
+ shape=(self.config.max_position_embeddings, self.embed_dim),
303
+ initializer=get_initializer(self.config.initializer_factor * self.config.initializer_range),
304
+ trainable=True,
305
+ name="embeddings",
306
+ )
307
+
308
+ super().build(input_shape)
309
+
310
+ def call(
311
+ self,
312
+ input_ids: Optional[tf.Tensor] = None,
313
+ position_ids: Optional[tf.Tensor] = None,
314
+ inputs_embeds: Optional[tf.Tensor] = None,
315
+ ) -> tf.Tensor:
316
+ """
317
+ Applies embedding based on inputs tensor.
318
+
319
+ Returns:
320
+ final_embeddings (`tf.Tensor`): output embedding tensor.
321
+ """
322
+ if input_ids is None and inputs_embeds is None:
323
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
324
+
325
+ if inputs_embeds is None:
326
+ check_embeddings_within_bounds(input_ids, self.config.vocab_size)
327
+ inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
328
+
329
+ input_shape = shape_list(inputs_embeds)[:-1]
330
+
331
+ if position_ids is None:
332
+ position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
333
+
334
+ position_embeds = tf.gather(params=self.position_embedding, indices=position_ids)
335
+ position_embeds = tf.tile(input=position_embeds, multiples=(input_shape[0], 1, 1))
336
+ final_embeddings = inputs_embeds + position_embeds
337
+
338
+ return final_embeddings
339
+
340
+
341
+ class TFBlipAttention(keras.layers.Layer):
342
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
343
+
344
+ def __init__(self, config, **kwargs):
345
+ super().__init__(**kwargs)
346
+ self.config = config
347
+ self.embed_dim = config.hidden_size
348
+ self.num_heads = config.num_attention_heads
349
+ self.head_dim = self.embed_dim // self.num_heads
350
+ if self.head_dim * self.num_heads != self.embed_dim:
351
+ raise ValueError(
352
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
353
+ f" {self.num_heads})."
354
+ )
355
+ self.scale = self.head_dim**-0.5
356
+ self.dropout = keras.layers.Dropout(config.attention_dropout, name="dropout")
357
+
358
+ self.qkv = keras.layers.Dense(
359
+ 3 * self.embed_dim, kernel_initializer=get_initializer(config.initializer_range), name="qkv"
360
+ )
361
+
362
+ self.projection = keras.layers.Dense(
363
+ self.embed_dim, kernel_initializer=get_initializer(config.initializer_range), name="projection"
364
+ )
365
+
366
+ def call(
367
+ self,
368
+ hidden_states: tf.Tensor,
369
+ head_mask: tf.Tensor | None = None,
370
+ output_attentions: Optional[bool] = False,
371
+ training: Optional[bool] = None,
372
+ ) -> Tuple[tf.Tensor, tf.Tensor | None, Tuple[tf.Tensor] | None]:
373
+ """Input shape: Batch x Time x Channel"""
374
+
375
+ bsz, tgt_len, embed_dim = shape_list(hidden_states)
376
+
377
+ mixed_qkv = self.qkv(hidden_states)
378
+ mixed_qkv = tf.reshape(mixed_qkv, (bsz, tgt_len, 3, self.num_heads, self.head_dim))
379
+ mixed_qkv = tf.transpose(mixed_qkv, perm=(2, 0, 3, 1, 4))
380
+
381
+ query_states, key_states, value_states = mixed_qkv[0], mixed_qkv[1], mixed_qkv[2]
382
+
383
+ # Take the dot product between "query" and "key" to get the raw attention scores.
384
+ attention_scores = query_states @ tf.transpose(key_states, (0, 1, 3, 2))
385
+
386
+ attention_scores = attention_scores * self.scale
387
+
388
+ # Normalize the attention scores to probabilities.
389
+ attention_probs = stable_softmax(attention_scores, axis=-1)
390
+
391
+ # This is actually dropping out entire tokens to attend to, which might
392
+ # seem a bit unusual, but is taken from the original Transformer paper.
393
+ attention_probs = self.dropout(attention_probs, training=training)
394
+
395
+ # Mask heads if we want to
396
+ if head_mask is not None:
397
+ attention_probs = attention_probs * head_mask
398
+
399
+ context_layer = tf.transpose(attention_probs @ value_states, perm=(0, 2, 1, 3))
400
+
401
+ new_context_layer_shape = shape_list(context_layer)[:-2] + [self.embed_dim]
402
+ context_layer = tf.reshape(context_layer, new_context_layer_shape)
403
+
404
+ output = self.projection(context_layer)
405
+
406
+ outputs = (output, attention_probs) if output_attentions else (output, None)
407
+
408
+ return outputs
409
+
410
+ def build(self, input_shape=None):
411
+ if self.built:
412
+ return
413
+ self.built = True
414
+ if getattr(self, "dropout", None) is not None:
415
+ with tf.name_scope(self.dropout.name):
416
+ self.dropout.build(None)
417
+ if getattr(self, "qkv", None) is not None:
418
+ with tf.name_scope(self.qkv.name):
419
+ self.qkv.build([None, None, self.embed_dim])
420
+ if getattr(self, "projection", None) is not None:
421
+ with tf.name_scope(self.projection.name):
422
+ self.projection.build([None, None, self.embed_dim])
423
+
424
+
425
+ class TFBlipMLP(keras.layers.Layer):
426
+ def __init__(self, config: BlipConfig, **kwargs):
427
+ super().__init__(**kwargs)
428
+
429
+ self.activation_fn = get_tf_activation(config.hidden_act)
430
+
431
+ in_proj_std = (config.hidden_size**-0.5) * ((2 * config.num_hidden_layers) ** -0.5)
432
+ fc_std = (2 * config.hidden_size) ** -0.5
433
+
434
+ self.fc1 = keras.layers.Dense(
435
+ units=config.intermediate_size, kernel_initializer=get_initializer(fc_std), name="fc1"
436
+ )
437
+ self.fc2 = keras.layers.Dense(
438
+ units=config.hidden_size, kernel_initializer=get_initializer(in_proj_std), name="fc2"
439
+ )
440
+ self.config = config
441
+
442
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
443
+ hidden_states = self.fc1(inputs=hidden_states)
444
+ hidden_states = self.activation_fn(hidden_states)
445
+ hidden_states = self.fc2(inputs=hidden_states)
446
+ return hidden_states
447
+
448
+ def build(self, input_shape=None):
449
+ if self.built:
450
+ return
451
+ self.built = True
452
+ if getattr(self, "fc1", None) is not None:
453
+ with tf.name_scope(self.fc1.name):
454
+ self.fc1.build([None, None, self.config.hidden_size])
455
+ if getattr(self, "fc2", None) is not None:
456
+ with tf.name_scope(self.fc2.name):
457
+ self.fc2.build([None, None, self.config.intermediate_size])
458
+
459
+
460
+ class TFBlipEncoderLayer(keras.layers.Layer):
461
+ def __init__(self, config: BlipConfig, **kwargs):
462
+ super().__init__(**kwargs)
463
+ self.embed_dim = config.hidden_size
464
+ self.self_attn = TFBlipAttention(config, name="self_attn")
465
+ self.layer_norm1 = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm1")
466
+ self.mlp = TFBlipMLP(config, name="mlp")
467
+ self.layer_norm2 = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm2")
468
+
469
+ def call(
470
+ self,
471
+ hidden_states: tf.Tensor,
472
+ attention_mask: tf.Tensor,
473
+ output_attentions: Optional[bool] = False,
474
+ training: Optional[bool] = None,
475
+ ) -> Tuple[tf.Tensor]:
476
+ """
477
+ Args:
478
+ hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
479
+ attention_mask (`tf.Tensor`): attention mask of size
480
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
481
+ `(config.encoder_attention_heads,)`.
482
+ output_attentions (`bool`, *optional*):
483
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
484
+ returned tensors for more detail.
485
+ """
486
+ residual = hidden_states
487
+
488
+ hidden_states = self.layer_norm1(hidden_states)
489
+ hidden_states, attn_weights = self.self_attn(
490
+ hidden_states=hidden_states,
491
+ head_mask=attention_mask,
492
+ output_attentions=output_attentions,
493
+ training=training,
494
+ )
495
+ hidden_states = hidden_states + residual
496
+ residual = hidden_states
497
+ hidden_states = self.layer_norm2(hidden_states)
498
+ hidden_states = self.mlp(hidden_states)
499
+
500
+ hidden_states = hidden_states + residual
501
+
502
+ outputs = (hidden_states,)
503
+
504
+ if output_attentions:
505
+ outputs += (attn_weights,)
506
+
507
+ return outputs
508
+
509
+ def build(self, input_shape=None):
510
+ if self.built:
511
+ return
512
+ self.built = True
513
+ if getattr(self, "self_attn", None) is not None:
514
+ with tf.name_scope(self.self_attn.name):
515
+ self.self_attn.build(None)
516
+ if getattr(self, "layer_norm1", None) is not None:
517
+ with tf.name_scope(self.layer_norm1.name):
518
+ self.layer_norm1.build([None, None, self.embed_dim])
519
+ if getattr(self, "mlp", None) is not None:
520
+ with tf.name_scope(self.mlp.name):
521
+ self.mlp.build(None)
522
+ if getattr(self, "layer_norm2", None) is not None:
523
+ with tf.name_scope(self.layer_norm2.name):
524
+ self.layer_norm2.build([None, None, self.embed_dim])
525
+
526
+
527
+ class TFBlipPreTrainedModel(TFPreTrainedModel):
528
+ """
529
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
530
+ models.
531
+ """
532
+
533
+ config_class = BlipConfig
534
+ base_model_prefix = "blip"
535
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
536
+
537
+
538
+ BLIP_START_DOCSTRING = r"""
539
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
540
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
541
+ etc.)
542
+
543
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
544
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
545
+ behavior.
546
+
547
+ Parameters:
548
+ config ([`BlipConfig`]): Model configuration class with all the parameters of the model.
549
+ Initializing with a config file does not load the weights associated with the model, only the
550
+ configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
551
+ """
552
+
553
+ BLIP_VISION_INPUTS_DOCSTRING = r"""
554
+ Args:
555
+ pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
556
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
557
+ [`BlipImageProcessor`]. See [`BlipImageProcessor.__call__`] for details.
558
+ output_attentions (`bool`, *optional*):
559
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
560
+ tensors for more detail.
561
+ output_hidden_states (`bool`, *optional*):
562
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
563
+ more detail.
564
+ return_dict (`bool`, *optional*):
565
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
566
+ """
567
+
568
+ BLIP_INPUTS_DOCSTRING = r"""
569
+ Args:
570
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
571
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
572
+ it.
573
+
574
+ Indices can be obtained using [`AutoProcessor`]. See [`BlipProcessor.__call__`] for details.
575
+
576
+ [What are input IDs?](../glossary#input-ids)
577
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
578
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
579
+
580
+ - 1 for tokens that are **not masked**,
581
+ - 0 for tokens that are **masked**.
582
+
583
+ [What are attention masks?](../glossary#attention-mask)
584
+ position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
585
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
586
+ config.max_position_embeddings - 1]`.
587
+
588
+ [What are position IDs?](../glossary#position-ids)
589
+ pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
590
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
591
+ [`BlipImageProcessor`]. See [`BlipImageProcessor.__call__`] for details.
592
+ return_loss (`bool`, *optional*):
593
+ Whether or not to return the contrastive loss.
594
+ output_attentions (`bool`, *optional*):
595
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
596
+ tensors for more detail.
597
+ output_hidden_states (`bool`, *optional*):
598
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
599
+ more detail.
600
+ return_dict (`bool`, *optional*):
601
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
602
+ """
603
+
604
+
605
+ @keras_serializable
606
+ class TFBlipEncoder(keras.layers.Layer):
607
+ config_class = BlipConfig
608
+ """
609
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
610
+ [`BlipEncoderLayer`].
611
+
612
+ Args:
613
+ config (`BlipConfig`):
614
+ The corresponding vision configuration for the `BlipEncoder`.
615
+ """
616
+
617
+ def __init__(self, config: BlipConfig, **kwargs):
618
+ super().__init__(**kwargs)
619
+ self.config = config
620
+ self.layers = [TFBlipEncoderLayer(config, name=f"layers_._{i}") for i in range(config.num_hidden_layers)]
621
+
622
+ @unpack_inputs
623
+ def call(
624
+ self,
625
+ inputs_embeds,
626
+ attention_mask: tf.Tensor | None = None,
627
+ output_attentions: Optional[bool] = None,
628
+ output_hidden_states: Optional[bool] = None,
629
+ return_dict: Optional[bool] = None,
630
+ training: Optional[bool] = None,
631
+ ) -> Union[Tuple, TFBaseModelOutput]:
632
+ r"""
633
+ Args:
634
+ inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
635
+ Embedded representation of the inputs. Should be float, not int tokens.
636
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
637
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
638
+
639
+ - 1 for tokens that are **not masked**,
640
+ - 0 for tokens that are **masked**.
641
+
642
+ [What are attention masks?](../glossary#attention-mask)
643
+ output_attentions (`bool`, *optional*):
644
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
645
+ returned tensors for more detail.
646
+ output_hidden_states (`bool`, *optional*):
647
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
648
+ for more detail.
649
+ return_dict (`bool`, *optional*):
650
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
651
+ """
652
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
653
+ output_hidden_states = (
654
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
655
+ )
656
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
657
+
658
+ encoder_states = () if output_hidden_states else None
659
+ all_attentions = () if output_attentions else None
660
+
661
+ hidden_states = inputs_embeds
662
+ for idx, encoder_layer in enumerate(self.layers):
663
+ if output_hidden_states:
664
+ encoder_states = encoder_states + (hidden_states,)
665
+ layer_outputs = encoder_layer(
666
+ hidden_states,
667
+ attention_mask,
668
+ output_attentions=output_attentions,
669
+ training=training,
670
+ )
671
+
672
+ hidden_states = layer_outputs[0]
673
+
674
+ if output_attentions:
675
+ all_attentions = all_attentions + (layer_outputs[1],)
676
+
677
+ if output_hidden_states:
678
+ encoder_states = encoder_states + (hidden_states,)
679
+
680
+ if not return_dict:
681
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
682
+ return TFBaseModelOutput(
683
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
684
+ )
685
+
686
+ def build(self, input_shape=None):
687
+ if self.built:
688
+ return
689
+ self.built = True
690
+ if getattr(self, "layers", None) is not None:
691
+ for layer in self.layers:
692
+ with tf.name_scope(layer.name):
693
+ layer.build(None)
694
+
695
+
696
+ class TFBlipVisionModel(TFBlipPreTrainedModel):
697
+ main_input_name = "pixel_values"
698
+ config_class = BlipVisionConfig
699
+
700
+ def __init__(self, config: BlipVisionConfig, *args, **kwargs):
701
+ super().__init__(config, *args, **kwargs)
702
+ self.config = config
703
+
704
+ self.embeddings = TFBlipVisionEmbeddings(config, name="embeddings")
705
+ self.encoder = TFBlipEncoder(config, name="encoder")
706
+ self.post_layernorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="post_layernorm")
707
+ self.embed_dim = config.hidden_size
708
+
709
+ def serving_output(self, output: TFBaseModelOutputWithPooling) -> TFBaseModelOutputWithPooling:
710
+ hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
711
+ attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
712
+
713
+ return TFBaseModelOutputWithPooling(
714
+ last_hidden_state=output.last_hidden_state,
715
+ pooler_output=output.pooler_output,
716
+ hidden_states=hs,
717
+ attentions=attns,
718
+ )
719
+
720
+ @unpack_inputs
721
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
722
+ @replace_return_docstrings(output_type=TFBaseModelOutputWithPooling, config_class=BlipVisionConfig)
723
+ def call(
724
+ self,
725
+ pixel_values: tf.Tensor | None = None,
726
+ output_attentions: Optional[bool] = None,
727
+ output_hidden_states: Optional[bool] = None,
728
+ return_dict: Optional[bool] = None,
729
+ training: Optional[bool] = None,
730
+ ) -> Union[Tuple, TFBaseModelOutputWithPooling]:
731
+ r"""
732
+ Returns:
733
+
734
+ """
735
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
736
+ output_hidden_states = (
737
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
738
+ )
739
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
740
+
741
+ if pixel_values is None:
742
+ raise ValueError("You have to specify pixel_values")
743
+
744
+ hidden_states = self.embeddings(pixel_values)
745
+
746
+ encoder_outputs = self.encoder(
747
+ inputs_embeds=hidden_states,
748
+ output_attentions=output_attentions,
749
+ output_hidden_states=output_hidden_states,
750
+ return_dict=return_dict,
751
+ training=training,
752
+ )
753
+
754
+ last_hidden_state = encoder_outputs[0]
755
+ last_hidden_state = self.post_layernorm(last_hidden_state)
756
+
757
+ pooled_output = last_hidden_state[:, 0, :]
758
+ # TF gets confused if we call the layer with inputs of different ranks, so insert a singleton dimension
759
+ pooled_output = self.post_layernorm(tf.expand_dims(pooled_output, 1))
760
+ pooled_output = tf.squeeze(pooled_output, 1)
761
+
762
+ if not return_dict:
763
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
764
+
765
+ return TFBaseModelOutputWithPooling(
766
+ last_hidden_state=last_hidden_state,
767
+ pooler_output=pooled_output,
768
+ hidden_states=encoder_outputs.hidden_states,
769
+ attentions=encoder_outputs.attentions,
770
+ )
771
+
772
+ def get_input_embeddings(self):
773
+ return self.embeddings
774
+
775
+ def build(self, input_shape=None):
776
+ if self.built:
777
+ return
778
+ self.built = True
779
+ if getattr(self, "embeddings", None) is not None:
780
+ with tf.name_scope(self.embeddings.name):
781
+ self.embeddings.build(None)
782
+ if getattr(self, "encoder", None) is not None:
783
+ with tf.name_scope(self.encoder.name):
784
+ self.encoder.build(None)
785
+ if getattr(self, "post_layernorm", None) is not None:
786
+ with tf.name_scope(self.post_layernorm.name):
787
+ self.post_layernorm.build([None, None, self.embed_dim])
788
+
789
+
790
+ class TFBlipMainLayer(keras.layers.Layer):
791
+ config_class = BlipConfig
792
+
793
+ def __init__(self, config: BlipConfig, *args, **kwargs):
794
+ super().__init__(*args, **kwargs)
795
+
796
+ if not isinstance(config.text_config, BlipTextConfig):
797
+ raise TypeError(
798
+ "config.text_config is expected to be of type BlipTextConfig but is of type"
799
+ f" {type(config.text_config)}."
800
+ )
801
+
802
+ if not isinstance(config.vision_config, BlipVisionConfig):
803
+ raise TypeError(
804
+ "config.vision_config is expected to be of type BlipVisionConfig but is of type"
805
+ f" {type(config.vision_config)}."
806
+ )
807
+
808
+ text_config = config.text_config
809
+ vision_config = config.vision_config
810
+
811
+ self.projection_dim = config.projection_dim
812
+ self.text_embed_dim = text_config.hidden_size
813
+ self.vision_embed_dim = vision_config.hidden_size
814
+
815
+ self.text_model = TFBlipTextModel(text_config, name="text_model")
816
+ self.vision_model = TFBlipVisionModel(vision_config, name="vision_model")
817
+
818
+ self.visual_projection = keras.layers.Dense(
819
+ self.projection_dim,
820
+ use_bias=False,
821
+ kernel_initializer=get_initializer(config.initializer_range),
822
+ name="visual_projection",
823
+ )
824
+ self.text_projection = keras.layers.Dense(
825
+ self.projection_dim,
826
+ use_bias=False,
827
+ kernel_initializer=get_initializer(config.initializer_range),
828
+ name="text_projection",
829
+ )
830
+
831
+ self.config = config
832
+
833
+ def build(self, input_shape=None):
834
+ self.logit_scale = self.add_weight(
835
+ name="logit_scale",
836
+ shape=[],
837
+ initializer=keras.initializers.Constant(self.config.logit_scale_init_value),
838
+ trainable=True,
839
+ )
840
+
841
+ if self.built:
842
+ return
843
+ self.built = True
844
+ if getattr(self, "text_model", None) is not None:
845
+ with tf.name_scope(self.text_model.name):
846
+ self.text_model.build(None)
847
+ if getattr(self, "vision_model", None) is not None:
848
+ with tf.name_scope(self.vision_model.name):
849
+ self.vision_model.build(None)
850
+ if getattr(self, "visual_projection", None) is not None:
851
+ with tf.name_scope(self.visual_projection.name):
852
+ self.visual_projection.build([None, None, self.vision_embed_dim])
853
+ if getattr(self, "text_projection", None) is not None:
854
+ with tf.name_scope(self.text_projection.name):
855
+ self.text_projection.build([None, None, self.text_embed_dim])
856
+
857
+ @unpack_inputs
858
+ def call(
859
+ self,
860
+ input_ids: tf.Tensor | None = None,
861
+ pixel_values: tf.Tensor | None = None,
862
+ attention_mask: tf.Tensor | None = None,
863
+ position_ids: tf.Tensor | None = None,
864
+ return_loss: Optional[bool] = None,
865
+ output_attentions: Optional[bool] = None,
866
+ output_hidden_states: Optional[bool] = None,
867
+ return_dict: Optional[bool] = None,
868
+ training: Optional[bool] = None,
869
+ ) -> Union[Tuple, TFBlipOutput]:
870
+ # Use BLIP model's config for some fields (if specified) instead of those of vision & text components.
871
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
872
+ output_hidden_states = (
873
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
874
+ )
875
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
876
+
877
+ vision_outputs = self.vision_model(
878
+ pixel_values=pixel_values,
879
+ output_attentions=output_attentions,
880
+ output_hidden_states=output_hidden_states,
881
+ return_dict=return_dict,
882
+ training=training,
883
+ )
884
+
885
+ text_outputs = self.text_model(
886
+ input_ids=input_ids,
887
+ attention_mask=attention_mask,
888
+ position_ids=position_ids,
889
+ output_attentions=output_attentions,
890
+ output_hidden_states=output_hidden_states,
891
+ return_dict=return_dict,
892
+ training=training,
893
+ )
894
+
895
+ image_embeds = vision_outputs[1]
896
+ image_embeds = self.visual_projection(image_embeds)
897
+
898
+ text_embeds = text_outputs[1]
899
+ text_embeds = self.text_projection(text_embeds)
900
+
901
+ # normalized features
902
+ image_embeds = image_embeds / tf.norm(image_embeds, ord=2, axis=-1, keepdims=True)
903
+ text_embeds = text_embeds / tf.norm(text_embeds, ord=2, axis=-1, keepdims=True)
904
+
905
+ # cosine similarity as logits
906
+ logit_scale = tf.exp(self.logit_scale)
907
+ logits_per_text = tf.matmul(text_embeds, image_embeds, transpose_b=True) * logit_scale
908
+ logits_per_image = tf.transpose(logits_per_text)
909
+
910
+ loss = None
911
+ if return_loss:
912
+ loss = blip_loss(logits_per_text)
913
+ loss = tf.reshape(loss, (1,))
914
+
915
+ if not return_dict:
916
+ output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
917
+ return ((loss,) + output) if loss is not None else output
918
+
919
+ return TFBlipOutput(
920
+ loss=loss,
921
+ logits_per_image=logits_per_image,
922
+ logits_per_text=logits_per_text,
923
+ text_embeds=text_embeds,
924
+ image_embeds=image_embeds,
925
+ text_model_output=text_outputs,
926
+ vision_model_output=vision_outputs,
927
+ )
928
+
929
+
930
+ class TFBlipModel(TFBlipPreTrainedModel):
931
+ config_class = BlipConfig
932
+ _keys_to_ignore_on_load_missing = [r"text_decoder.cls.predictions.decoder.bias"]
933
+ main_input_name = "input_ids"
934
+
935
+ def __init__(self, config: BlipConfig, *inputs, **kwargs):
936
+ super().__init__(config, *inputs, **kwargs)
937
+
938
+ self.blip = TFBlipMainLayer(config, name="blip")
939
+
940
+ def serving_output(self, output: TFBlipOutput) -> TFBlipOutput:
941
+ return TFBlipOutput(
942
+ logits_per_image=output.logits_per_image,
943
+ logits_per_text=output.logits_per_text,
944
+ text_embeds=output.text_embeds,
945
+ image_embeds=output.image_embeds,
946
+ )
947
+
948
+ @unpack_inputs
949
+ @add_start_docstrings_to_model_forward(BLIP_INPUTS_DOCSTRING)
950
+ @replace_return_docstrings(output_type=TFBlipOutput, config_class=BlipConfig)
951
+ def call(
952
+ self,
953
+ input_ids: tf.Tensor | None = None,
954
+ pixel_values: tf.Tensor | None = None,
955
+ attention_mask: tf.Tensor | None = None,
956
+ position_ids: tf.Tensor | None = None,
957
+ return_loss: Optional[bool] = None,
958
+ output_attentions: Optional[bool] = None,
959
+ output_hidden_states: Optional[bool] = None,
960
+ return_dict: Optional[bool] = None,
961
+ training: Optional[bool] = None,
962
+ ) -> Union[Tuple, TFBlipOutput]:
963
+ r"""
964
+ Returns:
965
+
966
+ Examples:
967
+
968
+ ```python
969
+ >>> from PIL import Image
970
+ >>> import requests
971
+ >>> from transformers import AutoProcessor, TFBlipModel
972
+
973
+ >>> model = TFBlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
974
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
975
+
976
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
977
+ >>> image = Image.open(requests.get(url, stream=True).raw)
978
+
979
+ >>> inputs = processor(
980
+ ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="tf", padding=True
981
+ ... )
982
+
983
+ >>> outputs = model(**inputs)
984
+ >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
985
+ >>> probs = tf.nn.softmax(logits_per_image, axis=1) # we can take the softmax to get the label probabilities
986
+ ```"""
987
+ outputs = self.blip(
988
+ input_ids=input_ids,
989
+ pixel_values=pixel_values,
990
+ attention_mask=attention_mask,
991
+ position_ids=position_ids,
992
+ return_loss=return_loss,
993
+ output_attentions=output_attentions,
994
+ output_hidden_states=output_hidden_states,
995
+ return_dict=return_dict,
996
+ training=training,
997
+ )
998
+ return outputs
999
+
1000
+ @add_start_docstrings_to_model_forward(BLIP_TEXT_INPUTS_DOCSTRING)
1001
+ def get_text_features(
1002
+ self,
1003
+ input_ids: tf.Tensor | None = None,
1004
+ attention_mask: tf.Tensor | None = None,
1005
+ position_ids: tf.Tensor | None = None,
1006
+ return_dict: Optional[bool] = None,
1007
+ ) -> tf.Tensor:
1008
+ r"""
1009
+ Returns:
1010
+ text_features (`tf.Tensor` of shape `(batch_size, output_dim`): The text embeddings obtained by applying
1011
+ the projection layer to the pooled output of [`TFBlipTextModel`].
1012
+
1013
+ Examples:
1014
+
1015
+ ```python
1016
+ >>> from transformers import AutoProcessor, TFBlipModel
1017
+
1018
+ >>> model = TFBlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
1019
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
1020
+
1021
+ >>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="tf")
1022
+ >>> text_features = model.get_text_features(**inputs)
1023
+ ```"""
1024
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1025
+
1026
+ text_outputs = self.blip.text_model(
1027
+ input_ids=input_ids,
1028
+ attention_mask=attention_mask,
1029
+ position_ids=position_ids,
1030
+ return_dict=return_dict,
1031
+ )
1032
+
1033
+ pooled_output = text_outputs[1]
1034
+ text_features = self.blip.text_projection(pooled_output)
1035
+
1036
+ return text_features
1037
+
1038
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
1039
+ def get_image_features(
1040
+ self,
1041
+ pixel_values: tf.Tensor | None = None,
1042
+ return_dict: Optional[bool] = None,
1043
+ ) -> tf.Tensor:
1044
+ r"""
1045
+ Returns:
1046
+ image_features (`tf.Tensor` of shape `(batch_size, output_dim`): The image embeddings obtained by applying
1047
+ the projection layer to the pooled output of [`TFBlipVisionModel`].
1048
+
1049
+ Examples:
1050
+
1051
+ ```python
1052
+ >>> from PIL import Image
1053
+ >>> import requests
1054
+ >>> from transformers import AutoProcessor, TFBlipModel
1055
+
1056
+ >>> model = TFBlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
1057
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
1058
+
1059
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1060
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1061
+
1062
+ >>> inputs = processor(images=image, return_tensors="tf")
1063
+
1064
+ >>> image_features = model.get_image_features(**inputs)
1065
+ ```"""
1066
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1067
+
1068
+ vision_outputs = self.blip.vision_model(pixel_values=pixel_values, return_dict=return_dict)
1069
+
1070
+ pooled_output = vision_outputs[1] # pooled_output
1071
+ image_features = self.blip.visual_projection(pooled_output)
1072
+
1073
+ return image_features
1074
+
1075
+ def build(self, input_shape=None):
1076
+ if self.built:
1077
+ return
1078
+ self.built = True
1079
+ if getattr(self, "blip", None) is not None:
1080
+ with tf.name_scope(self.blip.name):
1081
+ self.blip.build(None)
1082
+
1083
+
1084
+ @add_start_docstrings(
1085
+ """
1086
+ BLIP Model for image captioning. The model consists of a vision encoder and a text decoder. One can optionally pass
1087
+ `input_ids` to the model, which serve as a text prompt, to make the text decoder continue the prompt. Otherwise,
1088
+ the decoder starts generating text from the [BOS] (beginning-of-sequence) token. will start generating the caption
1089
+ from the text input. If no text input is provided, the decoder will start with the [BOS] token only.
1090
+ """,
1091
+ BLIP_START_DOCSTRING,
1092
+ )
1093
+ class TFBlipForConditionalGeneration(TFBlipPreTrainedModel):
1094
+ config_class = BlipConfig
1095
+ _keys_to_ignore_on_load_missing = [r"text_decoder.cls.predictions.decoder.bias"]
1096
+ main_input_name = "pixel_values"
1097
+
1098
+ def __init__(self, config: BlipConfig, *args, **kwargs):
1099
+ super().__init__(config, *args, **kwargs)
1100
+
1101
+ self.vision_model = TFBlipVisionModel(config.vision_config, name="vision_model")
1102
+
1103
+ self.text_decoder = TFBlipTextLMHeadModel(config.text_config, name="text_decoder")
1104
+
1105
+ self.decoder_input_ids = config.text_config.bos_token_id
1106
+ self.decoder_pad_token_id = config.text_config.pad_token_id
1107
+
1108
+ def get_input_embeddings(self) -> keras.layers.Layer:
1109
+ return self.vision_model.embeddings.patch_embedding
1110
+
1111
+ @unpack_inputs
1112
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
1113
+ @replace_return_docstrings(output_type=TFBlipForConditionalGenerationModelOutput, config_class=BlipConfig)
1114
+ def call(
1115
+ self,
1116
+ pixel_values: tf.Tensor,
1117
+ input_ids: tf.Tensor | None = None,
1118
+ attention_mask: tf.Tensor | None = None,
1119
+ output_attentions: Optional[bool] = None,
1120
+ output_hidden_states: Optional[bool] = None,
1121
+ labels: tf.Tensor | None = None,
1122
+ return_dict: Optional[bool] = None,
1123
+ training: Optional[bool] = None,
1124
+ ) -> Union[Tuple, TFBlipForConditionalGenerationModelOutput]:
1125
+ r"""
1126
+ Returns:
1127
+
1128
+ Examples:
1129
+
1130
+ ```python
1131
+ >>> from PIL import Image
1132
+ >>> import requests
1133
+ >>> from transformers import AutoProcessor, TFBlipForConditionalGeneration
1134
+
1135
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
1136
+ >>> model = TFBlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
1137
+
1138
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1139
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1140
+ >>> text = "A picture of"
1141
+
1142
+ >>> inputs = processor(images=image, text=text, return_tensors="tf")
1143
+
1144
+ >>> outputs = model(**inputs)
1145
+ ```"""
1146
+
1147
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1148
+ vision_outputs = self.vision_model(
1149
+ pixel_values=pixel_values,
1150
+ output_attentions=output_attentions,
1151
+ output_hidden_states=output_hidden_states,
1152
+ return_dict=return_dict,
1153
+ training=training,
1154
+ )
1155
+
1156
+ image_embeds = vision_outputs[0]
1157
+
1158
+ outputs = self.text_decoder(
1159
+ input_ids=input_ids,
1160
+ attention_mask=attention_mask,
1161
+ encoder_hidden_states=image_embeds,
1162
+ labels=labels,
1163
+ return_dict=False,
1164
+ training=training,
1165
+ )
1166
+
1167
+ if not return_dict:
1168
+ outputs = (outputs[0], outputs[1], image_embeds, vision_outputs[0]) + vision_outputs[2:]
1169
+ return tuple(output for output in outputs if output is not None)
1170
+
1171
+ if labels is not None:
1172
+ loss = outputs[0]
1173
+ logits = outputs[1]
1174
+ else:
1175
+ loss = None
1176
+ logits = outputs[0]
1177
+
1178
+ if loss is not None and loss.shape.rank == 0:
1179
+ loss = tf.reshape(loss, (1,))
1180
+
1181
+ return TFBlipForConditionalGenerationModelOutput(
1182
+ loss=loss,
1183
+ logits=logits,
1184
+ image_embeds=image_embeds,
1185
+ last_hidden_state=vision_outputs.last_hidden_state,
1186
+ hidden_states=vision_outputs.hidden_states,
1187
+ attentions=vision_outputs.attentions,
1188
+ )
1189
+
1190
+ def generate(
1191
+ self,
1192
+ pixel_values: tf.Tensor,
1193
+ input_ids: tf.Tensor | None = None,
1194
+ attention_mask: tf.Tensor | None = None,
1195
+ **generate_kwargs,
1196
+ ) -> tf.Tensor:
1197
+ r"""
1198
+ Overrides *generate* function to be able to use the model as a conditional generator
1199
+
1200
+ Parameters:
1201
+ pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, image_height, image_width)`:
1202
+ Input image to be processed
1203
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1204
+ The sequence used as a prompt for the generation.
1205
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1206
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1207
+
1208
+
1209
+ Examples:
1210
+ ```python
1211
+ >>> from PIL import Image
1212
+ >>> import requests
1213
+ >>> from transformers import AutoProcessor, TFBlipForConditionalGeneration
1214
+
1215
+ >>> model = TFBlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
1216
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
1217
+
1218
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1219
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1220
+
1221
+ >>> inputs = processor(images=image, return_tensors="tf")
1222
+
1223
+ >>> outputs = model.generate(**inputs)
1224
+ >>> print(processor.decode(outputs[0], skip_special_tokens=True))
1225
+ two cats sleeping on a couch
1226
+ ```
1227
+ """
1228
+
1229
+ batch_size = pixel_values.shape[0]
1230
+ vision_outputs = self.vision_model(pixel_values=pixel_values)
1231
+
1232
+ image_embeds = vision_outputs[0]
1233
+
1234
+ image_attention_mask = tf.ones(shape_list(image_embeds)[:-1], dtype=tf.int32)
1235
+
1236
+ if isinstance(input_ids, list):
1237
+ input_ids = tf.convert_to_tensor(input_ids, dtype=tf.int32)
1238
+ elif input_ids is None:
1239
+ input_ids = tf.convert_to_tensor(
1240
+ [[self.decoder_input_ids, self.config.text_config.eos_token_id]], dtype=tf.int32
1241
+ )
1242
+
1243
+ input_ids = tf.tile(input_ids, (batch_size, 1))
1244
+
1245
+ # PyTorch: input_ids[:, 0] = self.config.text_config.bos_token_id
1246
+ input_ids = tf.concat(
1247
+ [tf.ones((batch_size, 1), dtype=tf.int32) * self.config.text_config.bos_token_id, input_ids[:, 1:]], axis=1
1248
+ )
1249
+ attention_mask = attention_mask[:, :-1] if attention_mask is not None else None
1250
+
1251
+ outputs = self.text_decoder.generate(
1252
+ input_ids=input_ids[:, :-1],
1253
+ eos_token_id=self.config.text_config.sep_token_id,
1254
+ pad_token_id=self.config.text_config.pad_token_id,
1255
+ attention_mask=attention_mask,
1256
+ encoder_hidden_states=image_embeds,
1257
+ encoder_attention_mask=image_attention_mask,
1258
+ **generate_kwargs,
1259
+ )
1260
+
1261
+ return outputs
1262
+
1263
+ def build(self, input_shape=None):
1264
+ if self.built:
1265
+ return
1266
+ self.built = True
1267
+ if getattr(self, "vision_model", None) is not None:
1268
+ with tf.name_scope(self.vision_model.name):
1269
+ self.vision_model.build(None)
1270
+ if getattr(self, "text_decoder", None) is not None:
1271
+ with tf.name_scope(self.text_decoder.name):
1272
+ self.text_decoder.build(None)
1273
+
1274
+
1275
+ @add_start_docstrings(
1276
+ """
1277
+ BLIP Model for visual question answering. The model consists of a vision encoder, a text encoder as well as a text
1278
+ decoder. The vision encoder will encode the input image, the text encoder will encode the input question together
1279
+ with the encoding of the image, and the text decoder will output the answer to the question.
1280
+ """,
1281
+ BLIP_START_DOCSTRING,
1282
+ )
1283
+ class TFBlipForQuestionAnswering(TFBlipPreTrainedModel):
1284
+ config_class = BlipConfig
1285
+ _keys_to_ignore_on_load_missing = [r"text_decoder.cls.predictions.decoder.bias"]
1286
+
1287
+ def __init__(self, config: BlipConfig, *args, **kwargs):
1288
+ super().__init__(config, *args, **kwargs)
1289
+
1290
+ self.vision_model = TFBlipVisionModel(config.vision_config, name="vision_model")
1291
+
1292
+ self.text_encoder = TFBlipTextModel(config.text_config, name="text_encoder", add_pooling_layer=False)
1293
+
1294
+ self.text_decoder = TFBlipTextLMHeadModel(config.text_config, name="text_decoder")
1295
+
1296
+ self.decoder_pad_token_id = config.text_config.pad_token_id
1297
+ self.decoder_start_token_id = config.text_config.bos_token_id
1298
+
1299
+ def get_input_embeddings(self) -> keras.layers.Layer:
1300
+ return self.vision_model.embeddings.patch_embedding
1301
+
1302
+ # Adapted from transformers.models.t5.modeling_tf_t5.TFT5PreTrainedModel._shift_right
1303
+ def _shift_right(self, input_ids):
1304
+ decoder_start_token_id = self.decoder_start_token_id
1305
+ pad_token_id = self.decoder_pad_token_id
1306
+
1307
+ if decoder_start_token_id is None or pad_token_id is None:
1308
+ raise ValueError("decoder_start_token_id and pad_token_id must be defined!")
1309
+
1310
+ start_tokens = tf.fill((shape_list(input_ids)[0], 1), decoder_start_token_id)
1311
+ start_tokens = tf.cast(start_tokens, input_ids.dtype) # Ensure compatible dtypes for concatenation
1312
+ shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1)
1313
+
1314
+ # replace possible -100 values in labels by `pad_token_id`
1315
+ shifted_input_ids = tf.where(
1316
+ shifted_input_ids == -100,
1317
+ tf.cast(tf.fill(shape_list(shifted_input_ids), pad_token_id), shifted_input_ids.dtype),
1318
+ shifted_input_ids,
1319
+ )
1320
+
1321
+ # "Verify that `labels` has only positive values and -100"
1322
+ tf.debugging.assert_greater_equal(shifted_input_ids, tf.constant(0, dtype=shifted_input_ids.dtype))
1323
+
1324
+ return shifted_input_ids
1325
+
1326
+ @unpack_inputs
1327
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
1328
+ @replace_return_docstrings(output_type=TFBlipTextVisionModelOutput, config_class=BlipVisionConfig)
1329
+ def call(
1330
+ self,
1331
+ input_ids: tf.Tensor,
1332
+ pixel_values: tf.Tensor | None = None,
1333
+ decoder_input_ids: tf.Tensor | None = None,
1334
+ decoder_attention_mask: tf.Tensor | None = None,
1335
+ attention_mask: tf.Tensor | None = None,
1336
+ output_attentions: Optional[bool] = None,
1337
+ output_hidden_states: Optional[bool] = None,
1338
+ labels: tf.Tensor | None = None,
1339
+ return_dict: Optional[bool] = None,
1340
+ training: Optional[bool] = None,
1341
+ ) -> Union[Tuple, TFBlipTextVisionModelOutput]:
1342
+ r"""
1343
+ Returns:
1344
+
1345
+ Examples:
1346
+
1347
+ ```python
1348
+ >>> from PIL import Image
1349
+ >>> import requests
1350
+ >>> from transformers import AutoProcessor, TFBlipForQuestionAnswering
1351
+
1352
+ >>> model = TFBlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
1353
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")
1354
+
1355
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1356
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1357
+
1358
+ >>> # training
1359
+ >>> text = "How many cats are in the picture?"
1360
+ >>> label = "2"
1361
+ >>> inputs = processor(images=image, text=text, return_tensors="tf")
1362
+ >>> labels = processor(text=label, return_tensors="tf").input_ids
1363
+
1364
+ >>> inputs["labels"] = labels
1365
+ >>> outputs = model(**inputs)
1366
+ >>> loss = outputs.loss
1367
+
1368
+ >>> # inference
1369
+ >>> text = "How many cats are in the picture?"
1370
+ >>> inputs = processor(images=image, text=text, return_tensors="tf")
1371
+ >>> outputs = model.generate(**inputs)
1372
+ >>> print(processor.decode(outputs[0], skip_special_tokens=True))
1373
+ 2
1374
+ ```"""
1375
+ if labels is None and decoder_input_ids is None:
1376
+ raise ValueError(
1377
+ "Either `decoder_input_ids` or `labels` should be passed when calling"
1378
+ " `TFBlipForQuestionAnswering`. if you are training the model make sure that `labels` is passed, if you"
1379
+ " are using the model for inference make sure that `decoder_input_ids` is passed or call `generate`"
1380
+ )
1381
+
1382
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1383
+
1384
+ vision_outputs = self.vision_model(
1385
+ pixel_values=pixel_values,
1386
+ output_attentions=output_attentions,
1387
+ output_hidden_states=output_hidden_states,
1388
+ return_dict=return_dict,
1389
+ training=training,
1390
+ )
1391
+
1392
+ image_embeds = vision_outputs[0]
1393
+ image_attention_mask = tf.ones(shape_list(image_embeds)[:-1], dtype=tf.int64)
1394
+
1395
+ question_embeds = self.text_encoder(
1396
+ input_ids=input_ids,
1397
+ attention_mask=attention_mask,
1398
+ encoder_hidden_states=image_embeds,
1399
+ encoder_attention_mask=image_attention_mask,
1400
+ return_dict=return_dict,
1401
+ training=training,
1402
+ )
1403
+
1404
+ question_embeds = question_embeds[0] if not return_dict else question_embeds.last_hidden_state
1405
+
1406
+ if labels is not None and decoder_input_ids is None:
1407
+ # labels are already shifted right, see: https://github.com/huggingface/transformers/pull/23153
1408
+ decoder_input_ids = labels
1409
+
1410
+ answer_output = self.text_decoder(
1411
+ input_ids=decoder_input_ids,
1412
+ attention_mask=decoder_attention_mask,
1413
+ encoder_hidden_states=question_embeds,
1414
+ encoder_attention_mask=attention_mask,
1415
+ labels=labels,
1416
+ return_dict=return_dict,
1417
+ training=training,
1418
+ )
1419
+
1420
+ if labels is not None:
1421
+ decoder_loss = tf.reduce_mean(answer_output.loss) if return_dict else tf.reduce_mean(answer_output[0])
1422
+ else:
1423
+ decoder_loss = None
1424
+
1425
+ if not return_dict:
1426
+ outputs = (decoder_loss, image_embeds, vision_outputs[0]) + vision_outputs[2:]
1427
+ return tuple(output for output in outputs if output is not None)
1428
+
1429
+ return TFBlipTextVisionModelOutput(
1430
+ loss=decoder_loss,
1431
+ image_embeds=image_embeds,
1432
+ last_hidden_state=vision_outputs.last_hidden_state,
1433
+ hidden_states=vision_outputs.hidden_states,
1434
+ attentions=vision_outputs.attentions,
1435
+ )
1436
+
1437
+ def generate(
1438
+ self,
1439
+ input_ids: tf.Tensor,
1440
+ pixel_values: tf.Tensor,
1441
+ attention_mask: tf.Tensor | None = None,
1442
+ **generate_kwargs,
1443
+ ) -> tf.Tensor:
1444
+ r"""
1445
+ Overrides *generate* function to be able to use the model as a conditional generator
1446
+
1447
+ Parameters:
1448
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
1449
+ The sequence used as a prompt for the generation.
1450
+ pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, image_height, image_width)`:
1451
+ Input image to be processed
1452
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1453
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`. `1` for
1454
+ tokens that are NOT MASKED, `0` for MASKED tokens.
1455
+ generate_kwargs (dict, *optional*):
1456
+ Additional arguments passed to the `generate` function of the decoder
1457
+
1458
+
1459
+ Examples:
1460
+ ```python
1461
+ >>> from PIL import Image
1462
+ >>> import requests
1463
+ >>> from transformers import AutoProcessor, TFBlipForQuestionAnswering
1464
+
1465
+ >>> model = TFBlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
1466
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")
1467
+
1468
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1469
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1470
+ >>> text = "How many cats are in the picture?"
1471
+
1472
+ >>> inputs = processor(images=image, text=text, return_tensors="tf")
1473
+
1474
+ >>> outputs = model.generate(**inputs)
1475
+ >>> print(processor.decode(outputs[0], skip_special_tokens=True))
1476
+ 2
1477
+ ```
1478
+ """
1479
+ vision_outputs = self.vision_model(pixel_values=pixel_values)
1480
+
1481
+ image_embeds = vision_outputs[0]
1482
+
1483
+ image_attention_mask = tf.ones(shape_list(image_embeds)[:-1], dtype=tf.int32)
1484
+
1485
+ if isinstance(input_ids, list):
1486
+ input_ids = tf.Tensor(input_ids)
1487
+
1488
+ question_outputs = self.text_encoder(
1489
+ input_ids=input_ids,
1490
+ attention_mask=attention_mask,
1491
+ encoder_hidden_states=image_embeds,
1492
+ encoder_attention_mask=image_attention_mask,
1493
+ return_dict=False,
1494
+ )
1495
+
1496
+ question_embeds = question_outputs[0]
1497
+
1498
+ question_attention_mask = tf.ones(shape_list(question_embeds)[:-1], dtype=tf.int32)
1499
+
1500
+ bos_ids = tf.fill(
1501
+ (tf.shape(question_embeds)[0], 1), value=tf.cast(self.decoder_start_token_id, input_ids.dtype)
1502
+ )
1503
+
1504
+ outputs = self.text_decoder.generate(
1505
+ input_ids=bos_ids,
1506
+ eos_token_id=self.config.text_config.sep_token_id,
1507
+ pad_token_id=self.config.text_config.pad_token_id,
1508
+ encoder_hidden_states=question_embeds,
1509
+ encoder_attention_mask=question_attention_mask,
1510
+ **generate_kwargs,
1511
+ )
1512
+
1513
+ return outputs
1514
+
1515
+ def build(self, input_shape=None):
1516
+ if self.built:
1517
+ return
1518
+ self.built = True
1519
+ if getattr(self, "vision_model", None) is not None:
1520
+ with tf.name_scope(self.vision_model.name):
1521
+ self.vision_model.build(None)
1522
+ if getattr(self, "text_encoder", None) is not None:
1523
+ with tf.name_scope(self.text_encoder.name):
1524
+ self.text_encoder.build(None)
1525
+ if getattr(self, "text_decoder", None) is not None:
1526
+ with tf.name_scope(self.text_decoder.name):
1527
+ self.text_decoder.build(None)
1528
+
1529
+
1530
+ @add_start_docstrings(
1531
+ """
1532
+ BLIP Model with a vision and text projector, and a classification head on top. The model is used in the context of
1533
+ image-text retrieval. Given an image and a text, the model returns the probability of the text being relevant to
1534
+ the image.
1535
+ """,
1536
+ BLIP_START_DOCSTRING,
1537
+ )
1538
+ class TFBlipForImageTextRetrieval(TFBlipPreTrainedModel):
1539
+ config_class = BlipConfig
1540
+
1541
+ def __init__(self, config: BlipConfig, *args, **kwargs):
1542
+ super().__init__(config, *args, **kwargs)
1543
+
1544
+ self.vision_model = TFBlipVisionModel(config.vision_config, name="vision_model")
1545
+
1546
+ self.text_encoder = TFBlipTextModel(config.text_config, name="text_encoder", add_pooling_layer=False)
1547
+
1548
+ # vision projection layer
1549
+ self.vision_proj = keras.layers.Dense(
1550
+ config.image_text_hidden_size,
1551
+ kernel_initializer=get_initializer(config.initializer_range),
1552
+ name="vision_proj",
1553
+ )
1554
+
1555
+ # text projection layer
1556
+ self.text_proj = keras.layers.Dense(
1557
+ config.image_text_hidden_size,
1558
+ kernel_initializer=get_initializer(config.initializer_range),
1559
+ name="text_proj",
1560
+ )
1561
+
1562
+ # image text matching head
1563
+ self.itm_head = keras.layers.Dense(
1564
+ 2, kernel_initializer=get_initializer(config.initializer_range), name="itm_head"
1565
+ )
1566
+
1567
+ self.decoder_pad_token_id = (
1568
+ config.text_config.pad_token_id
1569
+ if not hasattr(config, "decoder_pad_token_id")
1570
+ else config.decoder_pad_token_id
1571
+ )
1572
+ self.decoder_start_token_id = (
1573
+ config.text_config.bos_token_id
1574
+ if not hasattr(config, "decoder_start_token_id")
1575
+ else config.decoder_start_token_id
1576
+ )
1577
+ self.config = config
1578
+
1579
+ def get_input_embeddings(self) -> keras.layers.Layer:
1580
+ return self.vision_model.embeddings.patch_embedding
1581
+
1582
+ @unpack_inputs
1583
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
1584
+ @replace_return_docstrings(output_type=TFBlipImageTextMatchingModelOutput, config_class=BlipVisionConfig)
1585
+ def call(
1586
+ self,
1587
+ input_ids: tf.Tensor,
1588
+ pixel_values: tf.Tensor | None = None,
1589
+ use_itm_head: Optional[bool] = True,
1590
+ attention_mask: tf.Tensor | None = None,
1591
+ output_attentions: Optional[bool] = None,
1592
+ output_hidden_states: Optional[bool] = None,
1593
+ return_dict: Optional[bool] = None,
1594
+ training: Optional[bool] = None,
1595
+ ) -> Union[Tuple, TFBlipImageTextMatchingModelOutput]:
1596
+ r"""
1597
+ Returns:
1598
+
1599
+ Examples:
1600
+
1601
+ ```python
1602
+ >>> from PIL import Image
1603
+ >>> import requests
1604
+ >>> from transformers import AutoProcessor, TFBlipForImageTextRetrieval
1605
+
1606
+ >>> model = TFBlipForImageTextRetrieval.from_pretrained("Salesforce/blip-itm-base-coco")
1607
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-itm-base-coco")
1608
+
1609
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1610
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1611
+ >>> text = "an image of a cat"
1612
+
1613
+ >>> inputs = processor(images=image, text=text, return_tensors="tf")
1614
+ >>> outputs = model(**inputs)
1615
+ ```
1616
+ """
1617
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1618
+
1619
+ vision_outputs = self.vision_model(
1620
+ pixel_values=pixel_values,
1621
+ output_attentions=output_attentions,
1622
+ output_hidden_states=output_hidden_states,
1623
+ return_dict=return_dict,
1624
+ training=training,
1625
+ )
1626
+
1627
+ image_embeds = vision_outputs[0]
1628
+ image_atts = tf.ones(shape_list(image_embeds)[:-1], dtype=tf.int64)
1629
+
1630
+ # Matt: In PyTorch, only one path (itm/non-itm) is taken. However, in TensorFlow this can result in
1631
+ # some layers not being built! To avoid this, we always call both paths, then use an if statement to select
1632
+ # which output to pass to the final output. The unnecessary nodes will be pruned from the final graph, but
1633
+ # not before the layers have all been built correctly.
1634
+ itm_question_embeds = self.text_encoder(
1635
+ input_ids=input_ids,
1636
+ attention_mask=attention_mask,
1637
+ encoder_hidden_states=image_embeds,
1638
+ encoder_attention_mask=image_atts,
1639
+ return_dict=return_dict,
1640
+ training=training,
1641
+ )
1642
+ itm_question_embeds = itm_question_embeds[0] if not return_dict else itm_question_embeds.last_hidden_state
1643
+
1644
+ itm_output = self.itm_head(itm_question_embeds[:, 0, :])
1645
+
1646
+ no_itm_question_embeds = self.text_encoder(
1647
+ input_ids=input_ids,
1648
+ attention_mask=attention_mask,
1649
+ return_dict=return_dict,
1650
+ training=training,
1651
+ )
1652
+ no_itm_question_embeds = (
1653
+ no_itm_question_embeds[0] if not return_dict else no_itm_question_embeds.last_hidden_state
1654
+ )
1655
+
1656
+ image_feat, _ = tf.linalg.normalize(self.vision_proj(image_embeds[:, 0, :]), ord=2, axis=-1)
1657
+ text_feat, _ = tf.linalg.normalize(self.text_proj(no_itm_question_embeds[:, 0, :]), ord=2, axis=-1)
1658
+
1659
+ no_itm_output = tf.matmul(image_feat, text_feat, transpose_b=True)
1660
+
1661
+ if use_itm_head:
1662
+ output = itm_output
1663
+ question_embeds = itm_question_embeds
1664
+ else:
1665
+ output = no_itm_output
1666
+ question_embeds = no_itm_question_embeds
1667
+
1668
+ if not return_dict:
1669
+ outputs = (output, vision_outputs[0]) + vision_outputs[2:] + (question_embeds,)
1670
+ return tuple(output for output in outputs if output is not None)
1671
+
1672
+ return TFBlipImageTextMatchingModelOutput(
1673
+ itm_score=output,
1674
+ last_hidden_state=vision_outputs.last_hidden_state,
1675
+ hidden_states=vision_outputs.hidden_states,
1676
+ attentions=vision_outputs.attentions,
1677
+ question_embeds=question_embeds,
1678
+ )
1679
+
1680
+ def build(self, input_shape=None):
1681
+ if self.built:
1682
+ return
1683
+ self.built = True
1684
+ if getattr(self, "vision_model", None) is not None:
1685
+ with tf.name_scope(self.vision_model.name):
1686
+ self.vision_model.build(None)
1687
+ if getattr(self, "text_encoder", None) is not None:
1688
+ with tf.name_scope(self.text_encoder.name):
1689
+ self.text_encoder.build(None)
1690
+ if getattr(self, "vision_proj", None) is not None:
1691
+ with tf.name_scope(self.vision_proj.name):
1692
+ self.vision_proj.build([None, None, self.config.vision_config.hidden_size])
1693
+ if getattr(self, "text_proj", None) is not None:
1694
+ with tf.name_scope(self.text_proj.name):
1695
+ self.text_proj.build([None, None, self.config.text_config.hidden_size])
1696
+ if getattr(self, "itm_head", None) is not None:
1697
+ with tf.name_scope(self.itm_head.name):
1698
+ self.itm_head.build([None, None, self.config.text_config.hidden_size])
1699
+
1700
+
1701
+ __all__ = [
1702
+ "TFBlipModel",
1703
+ "TFBlipPreTrainedModel",
1704
+ "TFBlipForConditionalGeneration",
1705
+ "TFBlipForQuestionAnswering",
1706
+ "TFBlipVisionModel",
1707
+ "TFBlipTextModel",
1708
+ "TFBlipForImageTextRetrieval",
1709
+ ]
lib/python3.12/site-packages/transformers/models/blip/modeling_tf_blip_text.py ADDED
@@ -0,0 +1,1122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Salesforce Team Authors and The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the BSD-3-clause license (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
+ # https://opensource.org/licenses/BSD-3-Clause
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
+
17
+ from __future__ import annotations
18
+
19
+ import math
20
+ from typing import Optional, Tuple
21
+
22
+ import tensorflow as tf
23
+
24
+ from ...modeling_tf_outputs import (
25
+ TFBaseModelOutputWithPastAndCrossAttentions,
26
+ TFBaseModelOutputWithPoolingAndCrossAttentions,
27
+ TFCausalLMOutputWithCrossAttentions,
28
+ )
29
+ from ...modeling_tf_utils import (
30
+ TFModelInputType,
31
+ TFPreTrainedModel,
32
+ get_initializer,
33
+ get_tf_activation,
34
+ keras,
35
+ keras_serializable,
36
+ shape_list,
37
+ unpack_inputs,
38
+ )
39
+ from ...tf_utils import check_embeddings_within_bounds, invert_attention_mask, stable_softmax
40
+ from ...utils import add_start_docstrings_to_model_forward, logging
41
+ from .configuration_blip import BlipTextConfig
42
+
43
+
44
+ logger = logging.get_logger(__name__)
45
+
46
+ BLIP_TEXT_INPUTS_DOCSTRING = r"""
47
+ Args:
48
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
49
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
50
+ it.
51
+
52
+ Indices can be obtained using [`AutoProcessor`]. See [`BlipProcessor.__call__`] for details.
53
+
54
+ [What are input IDs?](../glossary#input-ids)
55
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
56
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
57
+
58
+ - 1 for tokens that are **not masked**,
59
+ - 0 for tokens that are **masked**.
60
+
61
+ [What are attention masks?](../glossary#attention-mask)
62
+ position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
63
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
64
+ config.max_position_embeddings - 1]`.
65
+
66
+ [What are position IDs?](../glossary#position-ids)
67
+ output_attentions (`bool`, *optional*):
68
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
69
+ tensors for more detail.
70
+ output_hidden_states (`bool`, *optional*):
71
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
72
+ more detail.
73
+ return_dict (`bool`, *optional*):
74
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
75
+ """
76
+
77
+
78
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L52
79
+ class TFBlipTextEmbeddings(keras.layers.Layer):
80
+ """Construct the embeddings from word and position embeddings."""
81
+
82
+ def __init__(self, config, **kwargs):
83
+ super().__init__(**kwargs)
84
+ self.word_embeddings = keras.layers.Embedding(
85
+ config.vocab_size,
86
+ config.hidden_size,
87
+ embeddings_initializer=get_initializer(config.initializer_range),
88
+ name="word_embeddings",
89
+ )
90
+ self.position_embeddings = keras.layers.Embedding(
91
+ config.max_position_embeddings,
92
+ config.hidden_size,
93
+ embeddings_initializer=get_initializer(config.initializer_range),
94
+ name="position_embeddings",
95
+ )
96
+
97
+ # self.LayerNorm is not snake-cased to stick with PyTorch model variable name and be able to load
98
+ # any TensorFlow checkpoint file
99
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
100
+ self.dropout = keras.layers.Dropout(config.hidden_dropout_prob, name="dropout")
101
+
102
+ self.position_ids = tf.expand_dims(tf.range(config.max_position_embeddings), 0)
103
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
104
+
105
+ self.config = config
106
+
107
+ def call(self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0, training=None):
108
+ if input_ids is not None:
109
+ input_shape = tf.shape(input_ids)
110
+ else:
111
+ input_shape = tf.shape(inputs_embeds)[:-1]
112
+
113
+ seq_length = input_shape[1]
114
+
115
+ if position_ids is None:
116
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
117
+
118
+ if inputs_embeds is None:
119
+ check_embeddings_within_bounds(input_ids, self.config.vocab_size)
120
+ inputs_embeds = self.word_embeddings(input_ids)
121
+
122
+ embeddings = inputs_embeds
123
+
124
+ if self.position_embedding_type == "absolute":
125
+ position_embeddings = self.position_embeddings(position_ids)
126
+ embeddings += position_embeddings
127
+ embeddings = self.LayerNorm(embeddings)
128
+ embeddings = self.dropout(embeddings, training=training)
129
+ return embeddings
130
+
131
+ def build(self, input_shape=None):
132
+ if self.built:
133
+ return
134
+ self.built = True
135
+ if getattr(self, "word_embeddings", None) is not None:
136
+ with tf.name_scope(self.word_embeddings.name):
137
+ self.word_embeddings.build(None)
138
+ if getattr(self, "position_embeddings", None) is not None:
139
+ with tf.name_scope(self.position_embeddings.name):
140
+ self.position_embeddings.build(None)
141
+ if getattr(self, "LayerNorm", None) is not None:
142
+ with tf.name_scope(self.LayerNorm.name):
143
+ self.LayerNorm.build([None, None, self.config.hidden_size])
144
+ if getattr(self, "dropout", None) is not None:
145
+ with tf.name_scope(self.dropout.name):
146
+ self.dropout.build(None)
147
+
148
+
149
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L97
150
+ class TFBlipTextSelfAttention(keras.layers.Layer):
151
+ def __init__(self, config, is_cross_attention, **kwargs):
152
+ super().__init__(**kwargs)
153
+ self.config = config
154
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
155
+ raise ValueError(
156
+ "The hidden size (%d) is not a multiple of the number of attention heads (%d)"
157
+ % (config.hidden_size, config.num_attention_heads)
158
+ )
159
+
160
+ self.num_attention_heads = config.num_attention_heads
161
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
162
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
163
+
164
+ self.query = keras.layers.Dense(
165
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
166
+ )
167
+ self.key = keras.layers.Dense(
168
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
169
+ )
170
+ self.value = keras.layers.Dense(
171
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
172
+ )
173
+
174
+ self.dropout = keras.layers.Dropout(config.attention_probs_dropout_prob)
175
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
176
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
177
+ self.max_position_embeddings = config.max_position_embeddings
178
+ self.distance_embedding = keras.layers.Embedding(
179
+ 2 * config.max_position_embeddings - 1, self.attention_head_size
180
+ )
181
+ self.is_cross_attention = is_cross_attention
182
+
183
+ def transpose_for_scores(self, x):
184
+ new_x_shape = tf.concat(
185
+ [tf.shape(x)[:-1], tf.constant([self.num_attention_heads, self.attention_head_size], dtype=tf.int32)],
186
+ axis=0,
187
+ )
188
+ x = tf.reshape(x, new_x_shape)
189
+ return tf.transpose(x, perm=(0, 2, 1, 3))
190
+
191
+ def call(
192
+ self,
193
+ hidden_states,
194
+ attention_mask=None,
195
+ head_mask=None,
196
+ encoder_hidden_states=None,
197
+ encoder_attention_mask=None,
198
+ past_key_value=None,
199
+ output_attentions=False,
200
+ training=None,
201
+ ):
202
+ mixed_query_layer = self.query(hidden_states)
203
+
204
+ # If this is instantiated as a cross-attention module, the keys
205
+ # and values come from an encoder; the attention mask needs to be
206
+ # such that the encoder's padding tokens are not attended to.
207
+ is_cross_attention = encoder_hidden_states is not None
208
+
209
+ if is_cross_attention:
210
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
211
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
212
+ attention_mask = encoder_attention_mask
213
+ elif past_key_value is not None:
214
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
215
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
216
+ key_layer = tf.concat([past_key_value[0], key_layer], axis=2)
217
+ value_layer = tf.concat([past_key_value[1], value_layer], axis=2)
218
+ else:
219
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
220
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
221
+
222
+ query_layer = self.transpose_for_scores(mixed_query_layer)
223
+
224
+ past_key_value = (key_layer, value_layer)
225
+
226
+ # Take the dot product between "query" and "key" to get the raw attention scores.
227
+ attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
228
+
229
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
230
+ seq_length = shape_list(hidden_states)[1]
231
+ position_ids_l = tf.expand_dims(tf.range(seq_length, dtype=tf.int64, device=hidden_states.device), 1)
232
+ position_ids_r = tf.expand_dims(tf.range(seq_length, dtype=tf.int64, device=hidden_states.device), 0)
233
+ distance = position_ids_l - position_ids_r
234
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
235
+ positional_embedding = tf.cast(positional_embedding, query_layer.dtype) # fp16 compatibility
236
+
237
+ if self.position_embedding_type == "relative_key":
238
+ relative_position_scores = tf.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
239
+ attention_scores = attention_scores + relative_position_scores
240
+ elif self.position_embedding_type == "relative_key_query":
241
+ relative_position_scores_query = tf.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
242
+ relative_position_scores_key = tf.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
243
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
244
+
245
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
246
+ if attention_mask is not None:
247
+ # Apply the attention mask is (precomputed for all layers in BlipTextModel forward() function)
248
+ attention_scores = attention_scores + tf.cast(attention_mask, attention_scores.dtype)
249
+
250
+ # Normalize the attention scores to probabilities.
251
+ attention_probs = stable_softmax(attention_scores, axis=-1)
252
+
253
+ # This is actually dropping out entire tokens to attend to, which might
254
+ # seem a bit unusual, but is taken from the original Transformer paper.
255
+ attention_probs_dropped = self.dropout(attention_probs, training=training)
256
+
257
+ # Mask heads if we want to
258
+ if head_mask is not None:
259
+ attention_probs_dropped = attention_probs_dropped * head_mask
260
+
261
+ context_layer = attention_probs_dropped @ value_layer
262
+
263
+ context_layer = tf.transpose(context_layer, perm=(0, 2, 1, 3))
264
+ new_context_layer_shape = shape_list(context_layer)[:-2] + [self.all_head_size]
265
+ context_layer = tf.reshape(context_layer, new_context_layer_shape)
266
+
267
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
268
+
269
+ outputs = outputs + (past_key_value,)
270
+ return outputs
271
+
272
+ def build(self, input_shape=None):
273
+ if self.built:
274
+ return
275
+ self.built = True
276
+ if getattr(self, "query", None) is not None:
277
+ with tf.name_scope(self.query.name):
278
+ self.query.build([None, None, self.config.hidden_size])
279
+ if self.is_cross_attention:
280
+ if getattr(self, "key", None) is not None:
281
+ with tf.name_scope(self.key.name):
282
+ self.key.build([None, None, self.config.encoder_hidden_size])
283
+ if getattr(self, "value", None) is not None:
284
+ with tf.name_scope(self.value.name):
285
+ self.value.build([None, None, self.config.encoder_hidden_size])
286
+ else:
287
+ if getattr(self, "key", None) is not None:
288
+ with tf.name_scope(self.key.name):
289
+ self.key.build([None, None, self.config.hidden_size])
290
+ if getattr(self, "value", None) is not None:
291
+ with tf.name_scope(self.value.name):
292
+ self.value.build([None, None, self.config.hidden_size])
293
+
294
+
295
+ class TFBlipTextSelfOutput(keras.layers.Layer):
296
+ def __init__(self, config: BlipTextConfig, **kwargs):
297
+ super().__init__(**kwargs)
298
+
299
+ self.dense = keras.layers.Dense(
300
+ units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
301
+ )
302
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
303
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
304
+ self.config = config
305
+
306
+ def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: Optional[bool] = None) -> tf.Tensor:
307
+ hidden_states = self.dense(inputs=hidden_states)
308
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
309
+ hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
310
+
311
+ return hidden_states
312
+
313
+ def build(self, input_shape=None):
314
+ if self.built:
315
+ return
316
+ self.built = True
317
+ if getattr(self, "dense", None) is not None:
318
+ with tf.name_scope(self.dense.name):
319
+ self.dense.build([None, None, self.config.hidden_size])
320
+ if getattr(self, "LayerNorm", None) is not None:
321
+ with tf.name_scope(self.LayerNorm.name):
322
+ self.LayerNorm.build([None, None, self.config.hidden_size])
323
+
324
+
325
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#242
326
+ class TFBlipTextAttention(keras.layers.Layer):
327
+ def __init__(self, config, is_cross_attention=False, **kwargs):
328
+ super().__init__(**kwargs)
329
+ self.self = TFBlipTextSelfAttention(config, is_cross_attention, name="self")
330
+ # "output" is a protected attribute on TF models
331
+ self.self_output = TFBlipTextSelfOutput(config, name="output")
332
+
333
+ def call(
334
+ self,
335
+ hidden_states: tf.Tensor,
336
+ attention_mask: tf.Tensor | None = None,
337
+ head_mask: tf.Tensor | None = None,
338
+ encoder_hidden_states: tf.Tensor | None = None,
339
+ encoder_attention_mask: tf.Tensor | None = None,
340
+ past_key_value: Tuple[Tuple[tf.Tensor]] | None = None,
341
+ output_attentions: Optional[bool] = False,
342
+ training: Optional[bool] = None,
343
+ ):
344
+ self_outputs = self.self(
345
+ hidden_states,
346
+ attention_mask,
347
+ head_mask,
348
+ encoder_hidden_states,
349
+ encoder_attention_mask,
350
+ past_key_value,
351
+ output_attentions,
352
+ training=training,
353
+ )
354
+ attention_output = self.self_output(self_outputs[0], hidden_states, training=training)
355
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
356
+ return outputs
357
+
358
+ def build(self, input_shape=None):
359
+ if self.built:
360
+ return
361
+ self.built = True
362
+ if getattr(self, "self", None) is not None:
363
+ with tf.name_scope(self.self.name):
364
+ self.self.build(None)
365
+ if getattr(self, "self_output", None) is not None:
366
+ with tf.name_scope(self.self_output.name):
367
+ self.self_output.build(None)
368
+
369
+
370
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertIntermediate with Bert->BlipText
371
+ class TFBlipTextIntermediate(keras.layers.Layer):
372
+ def __init__(self, config: BlipTextConfig, **kwargs):
373
+ super().__init__(**kwargs)
374
+
375
+ self.dense = keras.layers.Dense(
376
+ units=config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
377
+ )
378
+
379
+ if isinstance(config.hidden_act, str):
380
+ self.intermediate_act_fn = get_tf_activation(config.hidden_act)
381
+ else:
382
+ self.intermediate_act_fn = config.hidden_act
383
+ self.config = config
384
+
385
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
386
+ hidden_states = self.dense(inputs=hidden_states)
387
+ hidden_states = self.intermediate_act_fn(hidden_states)
388
+
389
+ return hidden_states
390
+
391
+ def build(self, input_shape=None):
392
+ if self.built:
393
+ return
394
+ self.built = True
395
+ if getattr(self, "dense", None) is not None:
396
+ with tf.name_scope(self.dense.name):
397
+ self.dense.build([None, None, self.config.hidden_size])
398
+
399
+
400
+ class TFBlipTextOutput(keras.layers.Layer):
401
+ def __init__(self, config: BlipTextConfig, **kwargs):
402
+ super().__init__(**kwargs)
403
+
404
+ self.dense = keras.layers.Dense(
405
+ units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
406
+ )
407
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
408
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
409
+ self.config = config
410
+
411
+ def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
412
+ hidden_states = self.dense(inputs=hidden_states)
413
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
414
+ hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
415
+
416
+ return hidden_states
417
+
418
+ def build(self, input_shape=None):
419
+ if self.built:
420
+ return
421
+ self.built = True
422
+ if getattr(self, "dense", None) is not None:
423
+ with tf.name_scope(self.dense.name):
424
+ self.dense.build([None, None, self.config.intermediate_size])
425
+ if getattr(self, "LayerNorm", None) is not None:
426
+ with tf.name_scope(self.LayerNorm.name):
427
+ self.LayerNorm.build([None, None, self.config.hidden_size])
428
+
429
+
430
+ class TFBlipTextLayer(keras.layers.Layer):
431
+ def __init__(self, config, **kwargs):
432
+ super().__init__(**kwargs)
433
+ self.config = config
434
+ self.attention = TFBlipTextAttention(config, name="attention")
435
+ if self.config.is_decoder:
436
+ self.crossattention = TFBlipTextAttention(
437
+ config, is_cross_attention=self.config.is_decoder, name="crossattention"
438
+ )
439
+ self.intermediate = TFBlipTextIntermediate(config, name="intermediate")
440
+ self.self_output = TFBlipTextOutput(config, name="output")
441
+
442
+ def call(
443
+ self,
444
+ hidden_states,
445
+ attention_mask=None,
446
+ head_mask=None,
447
+ encoder_hidden_states=None,
448
+ encoder_attention_mask=None,
449
+ past_key_value=None,
450
+ output_attentions=False,
451
+ training=None,
452
+ ):
453
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
454
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
455
+ self_attention_outputs = self.attention(
456
+ hidden_states,
457
+ attention_mask,
458
+ head_mask,
459
+ output_attentions=output_attentions,
460
+ past_key_value=self_attn_past_key_value,
461
+ training=training,
462
+ )
463
+ attention_output = self_attention_outputs[0]
464
+
465
+ outputs = self_attention_outputs[1:-1]
466
+ present_key_value = self_attention_outputs[-1]
467
+
468
+ if encoder_hidden_states is not None:
469
+ cross_attention_outputs = self.crossattention(
470
+ attention_output,
471
+ attention_mask,
472
+ head_mask,
473
+ encoder_hidden_states,
474
+ encoder_attention_mask,
475
+ output_attentions=output_attentions,
476
+ training=training,
477
+ )
478
+ attention_output = cross_attention_outputs[0]
479
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
480
+ intermediate_output = self.intermediate(attention_output)
481
+ layer_output = self.self_output(intermediate_output, attention_output, training=training)
482
+ outputs = (layer_output,) + outputs
483
+
484
+ outputs = outputs + (present_key_value,)
485
+
486
+ return outputs
487
+
488
+ def build(self, input_shape=None):
489
+ if self.built:
490
+ return
491
+ self.built = True
492
+ if getattr(self, "attention", None) is not None:
493
+ with tf.name_scope(self.attention.name):
494
+ self.attention.build(None)
495
+ if getattr(self, "intermediate", None) is not None:
496
+ with tf.name_scope(self.intermediate.name):
497
+ self.intermediate.build(None)
498
+ if getattr(self, "self_output", None) is not None:
499
+ with tf.name_scope(self.self_output.name):
500
+ self.self_output.build(None)
501
+ if getattr(self, "crossattention", None) is not None:
502
+ with tf.name_scope(self.crossattention.name):
503
+ self.crossattention.build(None)
504
+
505
+
506
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L386
507
+ @keras_serializable
508
+ class TFBlipTextEncoder(keras.layers.Layer):
509
+ config_class = BlipTextConfig
510
+
511
+ def __init__(self, config, name=None, **kwargs):
512
+ super().__init__(name=name, **kwargs)
513
+ self.config = config
514
+ self.layer = [TFBlipTextLayer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
515
+
516
+ @unpack_inputs
517
+ def call(
518
+ self,
519
+ hidden_states,
520
+ attention_mask=None,
521
+ head_mask=None,
522
+ encoder_hidden_states=None,
523
+ encoder_attention_mask=None,
524
+ past_key_values=None,
525
+ use_cache=None,
526
+ output_attentions=False,
527
+ output_hidden_states=False,
528
+ return_dict=True,
529
+ training=None,
530
+ ):
531
+ all_hidden_states = () if output_hidden_states else None
532
+ all_self_attentions = () if output_attentions else None
533
+ all_cross_attentions = () if output_attentions and self.config.is_decoder else None
534
+
535
+ next_decoder_cache = () if use_cache else None
536
+
537
+ for i in range(self.config.num_hidden_layers):
538
+ layer_module = self.layer[i]
539
+ if output_hidden_states:
540
+ all_hidden_states = all_hidden_states + (hidden_states,)
541
+
542
+ layer_head_mask = head_mask[i] if head_mask is not None else None
543
+ past_key_value = past_key_values[i] if past_key_values is not None else None
544
+
545
+ layer_outputs = layer_module(
546
+ hidden_states,
547
+ attention_mask,
548
+ layer_head_mask,
549
+ encoder_hidden_states,
550
+ encoder_attention_mask,
551
+ past_key_value,
552
+ output_attentions,
553
+ training=training,
554
+ )
555
+
556
+ hidden_states = layer_outputs[0]
557
+ if use_cache:
558
+ next_decoder_cache += (layer_outputs[-1],)
559
+ if output_attentions:
560
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
561
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
562
+
563
+ if output_hidden_states:
564
+ all_hidden_states = all_hidden_states + (hidden_states,)
565
+
566
+ if not return_dict:
567
+ return tuple(
568
+ v
569
+ for v in [
570
+ hidden_states,
571
+ next_decoder_cache,
572
+ all_hidden_states,
573
+ all_self_attentions,
574
+ all_cross_attentions,
575
+ ]
576
+ if v is not None
577
+ )
578
+ return TFBaseModelOutputWithPastAndCrossAttentions(
579
+ last_hidden_state=hidden_states,
580
+ past_key_values=next_decoder_cache,
581
+ hidden_states=all_hidden_states,
582
+ attentions=all_self_attentions,
583
+ cross_attentions=all_cross_attentions,
584
+ )
585
+
586
+ def build(self, input_shape=None):
587
+ if self.built:
588
+ return
589
+ self.built = True
590
+ if getattr(self, "layer", None) is not None:
591
+ for layer in self.layer:
592
+ with tf.name_scope(layer.name):
593
+ layer.build(None)
594
+
595
+
596
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertPooler with Bert->BlipText
597
+ class TFBlipTextPooler(keras.layers.Layer):
598
+ def __init__(self, config: BlipTextConfig, **kwargs):
599
+ super().__init__(**kwargs)
600
+
601
+ self.dense = keras.layers.Dense(
602
+ units=config.hidden_size,
603
+ kernel_initializer=get_initializer(config.initializer_range),
604
+ activation="tanh",
605
+ name="dense",
606
+ )
607
+ self.config = config
608
+
609
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
610
+ # We "pool" the model by simply taking the hidden state corresponding
611
+ # to the first token.
612
+ first_token_tensor = hidden_states[:, 0]
613
+ pooled_output = self.dense(inputs=first_token_tensor)
614
+
615
+ return pooled_output
616
+
617
+ def build(self, input_shape=None):
618
+ if self.built:
619
+ return
620
+ self.built = True
621
+ if getattr(self, "dense", None) is not None:
622
+ with tf.name_scope(self.dense.name):
623
+ self.dense.build([None, None, self.config.hidden_size])
624
+
625
+
626
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertPredictionHeadTransform with Bert->BlipText
627
+ class TFBlipTextPredictionHeadTransform(keras.layers.Layer):
628
+ def __init__(self, config: BlipTextConfig, **kwargs):
629
+ super().__init__(**kwargs)
630
+
631
+ self.dense = keras.layers.Dense(
632
+ units=config.hidden_size,
633
+ kernel_initializer=get_initializer(config.initializer_range),
634
+ name="dense",
635
+ )
636
+
637
+ if isinstance(config.hidden_act, str):
638
+ self.transform_act_fn = get_tf_activation(config.hidden_act)
639
+ else:
640
+ self.transform_act_fn = config.hidden_act
641
+
642
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
643
+ self.config = config
644
+
645
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
646
+ hidden_states = self.dense(inputs=hidden_states)
647
+ hidden_states = self.transform_act_fn(hidden_states)
648
+ hidden_states = self.LayerNorm(inputs=hidden_states)
649
+
650
+ return hidden_states
651
+
652
+ def build(self, input_shape=None):
653
+ if self.built:
654
+ return
655
+ self.built = True
656
+ if getattr(self, "dense", None) is not None:
657
+ with tf.name_scope(self.dense.name):
658
+ self.dense.build([None, None, self.config.hidden_size])
659
+ if getattr(self, "LayerNorm", None) is not None:
660
+ with tf.name_scope(self.LayerNorm.name):
661
+ self.LayerNorm.build([None, None, self.config.hidden_size])
662
+
663
+
664
+ class TFBlipTextLMPredictionHead(keras.layers.Layer):
665
+ def __init__(self, config, **kwargs):
666
+ super().__init__(**kwargs)
667
+ self.transform = TFBlipTextPredictionHeadTransform(config, name="transform")
668
+
669
+ # The output weights are the same as the input embeddings, but there is
670
+ # an output-only bias for each token.
671
+ self.decoder = keras.layers.Dense(
672
+ config.vocab_size,
673
+ kernel_initializer=get_initializer(config.initializer_range),
674
+ name="decoder",
675
+ use_bias=False,
676
+ )
677
+ self.config = config
678
+
679
+ def build(self, input_shape=None):
680
+ self.bias = self.add_weight(name="bias", shape=(self.config.vocab_size,), initializer="zeros", trainable=True)
681
+
682
+ if self.built:
683
+ return
684
+ self.built = True
685
+ if getattr(self, "transform", None) is not None:
686
+ with tf.name_scope(self.transform.name):
687
+ self.transform.build(None)
688
+ if getattr(self, "decoder", None) is not None:
689
+ with tf.name_scope(self.decoder.name):
690
+ self.decoder.build([None, None, self.config.hidden_size])
691
+
692
+ def call(self, hidden_states):
693
+ hidden_states = self.transform(hidden_states)
694
+ hidden_states = self.decoder(hidden_states) + self.bias
695
+ return hidden_states
696
+
697
+
698
+ class TFBlipTextOnlyMLMHead(keras.layers.Layer):
699
+ def __init__(self, config, **kwargs):
700
+ super().__init__(**kwargs)
701
+ self.predictions = TFBlipTextLMPredictionHead(config, name="predictions")
702
+
703
+ def call(self, sequence_output: tf.Tensor) -> tf.Tensor:
704
+ prediction_scores = self.predictions(sequence_output)
705
+ return prediction_scores
706
+
707
+ def build(self, input_shape=None):
708
+ if self.built:
709
+ return
710
+ self.built = True
711
+ if getattr(self, "predictions", None) is not None:
712
+ with tf.name_scope(self.predictions.name):
713
+ self.predictions.build(None)
714
+
715
+
716
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L548
717
+ class TFBlipTextPreTrainedModel(TFPreTrainedModel):
718
+ """
719
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
720
+ models.
721
+ """
722
+
723
+ config_class = BlipTextConfig
724
+ base_model_prefix = "bert"
725
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
726
+
727
+
728
+ # Adapted from https://github.com/salesforce/BLIP/blob/3a29b7410476bf5f2ba0955827390eb6ea1f4f9d/models/med.py#L571
729
+ class TFBlipTextModel(TFBlipTextPreTrainedModel):
730
+ """
731
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
732
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
733
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
734
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. argument and `is_decoder` set to `True`; an
735
+ `encoder_hidden_states` is then expected as an input to the forward pass.
736
+ """
737
+
738
+ def __init__(self, config, add_pooling_layer=True, name=None, **kwargs):
739
+ super().__init__(config, name=name, **kwargs)
740
+ self.config = config
741
+
742
+ self.embeddings = TFBlipTextEmbeddings(config, name="embeddings")
743
+ self.encoder = TFBlipTextEncoder(config, name="encoder")
744
+ self.pooler = TFBlipTextPooler(config, name="pooler") if add_pooling_layer else None
745
+
746
+ def get_input_embeddings(self):
747
+ return self.embeddings.word_embeddings
748
+
749
+ def set_input_embeddings(self, value):
750
+ self.embeddings.word_embeddings = value
751
+
752
+ @tf.function
753
+ def get_extended_attention_mask(
754
+ self, attention_mask: tf.Tensor, input_shape: Tuple[int], is_decoder: bool
755
+ ) -> tf.Tensor:
756
+ """
757
+ Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
758
+
759
+ Arguments:
760
+ attention_mask (`tf.Tensor`):
761
+ Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
762
+ input_shape (`Tuple[int]`):
763
+ The shape of the input to the model.
764
+ is_decoder (`bool`):
765
+ Whether the model is used as a decoder.
766
+
767
+ Returns:
768
+ `tf.Tensor` The extended attention mask, with the same dtype as `attention_mask.dtype`.
769
+ """
770
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
771
+ # ourselves in which case we just need to make it broadcastable to all heads.
772
+ if not isinstance(attention_mask, tf.Tensor):
773
+ attention_mask = tf.convert_to_tensor(attention_mask) # Catches NumPy inputs that haven't been cast yet
774
+ if attention_mask.shape.rank == 3:
775
+ extended_attention_mask = attention_mask[:, None, :, :]
776
+ elif attention_mask.shape.rank == 2:
777
+ # Provided a padding mask of dimensions [batch_size, seq_length]
778
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
779
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
780
+ if is_decoder:
781
+ batch_size, seq_length = input_shape
782
+
783
+ seq_ids = tf.range(seq_length, dtype=attention_mask.dtype)
784
+ causal_mask = tf.broadcast_to(seq_ids, (batch_size, seq_length, seq_length)) <= seq_ids[None, :, None]
785
+ # in case past_key_values are used we need to add a prefix ones mask to the causal mask
786
+
787
+ if shape_list(causal_mask)[1] < shape_list(attention_mask)[1]:
788
+ prefix_seq_len = tf.shape(attention_mask)[1] - tf.shape(causal_mask)[1]
789
+ causal_mask = tf.concat(
790
+ [
791
+ tf.ones((batch_size, seq_length, prefix_seq_len), dtype=causal_mask.dtype),
792
+ causal_mask,
793
+ ],
794
+ axis=-1,
795
+ )
796
+ extended_attention_mask = (
797
+ tf.cast(causal_mask[:, None, :, :], attention_mask.dtype) * attention_mask[:, None, None, :]
798
+ )
799
+ else:
800
+ extended_attention_mask = attention_mask[:, None, None, :]
801
+ else:
802
+ raise ValueError(
803
+ "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
804
+ input_shape, attention_mask.shape
805
+ )
806
+ )
807
+
808
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
809
+ # masked positions, this operation will create a tensor which is 0.0 for
810
+ # positions we want to attend and -10000.0 for masked positions.
811
+ # Since we are adding it to the raw scores before the softmax, this is
812
+ # effectively the same as removing these entirely.
813
+ extended_attention_mask = tf.cast(extended_attention_mask, self.dtype) # fp16 compatibility
814
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
815
+ return extended_attention_mask
816
+
817
+ @add_start_docstrings_to_model_forward(BLIP_TEXT_INPUTS_DOCSTRING)
818
+ @unpack_inputs
819
+ def call(
820
+ self,
821
+ input_ids: TFModelInputType | None = None,
822
+ attention_mask: tf.Tensor | None = None,
823
+ position_ids: tf.Tensor | None = None,
824
+ head_mask: tf.Tensor | None = None,
825
+ inputs_embeds: tf.Tensor | None = None,
826
+ encoder_embeds: tf.Tensor | None = None,
827
+ encoder_hidden_states: tf.Tensor | None = None,
828
+ encoder_attention_mask: tf.Tensor | None = None,
829
+ past_key_values: Tuple[Tuple[tf.Tensor]] | None = None,
830
+ use_cache: bool | None = None,
831
+ output_attentions: bool | None = None,
832
+ output_hidden_states: bool | None = None,
833
+ return_dict: bool | None = None,
834
+ is_decoder: bool = False,
835
+ training: bool = False,
836
+ ) -> Tuple[tf.Tensor] | TFBaseModelOutputWithPoolingAndCrossAttentions:
837
+ r"""
838
+ encoder_hidden_states (`tf.Tensor`, *optional*):
839
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
840
+ the model is configured as a decoder.
841
+ encoder_attention_mask (`tf.Tensor`, *optional*):
842
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
843
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
844
+ - 1 for tokens that are **not masked**,
845
+ - 0 for tokens that are **masked**.
846
+ past_key_values (`tuple(tuple(tf.Tensor))`, *optional*):
847
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
848
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
849
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
850
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
851
+ use_cache (`bool`, *optional*):
852
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
853
+ `past_key_values`).
854
+ """
855
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
856
+ output_hidden_states = (
857
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
858
+ )
859
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
860
+
861
+ if is_decoder:
862
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
863
+ else:
864
+ use_cache = False
865
+
866
+ if input_ids is not None and inputs_embeds is not None:
867
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
868
+ elif input_ids is not None:
869
+ input_shape = shape_list(input_ids)
870
+ batch_size, seq_length = input_shape
871
+ elif inputs_embeds is not None:
872
+ input_shape = shape_list(inputs_embeds)[:-1]
873
+ batch_size, seq_length = input_shape
874
+ elif encoder_embeds is not None:
875
+ input_shape = shape_list(encoder_embeds)[:-1]
876
+ batch_size, seq_length = input_shape
877
+ else:
878
+ raise ValueError("You have to specify either input_ids or inputs_embeds or encoder_embeds")
879
+
880
+ # past_key_values_length
881
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
882
+
883
+ if attention_mask is None:
884
+ attention_mask = tf.ones(((batch_size, seq_length + past_key_values_length)))
885
+
886
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
887
+ # ourselves in which case we just need to make it broadcastable to all heads.
888
+ extended_attention_mask: tf.Tensor = self.get_extended_attention_mask(attention_mask, input_shape, is_decoder)
889
+
890
+ # If a 2D or 3D attention mask is provided for the cross-attention
891
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
892
+ if encoder_hidden_states is not None:
893
+ if isinstance(encoder_hidden_states, list):
894
+ encoder_batch_size, encoder_sequence_length, _ = shape_list(encoder_hidden_states[0])
895
+ else:
896
+ encoder_batch_size, encoder_sequence_length, _ = shape_list(encoder_hidden_states)
897
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
898
+
899
+ if isinstance(encoder_attention_mask, list):
900
+ encoder_extended_attention_mask = [invert_attention_mask(mask) for mask in encoder_attention_mask]
901
+ elif encoder_attention_mask is None:
902
+ encoder_attention_mask = tf.ones(encoder_hidden_shape)
903
+ encoder_extended_attention_mask = invert_attention_mask(encoder_attention_mask)
904
+ else:
905
+ encoder_extended_attention_mask = invert_attention_mask(encoder_attention_mask)
906
+ else:
907
+ encoder_extended_attention_mask = None
908
+
909
+ # Prepare head mask if needed
910
+ # 1.0 in head_mask indicate we keep the head
911
+ # attention_probs has shape bsz x n_heads x N x N
912
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
913
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
914
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
915
+
916
+ if encoder_embeds is None:
917
+ embedding_output = self.embeddings(
918
+ input_ids=input_ids,
919
+ position_ids=position_ids,
920
+ inputs_embeds=inputs_embeds,
921
+ past_key_values_length=past_key_values_length,
922
+ )
923
+ else:
924
+ embedding_output = encoder_embeds
925
+
926
+ encoder_outputs = self.encoder(
927
+ embedding_output,
928
+ attention_mask=extended_attention_mask,
929
+ head_mask=head_mask,
930
+ encoder_hidden_states=encoder_hidden_states,
931
+ encoder_attention_mask=encoder_extended_attention_mask,
932
+ past_key_values=past_key_values,
933
+ use_cache=use_cache,
934
+ output_attentions=output_attentions,
935
+ output_hidden_states=output_hidden_states,
936
+ return_dict=return_dict,
937
+ training=training,
938
+ )
939
+ sequence_output = encoder_outputs[0]
940
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
941
+
942
+ if not return_dict:
943
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
944
+
945
+ return TFBaseModelOutputWithPoolingAndCrossAttentions(
946
+ last_hidden_state=sequence_output,
947
+ pooler_output=pooled_output,
948
+ past_key_values=encoder_outputs.past_key_values,
949
+ hidden_states=encoder_outputs.hidden_states,
950
+ attentions=encoder_outputs.attentions,
951
+ cross_attentions=encoder_outputs.cross_attentions,
952
+ )
953
+
954
+ def build(self, input_shape=None):
955
+ if self.built:
956
+ return
957
+ self.built = True
958
+ if getattr(self, "embeddings", None) is not None:
959
+ with tf.name_scope(self.embeddings.name):
960
+ self.embeddings.build(None)
961
+ if getattr(self, "encoder", None) is not None:
962
+ with tf.name_scope(self.encoder.name):
963
+ self.encoder.build(None)
964
+ if getattr(self, "pooler", None) is not None:
965
+ with tf.name_scope(self.pooler.name):
966
+ self.pooler.build(None)
967
+
968
+
969
+ # Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L811
970
+ class TFBlipTextLMHeadModel(TFBlipTextPreTrainedModel):
971
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
972
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
973
+
974
+ def __init__(self, config, **kwargs):
975
+ super().__init__(config, **kwargs)
976
+
977
+ self.bert = TFBlipTextModel(config, add_pooling_layer=False, name="bert")
978
+ self.cls = TFBlipTextOnlyMLMHead(config, name="cls")
979
+ self.label_smoothing = config.label_smoothing
980
+
981
+ def get_output_embeddings(self):
982
+ return self.cls.predictions.decoder
983
+
984
+ def set_output_embeddings(self, new_embeddings):
985
+ self.cls.predictions.decoder = new_embeddings
986
+
987
+ @add_start_docstrings_to_model_forward(BLIP_TEXT_INPUTS_DOCSTRING)
988
+ @unpack_inputs
989
+ def call(
990
+ self,
991
+ input_ids=None,
992
+ attention_mask=None,
993
+ position_ids=None,
994
+ head_mask=None,
995
+ inputs_embeds=None,
996
+ encoder_hidden_states=None,
997
+ encoder_attention_mask=None,
998
+ labels=None,
999
+ past_key_values=None,
1000
+ use_cache=None,
1001
+ output_attentions=None,
1002
+ output_hidden_states=None,
1003
+ return_dict=None,
1004
+ return_logits=False,
1005
+ is_decoder=True,
1006
+ training=None,
1007
+ ):
1008
+ r"""
1009
+ encoder_hidden_states (`tf.Tensor`, *optional*): Sequence of
1010
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is
1011
+ configured as a decoder.
1012
+ encoder_attention_mask (`tf.Tensor`, *optional*):
1013
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1014
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1015
+ - 1 for tokens that are **not masked**,
1016
+ - 0 for tokens that are **masked**.
1017
+ labels (`tf.Tensor`, *optional*):
1018
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1019
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
1020
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
1021
+ past_key_values (`tuple(tuple(tf.Tensor))`, *optional*):
1022
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1023
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1024
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1025
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1026
+ use_cache (`bool`, *optional*):
1027
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1028
+ `past_key_values`).
1029
+ """
1030
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1031
+ if labels is not None:
1032
+ use_cache = False
1033
+
1034
+ outputs = self.bert(
1035
+ input_ids,
1036
+ attention_mask=attention_mask,
1037
+ position_ids=position_ids,
1038
+ head_mask=head_mask,
1039
+ inputs_embeds=inputs_embeds,
1040
+ encoder_hidden_states=encoder_hidden_states,
1041
+ encoder_attention_mask=encoder_attention_mask,
1042
+ past_key_values=past_key_values,
1043
+ use_cache=use_cache,
1044
+ output_attentions=output_attentions,
1045
+ output_hidden_states=output_hidden_states,
1046
+ return_dict=return_dict,
1047
+ is_decoder=is_decoder,
1048
+ training=training,
1049
+ )
1050
+
1051
+ sequence_output = outputs[0]
1052
+ prediction_scores = self.cls(sequence_output)
1053
+
1054
+ if return_logits:
1055
+ return prediction_scores[:, :-1, :]
1056
+
1057
+ lm_loss = None
1058
+ if labels is not None:
1059
+ # we are doing next-token prediction; shift prediction scores and input ids by one
1060
+ shifted_prediction_scores = prediction_scores[:, :-1, :]
1061
+ shifted_prediction_scores = tf.reshape(shifted_prediction_scores, (-1, self.config.vocab_size))
1062
+ labels = labels[:, 1:]
1063
+ labels = tf.reshape(labels, (-1,))
1064
+ # Keras won't give us label smoothing for sparse CE, so we de-sparsify things here
1065
+ # Use relu to clamp masked labels at 0 to avoid NaN (we will be zeroing those out later anyway)
1066
+ one_hot_labels = tf.one_hot(tf.nn.relu(labels), depth=self.config.vocab_size, dtype=tf.float32)
1067
+ loss_fct = keras.losses.CategoricalCrossentropy(
1068
+ from_logits=True, label_smoothing=self.label_smoothing, reduction="none"
1069
+ )
1070
+ masked_positions = tf.cast(tf.not_equal(labels, -100), dtype=tf.float32)
1071
+ lm_loss = loss_fct(one_hot_labels, shifted_prediction_scores)
1072
+ lm_loss *= masked_positions
1073
+ lm_loss = tf.reduce_sum(lm_loss, axis=0) / tf.math.count_nonzero(masked_positions, dtype=tf.float32)
1074
+
1075
+ if not return_dict:
1076
+ output = (prediction_scores,) + outputs[2:]
1077
+ return ((lm_loss,) + output) if lm_loss is not None else output
1078
+
1079
+ return TFCausalLMOutputWithCrossAttentions(
1080
+ loss=lm_loss,
1081
+ logits=prediction_scores,
1082
+ past_key_values=outputs.past_key_values,
1083
+ hidden_states=outputs.hidden_states,
1084
+ attentions=outputs.attentions,
1085
+ cross_attentions=outputs.cross_attentions,
1086
+ )
1087
+
1088
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
1089
+ input_shape = input_ids.shape
1090
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1091
+ if attention_mask is None:
1092
+ attention_mask = input_ids.new_ones(input_shape)
1093
+
1094
+ # cut decoder_input_ids if past_key_values is used
1095
+ if past_key_values is not None:
1096
+ input_ids = input_ids[:, -1:]
1097
+
1098
+ return {
1099
+ "input_ids": input_ids,
1100
+ "attention_mask": attention_mask,
1101
+ "past_key_values": past_key_values,
1102
+ "encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None),
1103
+ "encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None),
1104
+ "is_decoder": True,
1105
+ }
1106
+
1107
+ def _reorder_cache(self, past_key_values, beam_idx):
1108
+ reordered_past = ()
1109
+ for layer_past in past_key_values:
1110
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
1111
+ return reordered_past
1112
+
1113
+ def build(self, input_shape=None):
1114
+ if self.built:
1115
+ return
1116
+ self.built = True
1117
+ if getattr(self, "bert", None) is not None:
1118
+ with tf.name_scope(self.bert.name):
1119
+ self.bert.build(None)
1120
+ if getattr(self, "cls", None) is not None:
1121
+ with tf.name_scope(self.cls.name):
1122
+ self.cls.build(None)
lib/python3.12/site-packages/transformers/models/blip/processing_blip.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Processor class for Blip.
17
+ """
18
+
19
+ from typing import List, Optional, Union
20
+
21
+ from ...image_utils import ImageInput
22
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
23
+ from ...tokenization_utils_base import BatchEncoding, PreTokenizedInput, TextInput
24
+
25
+
26
+ class BlipProcessorKwargs(ProcessingKwargs, total=False):
27
+ _defaults = {
28
+ "text_kwargs": {
29
+ "add_special_tokens": True,
30
+ "padding": False,
31
+ "stride": 0,
32
+ "return_overflowing_tokens": False,
33
+ "return_special_tokens_mask": False,
34
+ "return_offsets_mapping": False,
35
+ "return_token_type_ids": False,
36
+ "return_length": False,
37
+ "verbose": True,
38
+ },
39
+ "images_kwargs": {},
40
+ }
41
+
42
+
43
+ class BlipProcessor(ProcessorMixin):
44
+ r"""
45
+ Constructs a BLIP processor which wraps a BERT tokenizer and BLIP image processor into a single processor.
46
+
47
+ [`BlipProcessor`] offers all the functionalities of [`BlipImageProcessor`] and [`BertTokenizerFast`]. See the
48
+ docstring of [`~BlipProcessor.__call__`] and [`~BlipProcessor.decode`] for more information.
49
+
50
+ Args:
51
+ image_processor (`BlipImageProcessor`):
52
+ An instance of [`BlipImageProcessor`]. The image processor is a required input.
53
+ tokenizer (`BertTokenizerFast`):
54
+ An instance of ['BertTokenizerFast`]. The tokenizer is a required input.
55
+ """
56
+
57
+ attributes = ["image_processor", "tokenizer"]
58
+ valid_kwargs = []
59
+ image_processor_class = ("BlipImageProcessor", "BlipImageProcessorFast")
60
+ tokenizer_class = ("BertTokenizer", "BertTokenizerFast")
61
+
62
+ def __init__(self, image_processor, tokenizer, **kwargs):
63
+ tokenizer.return_token_type_ids = False
64
+ super().__init__(image_processor, tokenizer)
65
+ self.current_processor = self.image_processor
66
+
67
+ def __call__(
68
+ self,
69
+ images: ImageInput = None,
70
+ text: Optional[Union[str, List[str], TextInput, PreTokenizedInput]] = None,
71
+ audio=None,
72
+ videos=None,
73
+ **kwargs: Unpack[BlipProcessorKwargs],
74
+ ) -> BatchEncoding:
75
+ """
76
+ This method uses [`BlipImageProcessor.__call__`] method to prepare image(s) for the model, and
77
+ [`BertTokenizerFast.__call__`] to prepare text for the model.
78
+
79
+ Please refer to the docstring of the above two methods for more information.
80
+ Args:
81
+ images (`ImageInput`):
82
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
83
+ tensor. Both channels-first and channels-last formats are supported.
84
+ text (`TextInput`, `PreTokenizedInput`, `List[TextInput]`, `List[PreTokenizedInput]`):
85
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
86
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
87
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
88
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
89
+ If set, will return tensors of a particular framework. Acceptable values are:
90
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
91
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
92
+ - `'np'`: Return NumPy `np.ndarray` objects.
93
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
94
+ """
95
+ if images is None and text is None:
96
+ raise ValueError("You have to specify either images or text.")
97
+
98
+ text_encoding = None
99
+
100
+ # add pixel_values encoding. If we also have text_encoding, update image encoding and return it.
101
+ # else, return the text encoding.
102
+ output_kwargs = self._merge_kwargs(
103
+ BlipProcessorKwargs,
104
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
105
+ **kwargs,
106
+ )
107
+ if text is not None:
108
+ text_encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
109
+ if images is not None:
110
+ encoding_image_processor = self.image_processor(images, **output_kwargs["images_kwargs"])
111
+
112
+ if text_encoding is not None:
113
+ encoding_image_processor.update(text_encoding)
114
+ return encoding_image_processor
115
+
116
+ return text_encoding
117
+
118
+ def batch_decode(self, *args, **kwargs):
119
+ """
120
+ This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
121
+ refer to the docstring of this method for more information.
122
+ """
123
+ return self.tokenizer.batch_decode(*args, **kwargs)
124
+
125
+ def decode(self, *args, **kwargs):
126
+ """
127
+ This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
128
+ the docstring of this method for more information.
129
+ """
130
+ return self.tokenizer.decode(*args, **kwargs)
131
+
132
+ @property
133
+ def model_input_names(self):
134
+ tokenizer_input_names = self.tokenizer.model_input_names
135
+ image_processor_input_names = self.image_processor.model_input_names
136
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
137
+
138
+
139
+ __all__ = ["BlipProcessor"]