ZTWHHH commited on
Commit
01b1814
·
verified ·
1 Parent(s): 68d875b

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. janus/lib/python3.10/site-packages/transformers/models/bart/__pycache__/__init__.cpython-310.pyc +0 -0
  2. janus/lib/python3.10/site-packages/transformers/models/bert/__init__.py +32 -0
  3. janus/lib/python3.10/site-packages/transformers/models/bert/__pycache__/tokenization_bert.cpython-310.pyc +0 -0
  4. janus/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py +2009 -0
  5. janus/lib/python3.10/site-packages/transformers/models/bert/modeling_flax_bert.py +1727 -0
  6. janus/lib/python3.10/site-packages/transformers/models/bert/tokenization_bert_fast.py +175 -0
  7. janus/lib/python3.10/site-packages/transformers/models/blip/__pycache__/__init__.cpython-310.pyc +0 -0
  8. janus/lib/python3.10/site-packages/transformers/models/blip/__pycache__/modeling_blip_text.cpython-310.pyc +0 -0
  9. janus/lib/python3.10/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip.cpython-310.pyc +0 -0
  10. janus/lib/python3.10/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip_text.cpython-310.pyc +0 -0
  11. janus/lib/python3.10/site-packages/transformers/models/blip/image_processing_blip.py +297 -0
  12. janus/lib/python3.10/site-packages/transformers/models/blip/modeling_blip.py +1596 -0
  13. janus/lib/python3.10/site-packages/transformers/models/blip/modeling_tf_blip.py +1709 -0
  14. janus/lib/python3.10/site-packages/transformers/models/decision_transformer/__init__.py +27 -0
  15. janus/lib/python3.10/site-packages/transformers/models/decision_transformer/__pycache__/modeling_decision_transformer.cpython-310.pyc +0 -0
  16. janus/lib/python3.10/site-packages/transformers/models/decision_transformer/modeling_decision_transformer.py +963 -0
  17. janus/lib/python3.10/site-packages/transformers/models/ernie/__init__.py +27 -0
  18. janus/lib/python3.10/site-packages/transformers/models/ernie/__pycache__/__init__.cpython-310.pyc +0 -0
  19. janus/lib/python3.10/site-packages/transformers/models/ernie/__pycache__/configuration_ernie.cpython-310.pyc +0 -0
  20. janus/lib/python3.10/site-packages/transformers/models/ernie/__pycache__/modeling_ernie.cpython-310.pyc +0 -0
  21. janus/lib/python3.10/site-packages/transformers/models/ernie/configuration_ernie.py +163 -0
  22. janus/lib/python3.10/site-packages/transformers/models/ernie/modeling_ernie.py +1815 -0
  23. janus/lib/python3.10/site-packages/transformers/models/falcon/__init__.py +27 -0
  24. janus/lib/python3.10/site-packages/transformers/models/falcon/__pycache__/configuration_falcon.cpython-310.pyc +0 -0
  25. janus/lib/python3.10/site-packages/transformers/models/fuyu/__pycache__/__init__.cpython-310.pyc +0 -0
  26. janus/lib/python3.10/site-packages/transformers/models/fuyu/__pycache__/modeling_fuyu.cpython-310.pyc +0 -0
  27. janus/lib/python3.10/site-packages/transformers/models/fuyu/__pycache__/processing_fuyu.cpython-310.pyc +0 -0
  28. janus/lib/python3.10/site-packages/transformers/models/fuyu/configuration_fuyu.py +210 -0
  29. janus/lib/python3.10/site-packages/transformers/models/longformer/__init__.py +30 -0
  30. janus/lib/python3.10/site-packages/transformers/models/longformer/__pycache__/modeling_longformer.cpython-310.pyc +0 -0
  31. janus/lib/python3.10/site-packages/transformers/models/longformer/modeling_tf_longformer.py +0 -0
  32. janus/lib/python3.10/site-packages/transformers/models/longformer/tokenization_longformer.py +402 -0
  33. janus/lib/python3.10/site-packages/transformers/models/longformer/tokenization_longformer_fast.py +265 -0
  34. janus/lib/python3.10/site-packages/transformers/models/mixtral/__init__.py +66 -0
  35. janus/lib/python3.10/site-packages/transformers/models/mixtral/__pycache__/__init__.cpython-310.pyc +0 -0
  36. janus/lib/python3.10/site-packages/transformers/models/mixtral/__pycache__/configuration_mixtral.cpython-310.pyc +0 -0
  37. janus/lib/python3.10/site-packages/transformers/models/mixtral/__pycache__/modeling_mixtral.cpython-310.pyc +0 -0
  38. janus/lib/python3.10/site-packages/transformers/models/mixtral/configuration_mixtral.py +173 -0
  39. janus/lib/python3.10/site-packages/transformers/models/mixtral/modular_mixtral.py +574 -0
  40. janus/lib/python3.10/site-packages/transformers/models/musicgen/__init__.py +28 -0
  41. janus/lib/python3.10/site-packages/transformers/models/musicgen/__pycache__/__init__.cpython-310.pyc +0 -0
  42. janus/lib/python3.10/site-packages/transformers/models/musicgen/__pycache__/configuration_musicgen.cpython-310.pyc +0 -0
  43. janus/lib/python3.10/site-packages/transformers/models/musicgen/__pycache__/modeling_musicgen.cpython-310.pyc +0 -0
  44. janus/lib/python3.10/site-packages/transformers/models/musicgen/__pycache__/processing_musicgen.cpython-310.pyc +0 -0
  45. janus/lib/python3.10/site-packages/transformers/models/musicgen/configuration_musicgen.py +247 -0
  46. janus/lib/python3.10/site-packages/transformers/models/musicgen/modeling_musicgen.py +0 -0
  47. janus/lib/python3.10/site-packages/transformers/models/musicgen/processing_musicgen.py +144 -0
  48. janus/lib/python3.10/site-packages/transformers/models/paligemma/__init__.py +28 -0
  49. janus/lib/python3.10/site-packages/transformers/models/paligemma/__pycache__/configuration_paligemma.cpython-310.pyc +0 -0
  50. janus/lib/python3.10/site-packages/transformers/models/paligemma/modeling_paligemma.py +623 -0
janus/lib/python3.10/site-packages/transformers/models/bart/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (652 Bytes). View file
 
janus/lib/python3.10/site-packages/transformers/models/bert/__init__.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_bert import *
22
+ from .modeling_bert import *
23
+ from .modeling_flax_bert import *
24
+ from .modeling_tf_bert import *
25
+ from .tokenization_bert import *
26
+ from .tokenization_bert_fast import *
27
+ from .tokenization_bert_tf import *
28
+ else:
29
+ import sys
30
+
31
+ _file = globals()["__file__"]
32
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
janus/lib/python3.10/site-packages/transformers/models/bert/__pycache__/tokenization_bert.cpython-310.pyc ADDED
Binary file (17.2 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py ADDED
@@ -0,0 +1,2009 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch BERT model."""
17
+
18
+ import math
19
+ import os
20
+ import warnings
21
+ from dataclasses import dataclass
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from packaging import version
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from ...activations import ACT2FN
31
+ from ...generation import GenerationMixin
32
+ from ...modeling_attn_mask_utils import (
33
+ _prepare_4d_attention_mask_for_sdpa,
34
+ _prepare_4d_causal_attention_mask_for_sdpa,
35
+ )
36
+ from ...modeling_outputs import (
37
+ BaseModelOutputWithPastAndCrossAttentions,
38
+ BaseModelOutputWithPoolingAndCrossAttentions,
39
+ CausalLMOutputWithCrossAttentions,
40
+ MaskedLMOutput,
41
+ MultipleChoiceModelOutput,
42
+ NextSentencePredictorOutput,
43
+ QuestionAnsweringModelOutput,
44
+ SequenceClassifierOutput,
45
+ TokenClassifierOutput,
46
+ )
47
+ from ...modeling_utils import PreTrainedModel
48
+ from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
49
+ from ...utils import (
50
+ ModelOutput,
51
+ add_code_sample_docstrings,
52
+ add_start_docstrings,
53
+ add_start_docstrings_to_model_forward,
54
+ get_torch_version,
55
+ logging,
56
+ replace_return_docstrings,
57
+ )
58
+ from .configuration_bert import BertConfig
59
+
60
+
61
+ logger = logging.get_logger(__name__)
62
+
63
+ _CHECKPOINT_FOR_DOC = "google-bert/bert-base-uncased"
64
+ _CONFIG_FOR_DOC = "BertConfig"
65
+
66
+ # TokenClassification docstring
67
+ _CHECKPOINT_FOR_TOKEN_CLASSIFICATION = "dbmdz/bert-large-cased-finetuned-conll03-english"
68
+ _TOKEN_CLASS_EXPECTED_OUTPUT = (
69
+ "['O', 'I-ORG', 'I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC'] "
70
+ )
71
+ _TOKEN_CLASS_EXPECTED_LOSS = 0.01
72
+
73
+ # QuestionAnswering docstring
74
+ _CHECKPOINT_FOR_QA = "deepset/bert-base-cased-squad2"
75
+ _QA_EXPECTED_OUTPUT = "'a nice puppet'"
76
+ _QA_EXPECTED_LOSS = 7.41
77
+ _QA_TARGET_START_INDEX = 14
78
+ _QA_TARGET_END_INDEX = 15
79
+
80
+ # SequenceClassification docstring
81
+ _CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "textattack/bert-base-uncased-yelp-polarity"
82
+ _SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_1'"
83
+ _SEQ_CLASS_EXPECTED_LOSS = 0.01
84
+
85
+
86
+ def load_tf_weights_in_bert(model, config, tf_checkpoint_path):
87
+ """Load tf checkpoints in a pytorch model."""
88
+ try:
89
+ import re
90
+
91
+ import numpy as np
92
+ import tensorflow as tf
93
+ except ImportError:
94
+ logger.error(
95
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
96
+ "https://www.tensorflow.org/install/ for installation instructions."
97
+ )
98
+ raise
99
+ tf_path = os.path.abspath(tf_checkpoint_path)
100
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
101
+ # Load weights from TF model
102
+ init_vars = tf.train.list_variables(tf_path)
103
+ names = []
104
+ arrays = []
105
+ for name, shape in init_vars:
106
+ logger.info(f"Loading TF weight {name} with shape {shape}")
107
+ array = tf.train.load_variable(tf_path, name)
108
+ names.append(name)
109
+ arrays.append(array)
110
+
111
+ for name, array in zip(names, arrays):
112
+ name = name.split("/")
113
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
114
+ # which are not required for using pretrained model
115
+ if any(
116
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
117
+ for n in name
118
+ ):
119
+ logger.info(f"Skipping {'/'.join(name)}")
120
+ continue
121
+ pointer = model
122
+ for m_name in name:
123
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
124
+ scope_names = re.split(r"_(\d+)", m_name)
125
+ else:
126
+ scope_names = [m_name]
127
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
128
+ pointer = getattr(pointer, "weight")
129
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
130
+ pointer = getattr(pointer, "bias")
131
+ elif scope_names[0] == "output_weights":
132
+ pointer = getattr(pointer, "weight")
133
+ elif scope_names[0] == "squad":
134
+ pointer = getattr(pointer, "classifier")
135
+ else:
136
+ try:
137
+ pointer = getattr(pointer, scope_names[0])
138
+ except AttributeError:
139
+ logger.info(f"Skipping {'/'.join(name)}")
140
+ continue
141
+ if len(scope_names) >= 2:
142
+ num = int(scope_names[1])
143
+ pointer = pointer[num]
144
+ if m_name[-11:] == "_embeddings":
145
+ pointer = getattr(pointer, "weight")
146
+ elif m_name == "kernel":
147
+ array = np.transpose(array)
148
+ try:
149
+ if pointer.shape != array.shape:
150
+ raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
151
+ except ValueError as e:
152
+ e.args += (pointer.shape, array.shape)
153
+ raise
154
+ logger.info(f"Initialize PyTorch weight {name}")
155
+ pointer.data = torch.from_numpy(array)
156
+ return model
157
+
158
+
159
+ class BertEmbeddings(nn.Module):
160
+ """Construct the embeddings from word, position and token_type embeddings."""
161
+
162
+ def __init__(self, config):
163
+ super().__init__()
164
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
165
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
166
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
167
+
168
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
169
+ # any TensorFlow checkpoint file
170
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
171
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
172
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
173
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
174
+ self.register_buffer(
175
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
176
+ )
177
+ self.register_buffer(
178
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
179
+ )
180
+
181
+ def forward(
182
+ self,
183
+ input_ids: Optional[torch.LongTensor] = None,
184
+ token_type_ids: Optional[torch.LongTensor] = None,
185
+ position_ids: Optional[torch.LongTensor] = None,
186
+ inputs_embeds: Optional[torch.FloatTensor] = None,
187
+ past_key_values_length: int = 0,
188
+ ) -> torch.Tensor:
189
+ if input_ids is not None:
190
+ input_shape = input_ids.size()
191
+ else:
192
+ input_shape = inputs_embeds.size()[:-1]
193
+
194
+ seq_length = input_shape[1]
195
+
196
+ if position_ids is None:
197
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
198
+
199
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
200
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
201
+ # issue #5664
202
+ if token_type_ids is None:
203
+ if hasattr(self, "token_type_ids"):
204
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
205
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
206
+ token_type_ids = buffered_token_type_ids_expanded
207
+ else:
208
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
209
+
210
+ if inputs_embeds is None:
211
+ inputs_embeds = self.word_embeddings(input_ids)
212
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
213
+
214
+ embeddings = inputs_embeds + token_type_embeddings
215
+ if self.position_embedding_type == "absolute":
216
+ position_embeddings = self.position_embeddings(position_ids)
217
+ embeddings += position_embeddings
218
+ embeddings = self.LayerNorm(embeddings)
219
+ embeddings = self.dropout(embeddings)
220
+ return embeddings
221
+
222
+
223
+ class BertSelfAttention(nn.Module):
224
+ def __init__(self, config, position_embedding_type=None):
225
+ super().__init__()
226
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
227
+ raise ValueError(
228
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
229
+ f"heads ({config.num_attention_heads})"
230
+ )
231
+
232
+ self.num_attention_heads = config.num_attention_heads
233
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
234
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
235
+
236
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
237
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
238
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
239
+
240
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
241
+ self.position_embedding_type = position_embedding_type or getattr(
242
+ config, "position_embedding_type", "absolute"
243
+ )
244
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
245
+ self.max_position_embeddings = config.max_position_embeddings
246
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
247
+
248
+ self.is_decoder = config.is_decoder
249
+
250
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
251
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
252
+ x = x.view(new_x_shape)
253
+ return x.permute(0, 2, 1, 3)
254
+
255
+ def forward(
256
+ self,
257
+ hidden_states: torch.Tensor,
258
+ attention_mask: Optional[torch.FloatTensor] = None,
259
+ head_mask: Optional[torch.FloatTensor] = None,
260
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
261
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
262
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
263
+ output_attentions: Optional[bool] = False,
264
+ ) -> Tuple[torch.Tensor]:
265
+ mixed_query_layer = self.query(hidden_states)
266
+
267
+ # If this is instantiated as a cross-attention module, the keys
268
+ # and values come from an encoder; the attention mask needs to be
269
+ # such that the encoder's padding tokens are not attended to.
270
+ is_cross_attention = encoder_hidden_states is not None
271
+
272
+ if is_cross_attention and past_key_value is not None:
273
+ # reuse k,v, cross_attentions
274
+ key_layer = past_key_value[0]
275
+ value_layer = past_key_value[1]
276
+ attention_mask = encoder_attention_mask
277
+ elif is_cross_attention:
278
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
279
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
280
+ attention_mask = encoder_attention_mask
281
+ elif past_key_value is not None:
282
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
283
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
284
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
285
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
286
+ else:
287
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
288
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
289
+
290
+ query_layer = self.transpose_for_scores(mixed_query_layer)
291
+
292
+ use_cache = past_key_value is not None
293
+ if self.is_decoder:
294
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
295
+ # Further calls to cross_attention layer can then reuse all cross-attention
296
+ # key/value_states (first "if" case)
297
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
298
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
299
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
300
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
301
+ past_key_value = (key_layer, value_layer)
302
+
303
+ # Take the dot product between "query" and "key" to get the raw attention scores.
304
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
305
+
306
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
307
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
308
+ if use_cache:
309
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
310
+ -1, 1
311
+ )
312
+ else:
313
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
314
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
315
+ distance = position_ids_l - position_ids_r
316
+
317
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
318
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
319
+
320
+ if self.position_embedding_type == "relative_key":
321
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
322
+ attention_scores = attention_scores + relative_position_scores
323
+ elif self.position_embedding_type == "relative_key_query":
324
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
325
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
326
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
327
+
328
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
329
+ if attention_mask is not None:
330
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
331
+ attention_scores = attention_scores + attention_mask
332
+
333
+ # Normalize the attention scores to probabilities.
334
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
335
+
336
+ # This is actually dropping out entire tokens to attend to, which might
337
+ # seem a bit unusual, but is taken from the original Transformer paper.
338
+ attention_probs = self.dropout(attention_probs)
339
+
340
+ # Mask heads if we want to
341
+ if head_mask is not None:
342
+ attention_probs = attention_probs * head_mask
343
+
344
+ context_layer = torch.matmul(attention_probs, value_layer)
345
+
346
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
347
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
348
+ context_layer = context_layer.view(new_context_layer_shape)
349
+
350
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
351
+
352
+ if self.is_decoder:
353
+ outputs = outputs + (past_key_value,)
354
+ return outputs
355
+
356
+
357
+ class BertSdpaSelfAttention(BertSelfAttention):
358
+ def __init__(self, config, position_embedding_type=None):
359
+ super().__init__(config, position_embedding_type=position_embedding_type)
360
+ self.dropout_prob = config.attention_probs_dropout_prob
361
+ self.require_contiguous_qkv = version.parse(get_torch_version()) < version.parse("2.2.0")
362
+
363
+ # Adapted from BertSelfAttention
364
+ def forward(
365
+ self,
366
+ hidden_states: torch.Tensor,
367
+ attention_mask: Optional[torch.Tensor] = None,
368
+ head_mask: Optional[torch.FloatTensor] = None,
369
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
370
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
371
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
372
+ output_attentions: Optional[bool] = False,
373
+ ) -> Tuple[torch.Tensor]:
374
+ if self.position_embedding_type != "absolute" or output_attentions or head_mask is not None:
375
+ # TODO: Improve this warning with e.g. `model.config._attn_implementation = "manual"` once implemented.
376
+ logger.warning_once(
377
+ "BertSdpaSelfAttention is used but `torch.nn.functional.scaled_dot_product_attention` does not support "
378
+ "non-absolute `position_embedding_type` or `output_attentions=True` or `head_mask`. Falling back to "
379
+ "the manual attention implementation, but specifying the manual implementation will be required from "
380
+ "Transformers version v5.0.0 onwards. This warning can be removed using the argument "
381
+ '`attn_implementation="eager"` when loading the model.'
382
+ )
383
+ return super().forward(
384
+ hidden_states,
385
+ attention_mask,
386
+ head_mask,
387
+ encoder_hidden_states,
388
+ encoder_attention_mask,
389
+ past_key_value,
390
+ output_attentions,
391
+ )
392
+
393
+ bsz, tgt_len, _ = hidden_states.size()
394
+
395
+ query_layer = self.transpose_for_scores(self.query(hidden_states))
396
+
397
+ # If this is instantiated as a cross-attention module, the keys and values come from an encoder; the attention
398
+ # mask needs to be such that the encoder's padding tokens are not attended to.
399
+ is_cross_attention = encoder_hidden_states is not None
400
+
401
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
402
+ attention_mask = encoder_attention_mask if is_cross_attention else attention_mask
403
+
404
+ # Check `seq_length` of `past_key_value` == `len(current_states)` to support prefix tuning
405
+ if is_cross_attention and past_key_value and past_key_value[0].shape[2] == current_states.shape[1]:
406
+ key_layer, value_layer = past_key_value
407
+ else:
408
+ key_layer = self.transpose_for_scores(self.key(current_states))
409
+ value_layer = self.transpose_for_scores(self.value(current_states))
410
+ if past_key_value is not None and not is_cross_attention:
411
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
412
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
413
+
414
+ if self.is_decoder:
415
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
416
+ # Further calls to cross_attention layer can then reuse all cross-attention
417
+ # key/value_states (first "if" case)
418
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
419
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
420
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
421
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
422
+ past_key_value = (key_layer, value_layer)
423
+
424
+ # SDPA with memory-efficient backend is broken in torch==2.1.2 when using non-contiguous inputs and a custom
425
+ # attn_mask, so we need to call `.contiguous()` here. This was fixed in torch==2.2.0.
426
+ # Reference: https://github.com/pytorch/pytorch/issues/112577
427
+ if self.require_contiguous_qkv and query_layer.device.type == "cuda" and attention_mask is not None:
428
+ query_layer = query_layer.contiguous()
429
+ key_layer = key_layer.contiguous()
430
+ value_layer = value_layer.contiguous()
431
+
432
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
433
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
434
+ # The tgt_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create
435
+ # a causal mask in case tgt_len == 1.
436
+ is_causal = (
437
+ True if self.is_decoder and not is_cross_attention and attention_mask is None and tgt_len > 1 else False
438
+ )
439
+
440
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
441
+ query_layer,
442
+ key_layer,
443
+ value_layer,
444
+ attn_mask=attention_mask,
445
+ dropout_p=self.dropout_prob if self.training else 0.0,
446
+ is_causal=is_causal,
447
+ )
448
+
449
+ attn_output = attn_output.transpose(1, 2)
450
+ attn_output = attn_output.reshape(bsz, tgt_len, self.all_head_size)
451
+
452
+ outputs = (attn_output,)
453
+ if self.is_decoder:
454
+ outputs = outputs + (past_key_value,)
455
+ return outputs
456
+
457
+
458
+ class BertSelfOutput(nn.Module):
459
+ def __init__(self, config):
460
+ super().__init__()
461
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
462
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
463
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
464
+
465
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
466
+ hidden_states = self.dense(hidden_states)
467
+ hidden_states = self.dropout(hidden_states)
468
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
469
+ return hidden_states
470
+
471
+
472
+ BERT_SELF_ATTENTION_CLASSES = {
473
+ "eager": BertSelfAttention,
474
+ "sdpa": BertSdpaSelfAttention,
475
+ }
476
+
477
+
478
+ class BertAttention(nn.Module):
479
+ def __init__(self, config, position_embedding_type=None):
480
+ super().__init__()
481
+ self.self = BERT_SELF_ATTENTION_CLASSES[config._attn_implementation](
482
+ config, position_embedding_type=position_embedding_type
483
+ )
484
+ self.output = BertSelfOutput(config)
485
+ self.pruned_heads = set()
486
+
487
+ def prune_heads(self, heads):
488
+ if len(heads) == 0:
489
+ return
490
+ heads, index = find_pruneable_heads_and_indices(
491
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
492
+ )
493
+
494
+ # Prune linear layers
495
+ self.self.query = prune_linear_layer(self.self.query, index)
496
+ self.self.key = prune_linear_layer(self.self.key, index)
497
+ self.self.value = prune_linear_layer(self.self.value, index)
498
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
499
+
500
+ # Update hyper params and store pruned heads
501
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
502
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
503
+ self.pruned_heads = self.pruned_heads.union(heads)
504
+
505
+ def forward(
506
+ self,
507
+ hidden_states: torch.Tensor,
508
+ attention_mask: Optional[torch.FloatTensor] = None,
509
+ head_mask: Optional[torch.FloatTensor] = None,
510
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
511
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
512
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
513
+ output_attentions: Optional[bool] = False,
514
+ ) -> Tuple[torch.Tensor]:
515
+ self_outputs = self.self(
516
+ hidden_states,
517
+ attention_mask,
518
+ head_mask,
519
+ encoder_hidden_states,
520
+ encoder_attention_mask,
521
+ past_key_value,
522
+ output_attentions,
523
+ )
524
+ attention_output = self.output(self_outputs[0], hidden_states)
525
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
526
+ return outputs
527
+
528
+
529
+ class BertIntermediate(nn.Module):
530
+ def __init__(self, config):
531
+ super().__init__()
532
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
533
+ if isinstance(config.hidden_act, str):
534
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
535
+ else:
536
+ self.intermediate_act_fn = config.hidden_act
537
+
538
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
539
+ hidden_states = self.dense(hidden_states)
540
+ hidden_states = self.intermediate_act_fn(hidden_states)
541
+ return hidden_states
542
+
543
+
544
+ class BertOutput(nn.Module):
545
+ def __init__(self, config):
546
+ super().__init__()
547
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
548
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
549
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
550
+
551
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
552
+ hidden_states = self.dense(hidden_states)
553
+ hidden_states = self.dropout(hidden_states)
554
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
555
+ return hidden_states
556
+
557
+
558
+ class BertLayer(nn.Module):
559
+ def __init__(self, config):
560
+ super().__init__()
561
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
562
+ self.seq_len_dim = 1
563
+ self.attention = BertAttention(config)
564
+ self.is_decoder = config.is_decoder
565
+ self.add_cross_attention = config.add_cross_attention
566
+ if self.add_cross_attention:
567
+ if not self.is_decoder:
568
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
569
+ self.crossattention = BertAttention(config, position_embedding_type="absolute")
570
+ self.intermediate = BertIntermediate(config)
571
+ self.output = BertOutput(config)
572
+
573
+ def forward(
574
+ self,
575
+ hidden_states: torch.Tensor,
576
+ attention_mask: Optional[torch.FloatTensor] = None,
577
+ head_mask: Optional[torch.FloatTensor] = None,
578
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
579
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
580
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
581
+ output_attentions: Optional[bool] = False,
582
+ ) -> Tuple[torch.Tensor]:
583
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
584
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
585
+ self_attention_outputs = self.attention(
586
+ hidden_states,
587
+ attention_mask,
588
+ head_mask,
589
+ output_attentions=output_attentions,
590
+ past_key_value=self_attn_past_key_value,
591
+ )
592
+ attention_output = self_attention_outputs[0]
593
+
594
+ # if decoder, the last output is tuple of self-attn cache
595
+ if self.is_decoder:
596
+ outputs = self_attention_outputs[1:-1]
597
+ present_key_value = self_attention_outputs[-1]
598
+ else:
599
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
600
+
601
+ cross_attn_present_key_value = None
602
+ if self.is_decoder and encoder_hidden_states is not None:
603
+ if not hasattr(self, "crossattention"):
604
+ raise ValueError(
605
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
606
+ " by setting `config.add_cross_attention=True`"
607
+ )
608
+
609
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
610
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
611
+ cross_attention_outputs = self.crossattention(
612
+ attention_output,
613
+ attention_mask,
614
+ head_mask,
615
+ encoder_hidden_states,
616
+ encoder_attention_mask,
617
+ cross_attn_past_key_value,
618
+ output_attentions,
619
+ )
620
+ attention_output = cross_attention_outputs[0]
621
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
622
+
623
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
624
+ cross_attn_present_key_value = cross_attention_outputs[-1]
625
+ present_key_value = present_key_value + cross_attn_present_key_value
626
+
627
+ layer_output = apply_chunking_to_forward(
628
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
629
+ )
630
+ outputs = (layer_output,) + outputs
631
+
632
+ # if decoder, return the attn key/values as the last output
633
+ if self.is_decoder:
634
+ outputs = outputs + (present_key_value,)
635
+
636
+ return outputs
637
+
638
+ def feed_forward_chunk(self, attention_output):
639
+ intermediate_output = self.intermediate(attention_output)
640
+ layer_output = self.output(intermediate_output, attention_output)
641
+ return layer_output
642
+
643
+
644
+ class BertEncoder(nn.Module):
645
+ def __init__(self, config):
646
+ super().__init__()
647
+ self.config = config
648
+ self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)])
649
+ self.gradient_checkpointing = False
650
+
651
+ def forward(
652
+ self,
653
+ hidden_states: torch.Tensor,
654
+ attention_mask: Optional[torch.FloatTensor] = None,
655
+ head_mask: Optional[torch.FloatTensor] = None,
656
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
657
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
658
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
659
+ use_cache: Optional[bool] = None,
660
+ output_attentions: Optional[bool] = False,
661
+ output_hidden_states: Optional[bool] = False,
662
+ return_dict: Optional[bool] = True,
663
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
664
+ all_hidden_states = () if output_hidden_states else None
665
+ all_self_attentions = () if output_attentions else None
666
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
667
+
668
+ if self.gradient_checkpointing and self.training:
669
+ if use_cache:
670
+ logger.warning_once(
671
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
672
+ )
673
+ use_cache = False
674
+
675
+ next_decoder_cache = () if use_cache else None
676
+ for i, layer_module in enumerate(self.layer):
677
+ if output_hidden_states:
678
+ all_hidden_states = all_hidden_states + (hidden_states,)
679
+
680
+ layer_head_mask = head_mask[i] if head_mask is not None else None
681
+ past_key_value = past_key_values[i] if past_key_values is not None else None
682
+
683
+ if self.gradient_checkpointing and self.training:
684
+ layer_outputs = self._gradient_checkpointing_func(
685
+ layer_module.__call__,
686
+ hidden_states,
687
+ attention_mask,
688
+ layer_head_mask,
689
+ encoder_hidden_states,
690
+ encoder_attention_mask,
691
+ past_key_value,
692
+ output_attentions,
693
+ )
694
+ else:
695
+ layer_outputs = layer_module(
696
+ hidden_states,
697
+ attention_mask,
698
+ layer_head_mask,
699
+ encoder_hidden_states,
700
+ encoder_attention_mask,
701
+ past_key_value,
702
+ output_attentions,
703
+ )
704
+
705
+ hidden_states = layer_outputs[0]
706
+ if use_cache:
707
+ next_decoder_cache += (layer_outputs[-1],)
708
+ if output_attentions:
709
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
710
+ if self.config.add_cross_attention:
711
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
712
+
713
+ if output_hidden_states:
714
+ all_hidden_states = all_hidden_states + (hidden_states,)
715
+
716
+ if not return_dict:
717
+ return tuple(
718
+ v
719
+ for v in [
720
+ hidden_states,
721
+ next_decoder_cache,
722
+ all_hidden_states,
723
+ all_self_attentions,
724
+ all_cross_attentions,
725
+ ]
726
+ if v is not None
727
+ )
728
+ return BaseModelOutputWithPastAndCrossAttentions(
729
+ last_hidden_state=hidden_states,
730
+ past_key_values=next_decoder_cache,
731
+ hidden_states=all_hidden_states,
732
+ attentions=all_self_attentions,
733
+ cross_attentions=all_cross_attentions,
734
+ )
735
+
736
+
737
+ class BertPooler(nn.Module):
738
+ def __init__(self, config):
739
+ super().__init__()
740
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
741
+ self.activation = nn.Tanh()
742
+
743
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
744
+ # We "pool" the model by simply taking the hidden state corresponding
745
+ # to the first token.
746
+ first_token_tensor = hidden_states[:, 0]
747
+ pooled_output = self.dense(first_token_tensor)
748
+ pooled_output = self.activation(pooled_output)
749
+ return pooled_output
750
+
751
+
752
+ class BertPredictionHeadTransform(nn.Module):
753
+ def __init__(self, config):
754
+ super().__init__()
755
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
756
+ if isinstance(config.hidden_act, str):
757
+ self.transform_act_fn = ACT2FN[config.hidden_act]
758
+ else:
759
+ self.transform_act_fn = config.hidden_act
760
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
761
+
762
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
763
+ hidden_states = self.dense(hidden_states)
764
+ hidden_states = self.transform_act_fn(hidden_states)
765
+ hidden_states = self.LayerNorm(hidden_states)
766
+ return hidden_states
767
+
768
+
769
+ class BertLMPredictionHead(nn.Module):
770
+ def __init__(self, config):
771
+ super().__init__()
772
+ self.transform = BertPredictionHeadTransform(config)
773
+
774
+ # The output weights are the same as the input embeddings, but there is
775
+ # an output-only bias for each token.
776
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
777
+
778
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
779
+
780
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
781
+ self.decoder.bias = self.bias
782
+
783
+ def _tie_weights(self):
784
+ self.decoder.bias = self.bias
785
+
786
+ def forward(self, hidden_states):
787
+ hidden_states = self.transform(hidden_states)
788
+ hidden_states = self.decoder(hidden_states)
789
+ return hidden_states
790
+
791
+
792
+ class BertOnlyMLMHead(nn.Module):
793
+ def __init__(self, config):
794
+ super().__init__()
795
+ self.predictions = BertLMPredictionHead(config)
796
+
797
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
798
+ prediction_scores = self.predictions(sequence_output)
799
+ return prediction_scores
800
+
801
+
802
+ class BertOnlyNSPHead(nn.Module):
803
+ def __init__(self, config):
804
+ super().__init__()
805
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
806
+
807
+ def forward(self, pooled_output):
808
+ seq_relationship_score = self.seq_relationship(pooled_output)
809
+ return seq_relationship_score
810
+
811
+
812
+ class BertPreTrainingHeads(nn.Module):
813
+ def __init__(self, config):
814
+ super().__init__()
815
+ self.predictions = BertLMPredictionHead(config)
816
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
817
+
818
+ def forward(self, sequence_output, pooled_output):
819
+ prediction_scores = self.predictions(sequence_output)
820
+ seq_relationship_score = self.seq_relationship(pooled_output)
821
+ return prediction_scores, seq_relationship_score
822
+
823
+
824
+ class BertPreTrainedModel(PreTrainedModel):
825
+ """
826
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
827
+ models.
828
+ """
829
+
830
+ config_class = BertConfig
831
+ load_tf_weights = load_tf_weights_in_bert
832
+ base_model_prefix = "bert"
833
+ supports_gradient_checkpointing = True
834
+ _supports_sdpa = True
835
+
836
+ def _init_weights(self, module):
837
+ """Initialize the weights"""
838
+ if isinstance(module, nn.Linear):
839
+ # Slightly different from the TF version which uses truncated_normal for initialization
840
+ # cf https://github.com/pytorch/pytorch/pull/5617
841
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
842
+ if module.bias is not None:
843
+ module.bias.data.zero_()
844
+ elif isinstance(module, nn.Embedding):
845
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
846
+ if module.padding_idx is not None:
847
+ module.weight.data[module.padding_idx].zero_()
848
+ elif isinstance(module, nn.LayerNorm):
849
+ module.bias.data.zero_()
850
+ module.weight.data.fill_(1.0)
851
+
852
+
853
+ @dataclass
854
+ class BertForPreTrainingOutput(ModelOutput):
855
+ """
856
+ Output type of [`BertForPreTraining`].
857
+
858
+ Args:
859
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
860
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
861
+ (classification) loss.
862
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
863
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
864
+ seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
865
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
866
+ before SoftMax).
867
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
868
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
869
+ shape `(batch_size, sequence_length, hidden_size)`.
870
+
871
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
872
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
873
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
874
+ sequence_length)`.
875
+
876
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
877
+ heads.
878
+ """
879
+
880
+ loss: Optional[torch.FloatTensor] = None
881
+ prediction_logits: torch.FloatTensor = None
882
+ seq_relationship_logits: torch.FloatTensor = None
883
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
884
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
885
+
886
+
887
+ BERT_START_DOCSTRING = r"""
888
+
889
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
890
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
891
+ etc.)
892
+
893
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
894
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
895
+ and behavior.
896
+
897
+ Parameters:
898
+ config ([`BertConfig`]): Model configuration class with all the parameters of the model.
899
+ Initializing with a config file does not load the weights associated with the model, only the
900
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
901
+ """
902
+
903
+ BERT_INPUTS_DOCSTRING = r"""
904
+ Args:
905
+ input_ids (`torch.LongTensor` of shape `({0})`):
906
+ Indices of input sequence tokens in the vocabulary.
907
+
908
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
909
+ [`PreTrainedTokenizer.__call__`] for details.
910
+
911
+ [What are input IDs?](../glossary#input-ids)
912
+ attention_mask (`torch.FloatTensor` of shape `({0})`or `(batch_size, sequence_length, target_length)`, *optional*):
913
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
914
+
915
+ - 1 for tokens that are **not masked**,
916
+ - 0 for tokens that are **masked**.
917
+
918
+ [What are attention masks?](../glossary#attention-mask)
919
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
920
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
921
+ 1]`:
922
+
923
+ - 0 corresponds to a *sentence A* token,
924
+ - 1 corresponds to a *sentence B* token.
925
+
926
+ [What are token type IDs?](../glossary#token-type-ids)
927
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
928
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
929
+ config.max_position_embeddings - 1]`.
930
+
931
+ [What are position IDs?](../glossary#position-ids)
932
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
933
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
934
+
935
+ - 1 indicates the head is **not masked**,
936
+ - 0 indicates the head is **masked**.
937
+
938
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
939
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
940
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
941
+ model's internal embedding lookup matrix.
942
+ output_attentions (`bool`, *optional*):
943
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
944
+ tensors for more detail.
945
+ output_hidden_states (`bool`, *optional*):
946
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
947
+ more detail.
948
+ return_dict (`bool`, *optional*):
949
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
950
+ """
951
+
952
+
953
+ @add_start_docstrings(
954
+ "The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
955
+ BERT_START_DOCSTRING,
956
+ )
957
+ class BertModel(BertPreTrainedModel):
958
+ """
959
+
960
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
961
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
962
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
963
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
964
+
965
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
966
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
967
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
968
+ """
969
+
970
+ _no_split_modules = ["BertEmbeddings", "BertLayer"]
971
+
972
+ def __init__(self, config, add_pooling_layer=True):
973
+ super().__init__(config)
974
+ self.config = config
975
+
976
+ self.embeddings = BertEmbeddings(config)
977
+ self.encoder = BertEncoder(config)
978
+
979
+ self.pooler = BertPooler(config) if add_pooling_layer else None
980
+
981
+ self.attn_implementation = config._attn_implementation
982
+ self.position_embedding_type = config.position_embedding_type
983
+
984
+ # Initialize weights and apply final processing
985
+ self.post_init()
986
+
987
+ def get_input_embeddings(self):
988
+ return self.embeddings.word_embeddings
989
+
990
+ def set_input_embeddings(self, value):
991
+ self.embeddings.word_embeddings = value
992
+
993
+ def _prune_heads(self, heads_to_prune):
994
+ """
995
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
996
+ class PreTrainedModel
997
+ """
998
+ for layer, heads in heads_to_prune.items():
999
+ self.encoder.layer[layer].attention.prune_heads(heads)
1000
+
1001
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1002
+ @add_code_sample_docstrings(
1003
+ checkpoint=_CHECKPOINT_FOR_DOC,
1004
+ output_type=BaseModelOutputWithPoolingAndCrossAttentions,
1005
+ config_class=_CONFIG_FOR_DOC,
1006
+ )
1007
+ def forward(
1008
+ self,
1009
+ input_ids: Optional[torch.Tensor] = None,
1010
+ attention_mask: Optional[torch.Tensor] = None,
1011
+ token_type_ids: Optional[torch.Tensor] = None,
1012
+ position_ids: Optional[torch.Tensor] = None,
1013
+ head_mask: Optional[torch.Tensor] = None,
1014
+ inputs_embeds: Optional[torch.Tensor] = None,
1015
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1016
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1017
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1018
+ use_cache: Optional[bool] = None,
1019
+ output_attentions: Optional[bool] = None,
1020
+ output_hidden_states: Optional[bool] = None,
1021
+ return_dict: Optional[bool] = None,
1022
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
1023
+ r"""
1024
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1025
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1026
+ the model is configured as a decoder.
1027
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, target_length)`, *optional*):
1028
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1029
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1030
+
1031
+ - 1 for tokens that are **not masked**,
1032
+ - 0 for tokens that are **masked**.
1033
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
1034
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1035
+
1036
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1037
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1038
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1039
+ use_cache (`bool`, *optional*):
1040
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1041
+ `past_key_values`).
1042
+ """
1043
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1044
+ output_hidden_states = (
1045
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1046
+ )
1047
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1048
+
1049
+ if self.config.is_decoder:
1050
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1051
+ else:
1052
+ use_cache = False
1053
+
1054
+ if input_ids is not None and inputs_embeds is not None:
1055
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1056
+ elif input_ids is not None:
1057
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
1058
+ input_shape = input_ids.size()
1059
+ elif inputs_embeds is not None:
1060
+ input_shape = inputs_embeds.size()[:-1]
1061
+ else:
1062
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1063
+
1064
+ batch_size, seq_length = input_shape
1065
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1066
+
1067
+ # past_key_values_length
1068
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
1069
+
1070
+ if token_type_ids is None:
1071
+ if hasattr(self.embeddings, "token_type_ids"):
1072
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
1073
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
1074
+ token_type_ids = buffered_token_type_ids_expanded
1075
+ else:
1076
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
1077
+
1078
+ embedding_output = self.embeddings(
1079
+ input_ids=input_ids,
1080
+ position_ids=position_ids,
1081
+ token_type_ids=token_type_ids,
1082
+ inputs_embeds=inputs_embeds,
1083
+ past_key_values_length=past_key_values_length,
1084
+ )
1085
+
1086
+ if attention_mask is None:
1087
+ attention_mask = torch.ones((batch_size, seq_length + past_key_values_length), device=device)
1088
+
1089
+ use_sdpa_attention_masks = (
1090
+ self.attn_implementation == "sdpa"
1091
+ and self.position_embedding_type == "absolute"
1092
+ and head_mask is None
1093
+ and not output_attentions
1094
+ )
1095
+
1096
+ # Expand the attention mask
1097
+ if use_sdpa_attention_masks and attention_mask.dim() == 2:
1098
+ # Expand the attention mask for SDPA.
1099
+ # [bsz, seq_len] -> [bsz, 1, seq_len, seq_len]
1100
+ if self.config.is_decoder:
1101
+ extended_attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1102
+ attention_mask,
1103
+ input_shape,
1104
+ embedding_output,
1105
+ past_key_values_length,
1106
+ )
1107
+ else:
1108
+ extended_attention_mask = _prepare_4d_attention_mask_for_sdpa(
1109
+ attention_mask, embedding_output.dtype, tgt_len=seq_length
1110
+ )
1111
+ else:
1112
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
1113
+ # ourselves in which case we just need to make it broadcastable to all heads.
1114
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
1115
+
1116
+ # If a 2D or 3D attention mask is provided for the cross-attention
1117
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
1118
+ if self.config.is_decoder and encoder_hidden_states is not None:
1119
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
1120
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
1121
+ if encoder_attention_mask is None:
1122
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
1123
+
1124
+ if use_sdpa_attention_masks and encoder_attention_mask.dim() == 2:
1125
+ # Expand the attention mask for SDPA.
1126
+ # [bsz, seq_len] -> [bsz, 1, seq_len, seq_len]
1127
+ encoder_extended_attention_mask = _prepare_4d_attention_mask_for_sdpa(
1128
+ encoder_attention_mask, embedding_output.dtype, tgt_len=seq_length
1129
+ )
1130
+ else:
1131
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
1132
+ else:
1133
+ encoder_extended_attention_mask = None
1134
+
1135
+ # Prepare head mask if needed
1136
+ # 1.0 in head_mask indicate we keep the head
1137
+ # attention_probs has shape bsz x n_heads x N x N
1138
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
1139
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
1140
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
1141
+
1142
+ encoder_outputs = self.encoder(
1143
+ embedding_output,
1144
+ attention_mask=extended_attention_mask,
1145
+ head_mask=head_mask,
1146
+ encoder_hidden_states=encoder_hidden_states,
1147
+ encoder_attention_mask=encoder_extended_attention_mask,
1148
+ past_key_values=past_key_values,
1149
+ use_cache=use_cache,
1150
+ output_attentions=output_attentions,
1151
+ output_hidden_states=output_hidden_states,
1152
+ return_dict=return_dict,
1153
+ )
1154
+ sequence_output = encoder_outputs[0]
1155
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
1156
+
1157
+ if not return_dict:
1158
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
1159
+
1160
+ return BaseModelOutputWithPoolingAndCrossAttentions(
1161
+ last_hidden_state=sequence_output,
1162
+ pooler_output=pooled_output,
1163
+ past_key_values=encoder_outputs.past_key_values,
1164
+ hidden_states=encoder_outputs.hidden_states,
1165
+ attentions=encoder_outputs.attentions,
1166
+ cross_attentions=encoder_outputs.cross_attentions,
1167
+ )
1168
+
1169
+
1170
+ @add_start_docstrings(
1171
+ """
1172
+ Bert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
1173
+ sentence prediction (classification)` head.
1174
+ """,
1175
+ BERT_START_DOCSTRING,
1176
+ )
1177
+ class BertForPreTraining(BertPreTrainedModel):
1178
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
1179
+
1180
+ def __init__(self, config):
1181
+ super().__init__(config)
1182
+
1183
+ self.bert = BertModel(config)
1184
+ self.cls = BertPreTrainingHeads(config)
1185
+
1186
+ # Initialize weights and apply final processing
1187
+ self.post_init()
1188
+
1189
+ def get_output_embeddings(self):
1190
+ return self.cls.predictions.decoder
1191
+
1192
+ def set_output_embeddings(self, new_embeddings):
1193
+ self.cls.predictions.decoder = new_embeddings
1194
+ self.cls.predictions.bias = new_embeddings.bias
1195
+
1196
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1197
+ @replace_return_docstrings(output_type=BertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
1198
+ def forward(
1199
+ self,
1200
+ input_ids: Optional[torch.Tensor] = None,
1201
+ attention_mask: Optional[torch.Tensor] = None,
1202
+ token_type_ids: Optional[torch.Tensor] = None,
1203
+ position_ids: Optional[torch.Tensor] = None,
1204
+ head_mask: Optional[torch.Tensor] = None,
1205
+ inputs_embeds: Optional[torch.Tensor] = None,
1206
+ labels: Optional[torch.Tensor] = None,
1207
+ next_sentence_label: Optional[torch.Tensor] = None,
1208
+ output_attentions: Optional[bool] = None,
1209
+ output_hidden_states: Optional[bool] = None,
1210
+ return_dict: Optional[bool] = None,
1211
+ ) -> Union[Tuple[torch.Tensor], BertForPreTrainingOutput]:
1212
+ r"""
1213
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1214
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1215
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
1216
+ the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1217
+ next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1218
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
1219
+ pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
1220
+
1221
+ - 0 indicates sequence B is a continuation of sequence A,
1222
+ - 1 indicates sequence B is a random sequence.
1223
+ kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
1224
+ Used to hide legacy arguments that have been deprecated.
1225
+
1226
+ Returns:
1227
+
1228
+ Example:
1229
+
1230
+ ```python
1231
+ >>> from transformers import AutoTokenizer, BertForPreTraining
1232
+ >>> import torch
1233
+
1234
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
1235
+ >>> model = BertForPreTraining.from_pretrained("google-bert/bert-base-uncased")
1236
+
1237
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1238
+ >>> outputs = model(**inputs)
1239
+
1240
+ >>> prediction_logits = outputs.prediction_logits
1241
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
1242
+ ```
1243
+ """
1244
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1245
+
1246
+ outputs = self.bert(
1247
+ input_ids,
1248
+ attention_mask=attention_mask,
1249
+ token_type_ids=token_type_ids,
1250
+ position_ids=position_ids,
1251
+ head_mask=head_mask,
1252
+ inputs_embeds=inputs_embeds,
1253
+ output_attentions=output_attentions,
1254
+ output_hidden_states=output_hidden_states,
1255
+ return_dict=return_dict,
1256
+ )
1257
+
1258
+ sequence_output, pooled_output = outputs[:2]
1259
+ prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
1260
+
1261
+ total_loss = None
1262
+ if labels is not None and next_sentence_label is not None:
1263
+ loss_fct = CrossEntropyLoss()
1264
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1265
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
1266
+ total_loss = masked_lm_loss + next_sentence_loss
1267
+
1268
+ if not return_dict:
1269
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
1270
+ return ((total_loss,) + output) if total_loss is not None else output
1271
+
1272
+ return BertForPreTrainingOutput(
1273
+ loss=total_loss,
1274
+ prediction_logits=prediction_scores,
1275
+ seq_relationship_logits=seq_relationship_score,
1276
+ hidden_states=outputs.hidden_states,
1277
+ attentions=outputs.attentions,
1278
+ )
1279
+
1280
+
1281
+ @add_start_docstrings(
1282
+ """Bert Model with a `language modeling` head on top for CLM fine-tuning.""", BERT_START_DOCSTRING
1283
+ )
1284
+ class BertLMHeadModel(BertPreTrainedModel, GenerationMixin):
1285
+ _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
1286
+
1287
+ def __init__(self, config):
1288
+ super().__init__(config)
1289
+
1290
+ if not config.is_decoder:
1291
+ logger.warning("If you want to use `BertLMHeadModel` as a standalone, add `is_decoder=True.`")
1292
+
1293
+ self.bert = BertModel(config, add_pooling_layer=False)
1294
+ self.cls = BertOnlyMLMHead(config)
1295
+
1296
+ # Initialize weights and apply final processing
1297
+ self.post_init()
1298
+
1299
+ def get_output_embeddings(self):
1300
+ return self.cls.predictions.decoder
1301
+
1302
+ def set_output_embeddings(self, new_embeddings):
1303
+ self.cls.predictions.decoder = new_embeddings
1304
+ self.cls.predictions.bias = new_embeddings.bias
1305
+
1306
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1307
+ @add_code_sample_docstrings(
1308
+ checkpoint=_CHECKPOINT_FOR_DOC,
1309
+ output_type=CausalLMOutputWithCrossAttentions,
1310
+ config_class=_CONFIG_FOR_DOC,
1311
+ )
1312
+ def forward(
1313
+ self,
1314
+ input_ids: Optional[torch.Tensor] = None,
1315
+ attention_mask: Optional[torch.Tensor] = None,
1316
+ token_type_ids: Optional[torch.Tensor] = None,
1317
+ position_ids: Optional[torch.Tensor] = None,
1318
+ head_mask: Optional[torch.Tensor] = None,
1319
+ inputs_embeds: Optional[torch.Tensor] = None,
1320
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1321
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1322
+ labels: Optional[torch.Tensor] = None,
1323
+ past_key_values: Optional[List[torch.Tensor]] = None,
1324
+ use_cache: Optional[bool] = None,
1325
+ output_attentions: Optional[bool] = None,
1326
+ output_hidden_states: Optional[bool] = None,
1327
+ return_dict: Optional[bool] = None,
1328
+ **loss_kwargs,
1329
+ ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
1330
+ r"""
1331
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1332
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1333
+ the model is configured as a decoder.
1334
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1335
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1336
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1337
+
1338
+ - 1 for tokens that are **not masked**,
1339
+ - 0 for tokens that are **masked**.
1340
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1341
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1342
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
1343
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
1344
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
1345
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1346
+
1347
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1348
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1349
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1350
+ use_cache (`bool`, *optional*):
1351
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1352
+ `past_key_values`).
1353
+ """
1354
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1355
+ if labels is not None:
1356
+ use_cache = False
1357
+
1358
+ outputs = self.bert(
1359
+ input_ids,
1360
+ attention_mask=attention_mask,
1361
+ token_type_ids=token_type_ids,
1362
+ position_ids=position_ids,
1363
+ head_mask=head_mask,
1364
+ inputs_embeds=inputs_embeds,
1365
+ encoder_hidden_states=encoder_hidden_states,
1366
+ encoder_attention_mask=encoder_attention_mask,
1367
+ past_key_values=past_key_values,
1368
+ use_cache=use_cache,
1369
+ output_attentions=output_attentions,
1370
+ output_hidden_states=output_hidden_states,
1371
+ return_dict=return_dict,
1372
+ )
1373
+
1374
+ sequence_output = outputs[0]
1375
+ prediction_scores = self.cls(sequence_output)
1376
+
1377
+ lm_loss = None
1378
+ if labels is not None:
1379
+ lm_loss = self.loss_function(prediction_scores, labels, self.config.vocab_size, **loss_kwargs)
1380
+
1381
+ if not return_dict:
1382
+ output = (prediction_scores,) + outputs[2:]
1383
+ return ((lm_loss,) + output) if lm_loss is not None else output
1384
+
1385
+ return CausalLMOutputWithCrossAttentions(
1386
+ loss=lm_loss,
1387
+ logits=prediction_scores,
1388
+ past_key_values=outputs.past_key_values,
1389
+ hidden_states=outputs.hidden_states,
1390
+ attentions=outputs.attentions,
1391
+ cross_attentions=outputs.cross_attentions,
1392
+ )
1393
+
1394
+ def _reorder_cache(self, past_key_values, beam_idx):
1395
+ reordered_past = ()
1396
+ for layer_past in past_key_values:
1397
+ reordered_past += (
1398
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1399
+ )
1400
+ return reordered_past
1401
+
1402
+
1403
+ @add_start_docstrings("""Bert Model with a `language modeling` head on top.""", BERT_START_DOCSTRING)
1404
+ class BertForMaskedLM(BertPreTrainedModel):
1405
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
1406
+
1407
+ def __init__(self, config):
1408
+ super().__init__(config)
1409
+
1410
+ if config.is_decoder:
1411
+ logger.warning(
1412
+ "If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for "
1413
+ "bi-directional self-attention."
1414
+ )
1415
+
1416
+ self.bert = BertModel(config, add_pooling_layer=False)
1417
+ self.cls = BertOnlyMLMHead(config)
1418
+
1419
+ # Initialize weights and apply final processing
1420
+ self.post_init()
1421
+
1422
+ def get_output_embeddings(self):
1423
+ return self.cls.predictions.decoder
1424
+
1425
+ def set_output_embeddings(self, new_embeddings):
1426
+ self.cls.predictions.decoder = new_embeddings
1427
+ self.cls.predictions.bias = new_embeddings.bias
1428
+
1429
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1430
+ @add_code_sample_docstrings(
1431
+ checkpoint=_CHECKPOINT_FOR_DOC,
1432
+ output_type=MaskedLMOutput,
1433
+ config_class=_CONFIG_FOR_DOC,
1434
+ expected_output="'paris'",
1435
+ expected_loss=0.88,
1436
+ )
1437
+ def forward(
1438
+ self,
1439
+ input_ids: Optional[torch.Tensor] = None,
1440
+ attention_mask: Optional[torch.Tensor] = None,
1441
+ token_type_ids: Optional[torch.Tensor] = None,
1442
+ position_ids: Optional[torch.Tensor] = None,
1443
+ head_mask: Optional[torch.Tensor] = None,
1444
+ inputs_embeds: Optional[torch.Tensor] = None,
1445
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1446
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1447
+ labels: Optional[torch.Tensor] = None,
1448
+ output_attentions: Optional[bool] = None,
1449
+ output_hidden_states: Optional[bool] = None,
1450
+ return_dict: Optional[bool] = None,
1451
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
1452
+ r"""
1453
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1454
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1455
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1456
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1457
+ """
1458
+
1459
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1460
+
1461
+ outputs = self.bert(
1462
+ input_ids,
1463
+ attention_mask=attention_mask,
1464
+ token_type_ids=token_type_ids,
1465
+ position_ids=position_ids,
1466
+ head_mask=head_mask,
1467
+ inputs_embeds=inputs_embeds,
1468
+ encoder_hidden_states=encoder_hidden_states,
1469
+ encoder_attention_mask=encoder_attention_mask,
1470
+ output_attentions=output_attentions,
1471
+ output_hidden_states=output_hidden_states,
1472
+ return_dict=return_dict,
1473
+ )
1474
+
1475
+ sequence_output = outputs[0]
1476
+ prediction_scores = self.cls(sequence_output)
1477
+
1478
+ masked_lm_loss = None
1479
+ if labels is not None:
1480
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1481
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1482
+
1483
+ if not return_dict:
1484
+ output = (prediction_scores,) + outputs[2:]
1485
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1486
+
1487
+ return MaskedLMOutput(
1488
+ loss=masked_lm_loss,
1489
+ logits=prediction_scores,
1490
+ hidden_states=outputs.hidden_states,
1491
+ attentions=outputs.attentions,
1492
+ )
1493
+
1494
+ def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
1495
+ input_shape = input_ids.shape
1496
+ effective_batch_size = input_shape[0]
1497
+
1498
+ # add a dummy token
1499
+ if self.config.pad_token_id is None:
1500
+ raise ValueError("The PAD token should be defined for generation")
1501
+
1502
+ attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
1503
+ dummy_token = torch.full(
1504
+ (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
1505
+ )
1506
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
1507
+
1508
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
1509
+
1510
+
1511
+ @add_start_docstrings(
1512
+ """Bert Model with a `next sentence prediction (classification)` head on top.""",
1513
+ BERT_START_DOCSTRING,
1514
+ )
1515
+ class BertForNextSentencePrediction(BertPreTrainedModel):
1516
+ def __init__(self, config):
1517
+ super().__init__(config)
1518
+
1519
+ self.bert = BertModel(config)
1520
+ self.cls = BertOnlyNSPHead(config)
1521
+
1522
+ # Initialize weights and apply final processing
1523
+ self.post_init()
1524
+
1525
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1526
+ @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
1527
+ def forward(
1528
+ self,
1529
+ input_ids: Optional[torch.Tensor] = None,
1530
+ attention_mask: Optional[torch.Tensor] = None,
1531
+ token_type_ids: Optional[torch.Tensor] = None,
1532
+ position_ids: Optional[torch.Tensor] = None,
1533
+ head_mask: Optional[torch.Tensor] = None,
1534
+ inputs_embeds: Optional[torch.Tensor] = None,
1535
+ labels: Optional[torch.Tensor] = None,
1536
+ output_attentions: Optional[bool] = None,
1537
+ output_hidden_states: Optional[bool] = None,
1538
+ return_dict: Optional[bool] = None,
1539
+ **kwargs,
1540
+ ) -> Union[Tuple[torch.Tensor], NextSentencePredictorOutput]:
1541
+ r"""
1542
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1543
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
1544
+ (see `input_ids` docstring). Indices should be in `[0, 1]`:
1545
+
1546
+ - 0 indicates sequence B is a continuation of sequence A,
1547
+ - 1 indicates sequence B is a random sequence.
1548
+
1549
+ Returns:
1550
+
1551
+ Example:
1552
+
1553
+ ```python
1554
+ >>> from transformers import AutoTokenizer, BertForNextSentencePrediction
1555
+ >>> import torch
1556
+
1557
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
1558
+ >>> model = BertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")
1559
+
1560
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1561
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
1562
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
1563
+
1564
+ >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
1565
+ >>> logits = outputs.logits
1566
+ >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
1567
+ ```
1568
+ """
1569
+
1570
+ if "next_sentence_label" in kwargs:
1571
+ warnings.warn(
1572
+ "The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
1573
+ " `labels` instead.",
1574
+ FutureWarning,
1575
+ )
1576
+ labels = kwargs.pop("next_sentence_label")
1577
+
1578
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1579
+
1580
+ outputs = self.bert(
1581
+ input_ids,
1582
+ attention_mask=attention_mask,
1583
+ token_type_ids=token_type_ids,
1584
+ position_ids=position_ids,
1585
+ head_mask=head_mask,
1586
+ inputs_embeds=inputs_embeds,
1587
+ output_attentions=output_attentions,
1588
+ output_hidden_states=output_hidden_states,
1589
+ return_dict=return_dict,
1590
+ )
1591
+
1592
+ pooled_output = outputs[1]
1593
+
1594
+ seq_relationship_scores = self.cls(pooled_output)
1595
+
1596
+ next_sentence_loss = None
1597
+ if labels is not None:
1598
+ loss_fct = CrossEntropyLoss()
1599
+ next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
1600
+
1601
+ if not return_dict:
1602
+ output = (seq_relationship_scores,) + outputs[2:]
1603
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
1604
+
1605
+ return NextSentencePredictorOutput(
1606
+ loss=next_sentence_loss,
1607
+ logits=seq_relationship_scores,
1608
+ hidden_states=outputs.hidden_states,
1609
+ attentions=outputs.attentions,
1610
+ )
1611
+
1612
+
1613
+ @add_start_docstrings(
1614
+ """
1615
+ Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
1616
+ output) e.g. for GLUE tasks.
1617
+ """,
1618
+ BERT_START_DOCSTRING,
1619
+ )
1620
+ class BertForSequenceClassification(BertPreTrainedModel):
1621
+ def __init__(self, config):
1622
+ super().__init__(config)
1623
+ self.num_labels = config.num_labels
1624
+ self.config = config
1625
+
1626
+ self.bert = BertModel(config)
1627
+ classifier_dropout = (
1628
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1629
+ )
1630
+ self.dropout = nn.Dropout(classifier_dropout)
1631
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1632
+
1633
+ # Initialize weights and apply final processing
1634
+ self.post_init()
1635
+
1636
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1637
+ @add_code_sample_docstrings(
1638
+ checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION,
1639
+ output_type=SequenceClassifierOutput,
1640
+ config_class=_CONFIG_FOR_DOC,
1641
+ expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,
1642
+ expected_loss=_SEQ_CLASS_EXPECTED_LOSS,
1643
+ )
1644
+ def forward(
1645
+ self,
1646
+ input_ids: Optional[torch.Tensor] = None,
1647
+ attention_mask: Optional[torch.Tensor] = None,
1648
+ token_type_ids: Optional[torch.Tensor] = None,
1649
+ position_ids: Optional[torch.Tensor] = None,
1650
+ head_mask: Optional[torch.Tensor] = None,
1651
+ inputs_embeds: Optional[torch.Tensor] = None,
1652
+ labels: Optional[torch.Tensor] = None,
1653
+ output_attentions: Optional[bool] = None,
1654
+ output_hidden_states: Optional[bool] = None,
1655
+ return_dict: Optional[bool] = None,
1656
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
1657
+ r"""
1658
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1659
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1660
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1661
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1662
+ """
1663
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1664
+
1665
+ outputs = self.bert(
1666
+ input_ids,
1667
+ attention_mask=attention_mask,
1668
+ token_type_ids=token_type_ids,
1669
+ position_ids=position_ids,
1670
+ head_mask=head_mask,
1671
+ inputs_embeds=inputs_embeds,
1672
+ output_attentions=output_attentions,
1673
+ output_hidden_states=output_hidden_states,
1674
+ return_dict=return_dict,
1675
+ )
1676
+
1677
+ pooled_output = outputs[1]
1678
+
1679
+ pooled_output = self.dropout(pooled_output)
1680
+ logits = self.classifier(pooled_output)
1681
+
1682
+ loss = None
1683
+ if labels is not None:
1684
+ if self.config.problem_type is None:
1685
+ if self.num_labels == 1:
1686
+ self.config.problem_type = "regression"
1687
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1688
+ self.config.problem_type = "single_label_classification"
1689
+ else:
1690
+ self.config.problem_type = "multi_label_classification"
1691
+
1692
+ if self.config.problem_type == "regression":
1693
+ loss_fct = MSELoss()
1694
+ if self.num_labels == 1:
1695
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1696
+ else:
1697
+ loss = loss_fct(logits, labels)
1698
+ elif self.config.problem_type == "single_label_classification":
1699
+ loss_fct = CrossEntropyLoss()
1700
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1701
+ elif self.config.problem_type == "multi_label_classification":
1702
+ loss_fct = BCEWithLogitsLoss()
1703
+ loss = loss_fct(logits, labels)
1704
+ if not return_dict:
1705
+ output = (logits,) + outputs[2:]
1706
+ return ((loss,) + output) if loss is not None else output
1707
+
1708
+ return SequenceClassifierOutput(
1709
+ loss=loss,
1710
+ logits=logits,
1711
+ hidden_states=outputs.hidden_states,
1712
+ attentions=outputs.attentions,
1713
+ )
1714
+
1715
+
1716
+ @add_start_docstrings(
1717
+ """
1718
+ Bert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1719
+ softmax) e.g. for RocStories/SWAG tasks.
1720
+ """,
1721
+ BERT_START_DOCSTRING,
1722
+ )
1723
+ class BertForMultipleChoice(BertPreTrainedModel):
1724
+ def __init__(self, config):
1725
+ super().__init__(config)
1726
+
1727
+ self.bert = BertModel(config)
1728
+ classifier_dropout = (
1729
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1730
+ )
1731
+ self.dropout = nn.Dropout(classifier_dropout)
1732
+ self.classifier = nn.Linear(config.hidden_size, 1)
1733
+
1734
+ # Initialize weights and apply final processing
1735
+ self.post_init()
1736
+
1737
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
1738
+ @add_code_sample_docstrings(
1739
+ checkpoint=_CHECKPOINT_FOR_DOC,
1740
+ output_type=MultipleChoiceModelOutput,
1741
+ config_class=_CONFIG_FOR_DOC,
1742
+ )
1743
+ def forward(
1744
+ self,
1745
+ input_ids: Optional[torch.Tensor] = None,
1746
+ attention_mask: Optional[torch.Tensor] = None,
1747
+ token_type_ids: Optional[torch.Tensor] = None,
1748
+ position_ids: Optional[torch.Tensor] = None,
1749
+ head_mask: Optional[torch.Tensor] = None,
1750
+ inputs_embeds: Optional[torch.Tensor] = None,
1751
+ labels: Optional[torch.Tensor] = None,
1752
+ output_attentions: Optional[bool] = None,
1753
+ output_hidden_states: Optional[bool] = None,
1754
+ return_dict: Optional[bool] = None,
1755
+ ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
1756
+ r"""
1757
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1758
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1759
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1760
+ `input_ids` above)
1761
+ """
1762
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1763
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1764
+
1765
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1766
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1767
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1768
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
1769
+ inputs_embeds = (
1770
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1771
+ if inputs_embeds is not None
1772
+ else None
1773
+ )
1774
+
1775
+ outputs = self.bert(
1776
+ input_ids,
1777
+ attention_mask=attention_mask,
1778
+ token_type_ids=token_type_ids,
1779
+ position_ids=position_ids,
1780
+ head_mask=head_mask,
1781
+ inputs_embeds=inputs_embeds,
1782
+ output_attentions=output_attentions,
1783
+ output_hidden_states=output_hidden_states,
1784
+ return_dict=return_dict,
1785
+ )
1786
+
1787
+ pooled_output = outputs[1]
1788
+
1789
+ pooled_output = self.dropout(pooled_output)
1790
+ logits = self.classifier(pooled_output)
1791
+ reshaped_logits = logits.view(-1, num_choices)
1792
+
1793
+ loss = None
1794
+ if labels is not None:
1795
+ loss_fct = CrossEntropyLoss()
1796
+ loss = loss_fct(reshaped_logits, labels)
1797
+
1798
+ if not return_dict:
1799
+ output = (reshaped_logits,) + outputs[2:]
1800
+ return ((loss,) + output) if loss is not None else output
1801
+
1802
+ return MultipleChoiceModelOutput(
1803
+ loss=loss,
1804
+ logits=reshaped_logits,
1805
+ hidden_states=outputs.hidden_states,
1806
+ attentions=outputs.attentions,
1807
+ )
1808
+
1809
+
1810
+ @add_start_docstrings(
1811
+ """
1812
+ Bert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1813
+ Named-Entity-Recognition (NER) tasks.
1814
+ """,
1815
+ BERT_START_DOCSTRING,
1816
+ )
1817
+ class BertForTokenClassification(BertPreTrainedModel):
1818
+ def __init__(self, config):
1819
+ super().__init__(config)
1820
+ self.num_labels = config.num_labels
1821
+
1822
+ self.bert = BertModel(config, add_pooling_layer=False)
1823
+ classifier_dropout = (
1824
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1825
+ )
1826
+ self.dropout = nn.Dropout(classifier_dropout)
1827
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1828
+
1829
+ # Initialize weights and apply final processing
1830
+ self.post_init()
1831
+
1832
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1833
+ @add_code_sample_docstrings(
1834
+ checkpoint=_CHECKPOINT_FOR_TOKEN_CLASSIFICATION,
1835
+ output_type=TokenClassifierOutput,
1836
+ config_class=_CONFIG_FOR_DOC,
1837
+ expected_output=_TOKEN_CLASS_EXPECTED_OUTPUT,
1838
+ expected_loss=_TOKEN_CLASS_EXPECTED_LOSS,
1839
+ )
1840
+ def forward(
1841
+ self,
1842
+ input_ids: Optional[torch.Tensor] = None,
1843
+ attention_mask: Optional[torch.Tensor] = None,
1844
+ token_type_ids: Optional[torch.Tensor] = None,
1845
+ position_ids: Optional[torch.Tensor] = None,
1846
+ head_mask: Optional[torch.Tensor] = None,
1847
+ inputs_embeds: Optional[torch.Tensor] = None,
1848
+ labels: Optional[torch.Tensor] = None,
1849
+ output_attentions: Optional[bool] = None,
1850
+ output_hidden_states: Optional[bool] = None,
1851
+ return_dict: Optional[bool] = None,
1852
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1853
+ r"""
1854
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1855
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1856
+ """
1857
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1858
+
1859
+ outputs = self.bert(
1860
+ input_ids,
1861
+ attention_mask=attention_mask,
1862
+ token_type_ids=token_type_ids,
1863
+ position_ids=position_ids,
1864
+ head_mask=head_mask,
1865
+ inputs_embeds=inputs_embeds,
1866
+ output_attentions=output_attentions,
1867
+ output_hidden_states=output_hidden_states,
1868
+ return_dict=return_dict,
1869
+ )
1870
+
1871
+ sequence_output = outputs[0]
1872
+
1873
+ sequence_output = self.dropout(sequence_output)
1874
+ logits = self.classifier(sequence_output)
1875
+
1876
+ loss = None
1877
+ if labels is not None:
1878
+ loss_fct = CrossEntropyLoss()
1879
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1880
+
1881
+ if not return_dict:
1882
+ output = (logits,) + outputs[2:]
1883
+ return ((loss,) + output) if loss is not None else output
1884
+
1885
+ return TokenClassifierOutput(
1886
+ loss=loss,
1887
+ logits=logits,
1888
+ hidden_states=outputs.hidden_states,
1889
+ attentions=outputs.attentions,
1890
+ )
1891
+
1892
+
1893
+ @add_start_docstrings(
1894
+ """
1895
+ Bert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1896
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1897
+ """,
1898
+ BERT_START_DOCSTRING,
1899
+ )
1900
+ class BertForQuestionAnswering(BertPreTrainedModel):
1901
+ def __init__(self, config):
1902
+ super().__init__(config)
1903
+ self.num_labels = config.num_labels
1904
+
1905
+ self.bert = BertModel(config, add_pooling_layer=False)
1906
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1907
+
1908
+ # Initialize weights and apply final processing
1909
+ self.post_init()
1910
+
1911
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1912
+ @add_code_sample_docstrings(
1913
+ checkpoint=_CHECKPOINT_FOR_QA,
1914
+ output_type=QuestionAnsweringModelOutput,
1915
+ config_class=_CONFIG_FOR_DOC,
1916
+ qa_target_start_index=_QA_TARGET_START_INDEX,
1917
+ qa_target_end_index=_QA_TARGET_END_INDEX,
1918
+ expected_output=_QA_EXPECTED_OUTPUT,
1919
+ expected_loss=_QA_EXPECTED_LOSS,
1920
+ )
1921
+ def forward(
1922
+ self,
1923
+ input_ids: Optional[torch.Tensor] = None,
1924
+ attention_mask: Optional[torch.Tensor] = None,
1925
+ token_type_ids: Optional[torch.Tensor] = None,
1926
+ position_ids: Optional[torch.Tensor] = None,
1927
+ head_mask: Optional[torch.Tensor] = None,
1928
+ inputs_embeds: Optional[torch.Tensor] = None,
1929
+ start_positions: Optional[torch.Tensor] = None,
1930
+ end_positions: Optional[torch.Tensor] = None,
1931
+ output_attentions: Optional[bool] = None,
1932
+ output_hidden_states: Optional[bool] = None,
1933
+ return_dict: Optional[bool] = None,
1934
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
1935
+ r"""
1936
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1937
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1938
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1939
+ are not taken into account for computing the loss.
1940
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1941
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1942
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1943
+ are not taken into account for computing the loss.
1944
+ """
1945
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1946
+
1947
+ outputs = self.bert(
1948
+ input_ids,
1949
+ attention_mask=attention_mask,
1950
+ token_type_ids=token_type_ids,
1951
+ position_ids=position_ids,
1952
+ head_mask=head_mask,
1953
+ inputs_embeds=inputs_embeds,
1954
+ output_attentions=output_attentions,
1955
+ output_hidden_states=output_hidden_states,
1956
+ return_dict=return_dict,
1957
+ )
1958
+
1959
+ sequence_output = outputs[0]
1960
+
1961
+ logits = self.qa_outputs(sequence_output)
1962
+ start_logits, end_logits = logits.split(1, dim=-1)
1963
+ start_logits = start_logits.squeeze(-1).contiguous()
1964
+ end_logits = end_logits.squeeze(-1).contiguous()
1965
+
1966
+ total_loss = None
1967
+ if start_positions is not None and end_positions is not None:
1968
+ # If we are on multi-GPU, split add a dimension
1969
+ if len(start_positions.size()) > 1:
1970
+ start_positions = start_positions.squeeze(-1)
1971
+ if len(end_positions.size()) > 1:
1972
+ end_positions = end_positions.squeeze(-1)
1973
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1974
+ ignored_index = start_logits.size(1)
1975
+ start_positions = start_positions.clamp(0, ignored_index)
1976
+ end_positions = end_positions.clamp(0, ignored_index)
1977
+
1978
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1979
+ start_loss = loss_fct(start_logits, start_positions)
1980
+ end_loss = loss_fct(end_logits, end_positions)
1981
+ total_loss = (start_loss + end_loss) / 2
1982
+
1983
+ if not return_dict:
1984
+ output = (start_logits, end_logits) + outputs[2:]
1985
+ return ((total_loss,) + output) if total_loss is not None else output
1986
+
1987
+ return QuestionAnsweringModelOutput(
1988
+ loss=total_loss,
1989
+ start_logits=start_logits,
1990
+ end_logits=end_logits,
1991
+ hidden_states=outputs.hidden_states,
1992
+ attentions=outputs.attentions,
1993
+ )
1994
+
1995
+
1996
+ __all__ = [
1997
+ "BertForMaskedLM",
1998
+ "BertForMultipleChoice",
1999
+ "BertForNextSentencePrediction",
2000
+ "BertForPreTraining",
2001
+ "BertForQuestionAnswering",
2002
+ "BertForSequenceClassification",
2003
+ "BertForTokenClassification",
2004
+ "BertLayer",
2005
+ "BertLMHeadModel",
2006
+ "BertModel",
2007
+ "BertPreTrainedModel",
2008
+ "load_tf_weights_in_bert",
2009
+ ]
janus/lib/python3.10/site-packages/transformers/models/bert/modeling_flax_bert.py ADDED
@@ -0,0 +1,1727 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Google Flax 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
+ from typing import Callable, Optional, Tuple
17
+
18
+ import flax
19
+ import flax.linen as nn
20
+ import jax
21
+ import jax.numpy as jnp
22
+ import numpy as np
23
+ from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
24
+ from flax.linen import combine_masks, make_causal_mask
25
+ from flax.linen import partitioning as nn_partitioning
26
+ from flax.linen.attention import dot_product_attention_weights
27
+ from flax.traverse_util import flatten_dict, unflatten_dict
28
+ from jax import lax
29
+
30
+ from ...modeling_flax_outputs import (
31
+ FlaxBaseModelOutputWithPastAndCrossAttentions,
32
+ FlaxBaseModelOutputWithPooling,
33
+ FlaxBaseModelOutputWithPoolingAndCrossAttentions,
34
+ FlaxCausalLMOutputWithCrossAttentions,
35
+ FlaxMaskedLMOutput,
36
+ FlaxMultipleChoiceModelOutput,
37
+ FlaxNextSentencePredictorOutput,
38
+ FlaxQuestionAnsweringModelOutput,
39
+ FlaxSequenceClassifierOutput,
40
+ FlaxTokenClassifierOutput,
41
+ )
42
+ from ...modeling_flax_utils import (
43
+ ACT2FN,
44
+ FlaxPreTrainedModel,
45
+ append_call_sample_docstring,
46
+ append_replace_return_docstrings,
47
+ overwrite_call_docstring,
48
+ )
49
+ from ...utils import ModelOutput, add_start_docstrings, add_start_docstrings_to_model_forward, logging
50
+ from .configuration_bert import BertConfig
51
+
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CHECKPOINT_FOR_DOC = "google-bert/bert-base-uncased"
56
+ _CONFIG_FOR_DOC = "BertConfig"
57
+
58
+ remat = nn_partitioning.remat
59
+
60
+
61
+ @flax.struct.dataclass
62
+ class FlaxBertForPreTrainingOutput(ModelOutput):
63
+ """
64
+ Output type of [`BertForPreTraining`].
65
+
66
+ Args:
67
+ prediction_logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.vocab_size)`):
68
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
69
+ seq_relationship_logits (`jnp.ndarray` of shape `(batch_size, 2)`):
70
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
71
+ before SoftMax).
72
+ hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
73
+ Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape
74
+ `(batch_size, sequence_length, hidden_size)`.
75
+
76
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
77
+ attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
78
+ Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
79
+ sequence_length)`.
80
+
81
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
82
+ heads.
83
+ """
84
+
85
+ prediction_logits: jnp.ndarray = None
86
+ seq_relationship_logits: jnp.ndarray = None
87
+ hidden_states: Optional[Tuple[jnp.ndarray]] = None
88
+ attentions: Optional[Tuple[jnp.ndarray]] = None
89
+
90
+
91
+ BERT_START_DOCSTRING = r"""
92
+
93
+ This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
94
+ library implements for all its model (such as downloading, saving and converting weights from PyTorch models)
95
+
96
+ This model is also a
97
+ [flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html) subclass. Use it as
98
+ a regular Flax linen Module and refer to the Flax documentation for all matter related to general usage and
99
+ behavior.
100
+
101
+ Finally, this model supports inherent JAX features such as:
102
+
103
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
104
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
105
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
106
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
107
+
108
+ Parameters:
109
+ config ([`BertConfig`]): Model configuration class with all the parameters of the model.
110
+ Initializing with a config file does not load the weights associated with the model, only the
111
+ configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
112
+ dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
113
+ The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
114
+ `jax.numpy.bfloat16` (on TPUs).
115
+
116
+ This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
117
+ specified all the computation will be performed with the given `dtype`.
118
+
119
+ **Note that this only specifies the dtype of the computation and does not influence the dtype of model
120
+ parameters.**
121
+
122
+ If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
123
+ [`~FlaxPreTrainedModel.to_bf16`].
124
+ dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
125
+ The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
126
+ `jax.numpy.bfloat16` (on TPUs).
127
+
128
+ This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
129
+ specified all the computation will be performed with the given `dtype`.
130
+
131
+ **Note that this only specifies the dtype of the computation and does not influence the dtype of model
132
+ parameters.**
133
+
134
+ If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
135
+ [`~FlaxPreTrainedModel.to_bf16`].
136
+
137
+ """
138
+
139
+ BERT_INPUTS_DOCSTRING = r"""
140
+ Args:
141
+ input_ids (`numpy.ndarray` of shape `({0})`):
142
+ Indices of input sequence tokens in the vocabulary.
143
+
144
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
145
+ [`PreTrainedTokenizer.__call__`] for details.
146
+
147
+ [What are input IDs?](../glossary#input-ids)
148
+ attention_mask (`numpy.ndarray` of shape `({0})`, *optional*):
149
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
150
+
151
+ - 1 for tokens that are **not masked**,
152
+ - 0 for tokens that are **masked**.
153
+
154
+ [What are attention masks?](../glossary#attention-mask)
155
+ token_type_ids (`numpy.ndarray` of shape `({0})`, *optional*):
156
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
157
+ 1]`:
158
+
159
+ - 0 corresponds to a *sentence A* token,
160
+ - 1 corresponds to a *sentence B* token.
161
+
162
+ [What are token type IDs?](../glossary#token-type-ids)
163
+ position_ids (`numpy.ndarray` of shape `({0})`, *optional*):
164
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
165
+ config.max_position_embeddings - 1]`.
166
+ head_mask (`numpy.ndarray` of shape `({0})`, `optional):
167
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
168
+
169
+ - 1 indicates the head is **not masked**,
170
+ - 0 indicates the head is **masked**.
171
+
172
+ return_dict (`bool`, *optional*):
173
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
174
+
175
+ """
176
+
177
+
178
+ class FlaxBertEmbeddings(nn.Module):
179
+ """Construct the embeddings from word, position and token_type embeddings."""
180
+
181
+ config: BertConfig
182
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
183
+
184
+ def setup(self):
185
+ self.word_embeddings = nn.Embed(
186
+ self.config.vocab_size,
187
+ self.config.hidden_size,
188
+ embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
189
+ dtype=self.dtype,
190
+ )
191
+ self.position_embeddings = nn.Embed(
192
+ self.config.max_position_embeddings,
193
+ self.config.hidden_size,
194
+ embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
195
+ dtype=self.dtype,
196
+ )
197
+ self.token_type_embeddings = nn.Embed(
198
+ self.config.type_vocab_size,
199
+ self.config.hidden_size,
200
+ embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
201
+ dtype=self.dtype,
202
+ )
203
+ self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
204
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
205
+
206
+ def __call__(self, input_ids, token_type_ids, position_ids, attention_mask, deterministic: bool = True):
207
+ # Embed
208
+ inputs_embeds = self.word_embeddings(input_ids.astype("i4"))
209
+ position_embeds = self.position_embeddings(position_ids.astype("i4"))
210
+ token_type_embeddings = self.token_type_embeddings(token_type_ids.astype("i4"))
211
+
212
+ # Sum all embeddings
213
+ hidden_states = inputs_embeds + token_type_embeddings + position_embeds
214
+
215
+ # Layer Norm
216
+ hidden_states = self.LayerNorm(hidden_states)
217
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
218
+ return hidden_states
219
+
220
+
221
+ class FlaxBertSelfAttention(nn.Module):
222
+ config: BertConfig
223
+ causal: bool = False
224
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
225
+
226
+ def setup(self):
227
+ self.head_dim = self.config.hidden_size // self.config.num_attention_heads
228
+ if self.config.hidden_size % self.config.num_attention_heads != 0:
229
+ raise ValueError(
230
+ "`config.hidden_size`: {self.config.hidden_size} has to be a multiple of `config.num_attention_heads` "
231
+ " : {self.config.num_attention_heads}"
232
+ )
233
+
234
+ self.query = nn.Dense(
235
+ self.config.hidden_size,
236
+ dtype=self.dtype,
237
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
238
+ )
239
+ self.key = nn.Dense(
240
+ self.config.hidden_size,
241
+ dtype=self.dtype,
242
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
243
+ )
244
+ self.value = nn.Dense(
245
+ self.config.hidden_size,
246
+ dtype=self.dtype,
247
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
248
+ )
249
+
250
+ if self.causal:
251
+ self.causal_mask = make_causal_mask(
252
+ jnp.ones((1, self.config.max_position_embeddings), dtype="bool"), dtype="bool"
253
+ )
254
+
255
+ def _split_heads(self, hidden_states):
256
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.config.num_attention_heads, self.head_dim))
257
+
258
+ def _merge_heads(self, hidden_states):
259
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.config.hidden_size,))
260
+
261
+ @nn.compact
262
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartAttention._concatenate_to_cache
263
+ def _concatenate_to_cache(self, key, value, query, attention_mask):
264
+ """
265
+ This function takes projected key, value states from a single input token and concatenates the states to cached
266
+ states from previous steps. This function is slighly adapted from the official Flax repository:
267
+ https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
268
+ """
269
+ # detect if we're initializing by absence of existing cache data.
270
+ is_initialized = self.has_variable("cache", "cached_key")
271
+ cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
272
+ cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
273
+ cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
274
+
275
+ if is_initialized:
276
+ *batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
277
+ # update key, value caches with our new 1d spatial slices
278
+ cur_index = cache_index.value
279
+ indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
280
+ key = lax.dynamic_update_slice(cached_key.value, key, indices)
281
+ value = lax.dynamic_update_slice(cached_value.value, value, indices)
282
+ cached_key.value = key
283
+ cached_value.value = value
284
+ num_updated_cache_vectors = query.shape[1]
285
+ cache_index.value = cache_index.value + num_updated_cache_vectors
286
+ # 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.
287
+ pad_mask = jnp.broadcast_to(
288
+ jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
289
+ tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
290
+ )
291
+ attention_mask = combine_masks(pad_mask, attention_mask)
292
+ return key, value, attention_mask
293
+
294
+ def __call__(
295
+ self,
296
+ hidden_states,
297
+ attention_mask,
298
+ layer_head_mask,
299
+ key_value_states: Optional[jnp.ndarray] = None,
300
+ init_cache: bool = False,
301
+ deterministic=True,
302
+ output_attentions: bool = False,
303
+ ):
304
+ # if key_value_states are provided this layer is used as a cross-attention layer
305
+ # for the decoder
306
+ is_cross_attention = key_value_states is not None
307
+ batch_size = hidden_states.shape[0]
308
+
309
+ # get query proj
310
+ query_states = self.query(hidden_states)
311
+ # get key, value proj
312
+ if is_cross_attention:
313
+ # cross_attentions
314
+ key_states = self.key(key_value_states)
315
+ value_states = self.value(key_value_states)
316
+ else:
317
+ # self_attention
318
+ key_states = self.key(hidden_states)
319
+ value_states = self.value(hidden_states)
320
+
321
+ query_states = self._split_heads(query_states)
322
+ key_states = self._split_heads(key_states)
323
+ value_states = self._split_heads(value_states)
324
+
325
+ # handle cache prepare causal attention mask
326
+ if self.causal:
327
+ query_length, key_length = query_states.shape[1], key_states.shape[1]
328
+ if self.has_variable("cache", "cached_key"):
329
+ mask_shift = self.variables["cache"]["cache_index"]
330
+ max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
331
+ causal_mask = lax.dynamic_slice(
332
+ self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)
333
+ )
334
+ else:
335
+ causal_mask = self.causal_mask[:, :, :query_length, :key_length]
336
+ causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
337
+
338
+ # combine masks if needed
339
+ if attention_mask is not None and self.causal:
340
+ attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)
341
+ attention_mask = combine_masks(attention_mask, causal_mask)
342
+ elif self.causal:
343
+ attention_mask = causal_mask
344
+ elif attention_mask is not None:
345
+ attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
346
+
347
+ # During fast autoregressive decoding, we feed one position at a time,
348
+ # and cache the keys and values step by step.
349
+ if self.causal and (self.has_variable("cache", "cached_key") or init_cache):
350
+ key_states, value_states, attention_mask = self._concatenate_to_cache(
351
+ key_states, value_states, query_states, attention_mask
352
+ )
353
+
354
+ # Convert the boolean attention mask to an attention bias.
355
+ if attention_mask is not None:
356
+ # attention mask in the form of attention bias
357
+ attention_bias = lax.select(
358
+ attention_mask > 0,
359
+ jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
360
+ jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
361
+ )
362
+ else:
363
+ attention_bias = None
364
+
365
+ dropout_rng = None
366
+ if not deterministic and self.config.attention_probs_dropout_prob > 0.0:
367
+ dropout_rng = self.make_rng("dropout")
368
+
369
+ attn_weights = dot_product_attention_weights(
370
+ query_states,
371
+ key_states,
372
+ bias=attention_bias,
373
+ dropout_rng=dropout_rng,
374
+ dropout_rate=self.config.attention_probs_dropout_prob,
375
+ broadcast_dropout=True,
376
+ deterministic=deterministic,
377
+ dtype=self.dtype,
378
+ precision=None,
379
+ )
380
+
381
+ # Mask heads if we want to
382
+ if layer_head_mask is not None:
383
+ attn_weights = jnp.einsum("...hqk,h->...hqk", attn_weights, layer_head_mask)
384
+
385
+ attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
386
+ attn_output = attn_output.reshape(attn_output.shape[:2] + (-1,))
387
+
388
+ outputs = (attn_output, attn_weights) if output_attentions else (attn_output,)
389
+ return outputs
390
+
391
+
392
+ class FlaxBertSelfOutput(nn.Module):
393
+ config: BertConfig
394
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
395
+
396
+ def setup(self):
397
+ self.dense = nn.Dense(
398
+ self.config.hidden_size,
399
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
400
+ dtype=self.dtype,
401
+ )
402
+ self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
403
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
404
+
405
+ def __call__(self, hidden_states, input_tensor, deterministic: bool = True):
406
+ hidden_states = self.dense(hidden_states)
407
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
408
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
409
+ return hidden_states
410
+
411
+
412
+ class FlaxBertAttention(nn.Module):
413
+ config: BertConfig
414
+ causal: bool = False
415
+ dtype: jnp.dtype = jnp.float32
416
+
417
+ def setup(self):
418
+ self.self = FlaxBertSelfAttention(self.config, causal=self.causal, dtype=self.dtype)
419
+ self.output = FlaxBertSelfOutput(self.config, dtype=self.dtype)
420
+
421
+ def __call__(
422
+ self,
423
+ hidden_states,
424
+ attention_mask,
425
+ layer_head_mask,
426
+ key_value_states=None,
427
+ init_cache=False,
428
+ deterministic=True,
429
+ output_attentions: bool = False,
430
+ ):
431
+ # Attention mask comes in as attention_mask.shape == (*batch_sizes, kv_length)
432
+ # FLAX expects: attention_mask.shape == (*batch_sizes, 1, 1, kv_length) such that it is broadcastable
433
+ # with attn_weights.shape == (*batch_sizes, num_heads, q_length, kv_length)
434
+ attn_outputs = self.self(
435
+ hidden_states,
436
+ attention_mask,
437
+ layer_head_mask=layer_head_mask,
438
+ key_value_states=key_value_states,
439
+ init_cache=init_cache,
440
+ deterministic=deterministic,
441
+ output_attentions=output_attentions,
442
+ )
443
+ attn_output = attn_outputs[0]
444
+ hidden_states = self.output(attn_output, hidden_states, deterministic=deterministic)
445
+
446
+ outputs = (hidden_states,)
447
+
448
+ if output_attentions:
449
+ outputs += (attn_outputs[1],)
450
+
451
+ return outputs
452
+
453
+
454
+ class FlaxBertIntermediate(nn.Module):
455
+ config: BertConfig
456
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
457
+
458
+ def setup(self):
459
+ self.dense = nn.Dense(
460
+ self.config.intermediate_size,
461
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
462
+ dtype=self.dtype,
463
+ )
464
+ self.activation = ACT2FN[self.config.hidden_act]
465
+
466
+ def __call__(self, hidden_states):
467
+ hidden_states = self.dense(hidden_states)
468
+ hidden_states = self.activation(hidden_states)
469
+ return hidden_states
470
+
471
+
472
+ class FlaxBertOutput(nn.Module):
473
+ config: BertConfig
474
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
475
+
476
+ def setup(self):
477
+ self.dense = nn.Dense(
478
+ self.config.hidden_size,
479
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
480
+ dtype=self.dtype,
481
+ )
482
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
483
+ self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
484
+
485
+ def __call__(self, hidden_states, attention_output, deterministic: bool = True):
486
+ hidden_states = self.dense(hidden_states)
487
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
488
+ hidden_states = self.LayerNorm(hidden_states + attention_output)
489
+ return hidden_states
490
+
491
+
492
+ class FlaxBertLayer(nn.Module):
493
+ config: BertConfig
494
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
495
+
496
+ def setup(self):
497
+ self.attention = FlaxBertAttention(self.config, causal=self.config.is_decoder, dtype=self.dtype)
498
+ self.intermediate = FlaxBertIntermediate(self.config, dtype=self.dtype)
499
+ self.output = FlaxBertOutput(self.config, dtype=self.dtype)
500
+ if self.config.add_cross_attention:
501
+ self.crossattention = FlaxBertAttention(self.config, causal=False, dtype=self.dtype)
502
+
503
+ def __call__(
504
+ self,
505
+ hidden_states,
506
+ attention_mask,
507
+ layer_head_mask,
508
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
509
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
510
+ init_cache: bool = False,
511
+ deterministic: bool = True,
512
+ output_attentions: bool = False,
513
+ ):
514
+ # Self Attention
515
+ attention_outputs = self.attention(
516
+ hidden_states,
517
+ attention_mask,
518
+ layer_head_mask=layer_head_mask,
519
+ init_cache=init_cache,
520
+ deterministic=deterministic,
521
+ output_attentions=output_attentions,
522
+ )
523
+ attention_output = attention_outputs[0]
524
+
525
+ # Cross-Attention Block
526
+ if encoder_hidden_states is not None:
527
+ cross_attention_outputs = self.crossattention(
528
+ attention_output,
529
+ attention_mask=encoder_attention_mask,
530
+ layer_head_mask=layer_head_mask,
531
+ key_value_states=encoder_hidden_states,
532
+ deterministic=deterministic,
533
+ output_attentions=output_attentions,
534
+ )
535
+ attention_output = cross_attention_outputs[0]
536
+
537
+ hidden_states = self.intermediate(attention_output)
538
+ hidden_states = self.output(hidden_states, attention_output, deterministic=deterministic)
539
+
540
+ outputs = (hidden_states,)
541
+
542
+ if output_attentions:
543
+ outputs += (attention_outputs[1],)
544
+ if encoder_hidden_states is not None:
545
+ outputs += (cross_attention_outputs[1],)
546
+ return outputs
547
+
548
+
549
+ class FlaxBertLayerCollection(nn.Module):
550
+ config: BertConfig
551
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
552
+ gradient_checkpointing: bool = False
553
+
554
+ def setup(self):
555
+ if self.gradient_checkpointing:
556
+ FlaxBertCheckpointLayer = remat(FlaxBertLayer, static_argnums=(5, 6, 7))
557
+ self.layers = [
558
+ FlaxBertCheckpointLayer(self.config, name=str(i), dtype=self.dtype)
559
+ for i in range(self.config.num_hidden_layers)
560
+ ]
561
+ else:
562
+ self.layers = [
563
+ FlaxBertLayer(self.config, name=str(i), dtype=self.dtype) for i in range(self.config.num_hidden_layers)
564
+ ]
565
+
566
+ def __call__(
567
+ self,
568
+ hidden_states,
569
+ attention_mask,
570
+ head_mask,
571
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
572
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
573
+ init_cache: bool = False,
574
+ deterministic: bool = True,
575
+ output_attentions: bool = False,
576
+ output_hidden_states: bool = False,
577
+ return_dict: bool = True,
578
+ ):
579
+ all_attentions = () if output_attentions else None
580
+ all_hidden_states = () if output_hidden_states else None
581
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
582
+
583
+ # Check if head_mask has a correct number of layers specified if desired
584
+ if head_mask is not None:
585
+ if head_mask.shape[0] != (len(self.layers)):
586
+ raise ValueError(
587
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for "
588
+ f" {head_mask.shape[0]}."
589
+ )
590
+
591
+ for i, layer in enumerate(self.layers):
592
+ if output_hidden_states:
593
+ all_hidden_states += (hidden_states,)
594
+
595
+ layer_outputs = layer(
596
+ hidden_states,
597
+ attention_mask,
598
+ head_mask[i] if head_mask is not None else None,
599
+ encoder_hidden_states,
600
+ encoder_attention_mask,
601
+ init_cache,
602
+ deterministic,
603
+ output_attentions,
604
+ )
605
+
606
+ hidden_states = layer_outputs[0]
607
+
608
+ if output_attentions:
609
+ all_attentions += (layer_outputs[1],)
610
+
611
+ if encoder_hidden_states is not None:
612
+ all_cross_attentions += (layer_outputs[2],)
613
+
614
+ if output_hidden_states:
615
+ all_hidden_states += (hidden_states,)
616
+
617
+ outputs = (hidden_states, all_hidden_states, all_attentions, all_cross_attentions)
618
+
619
+ if not return_dict:
620
+ return tuple(v for v in outputs if v is not None)
621
+
622
+ return FlaxBaseModelOutputWithPastAndCrossAttentions(
623
+ last_hidden_state=hidden_states,
624
+ hidden_states=all_hidden_states,
625
+ attentions=all_attentions,
626
+ cross_attentions=all_cross_attentions,
627
+ )
628
+
629
+
630
+ class FlaxBertEncoder(nn.Module):
631
+ config: BertConfig
632
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
633
+ gradient_checkpointing: bool = False
634
+
635
+ def setup(self):
636
+ self.layer = FlaxBertLayerCollection(
637
+ self.config,
638
+ dtype=self.dtype,
639
+ gradient_checkpointing=self.gradient_checkpointing,
640
+ )
641
+
642
+ def __call__(
643
+ self,
644
+ hidden_states,
645
+ attention_mask,
646
+ head_mask,
647
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
648
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
649
+ init_cache: bool = False,
650
+ deterministic: bool = True,
651
+ output_attentions: bool = False,
652
+ output_hidden_states: bool = False,
653
+ return_dict: bool = True,
654
+ ):
655
+ return self.layer(
656
+ hidden_states,
657
+ attention_mask,
658
+ head_mask=head_mask,
659
+ encoder_hidden_states=encoder_hidden_states,
660
+ encoder_attention_mask=encoder_attention_mask,
661
+ init_cache=init_cache,
662
+ deterministic=deterministic,
663
+ output_attentions=output_attentions,
664
+ output_hidden_states=output_hidden_states,
665
+ return_dict=return_dict,
666
+ )
667
+
668
+
669
+ class FlaxBertPooler(nn.Module):
670
+ config: BertConfig
671
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
672
+
673
+ def setup(self):
674
+ self.dense = nn.Dense(
675
+ self.config.hidden_size,
676
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
677
+ dtype=self.dtype,
678
+ )
679
+
680
+ def __call__(self, hidden_states):
681
+ cls_hidden_state = hidden_states[:, 0]
682
+ cls_hidden_state = self.dense(cls_hidden_state)
683
+ return nn.tanh(cls_hidden_state)
684
+
685
+
686
+ class FlaxBertPredictionHeadTransform(nn.Module):
687
+ config: BertConfig
688
+ dtype: jnp.dtype = jnp.float32
689
+
690
+ def setup(self):
691
+ self.dense = nn.Dense(self.config.hidden_size, dtype=self.dtype)
692
+ self.activation = ACT2FN[self.config.hidden_act]
693
+ self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
694
+
695
+ def __call__(self, hidden_states):
696
+ hidden_states = self.dense(hidden_states)
697
+ hidden_states = self.activation(hidden_states)
698
+ return self.LayerNorm(hidden_states)
699
+
700
+
701
+ class FlaxBertLMPredictionHead(nn.Module):
702
+ config: BertConfig
703
+ dtype: jnp.dtype = jnp.float32
704
+ bias_init: Callable[..., np.ndarray] = jax.nn.initializers.zeros
705
+
706
+ def setup(self):
707
+ self.transform = FlaxBertPredictionHeadTransform(self.config, dtype=self.dtype)
708
+ self.decoder = nn.Dense(self.config.vocab_size, dtype=self.dtype, use_bias=False)
709
+ self.bias = self.param("bias", self.bias_init, (self.config.vocab_size,))
710
+
711
+ def __call__(self, hidden_states, shared_embedding=None):
712
+ hidden_states = self.transform(hidden_states)
713
+
714
+ if shared_embedding is not None:
715
+ hidden_states = self.decoder.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
716
+ else:
717
+ hidden_states = self.decoder(hidden_states)
718
+
719
+ bias = jnp.asarray(self.bias, self.dtype)
720
+ hidden_states += bias
721
+ return hidden_states
722
+
723
+
724
+ class FlaxBertOnlyMLMHead(nn.Module):
725
+ config: BertConfig
726
+ dtype: jnp.dtype = jnp.float32
727
+
728
+ def setup(self):
729
+ self.predictions = FlaxBertLMPredictionHead(self.config, dtype=self.dtype)
730
+
731
+ def __call__(self, hidden_states, shared_embedding=None):
732
+ hidden_states = self.predictions(hidden_states, shared_embedding=shared_embedding)
733
+ return hidden_states
734
+
735
+
736
+ class FlaxBertOnlyNSPHead(nn.Module):
737
+ dtype: jnp.dtype = jnp.float32
738
+
739
+ def setup(self):
740
+ self.seq_relationship = nn.Dense(2, dtype=self.dtype)
741
+
742
+ def __call__(self, pooled_output):
743
+ return self.seq_relationship(pooled_output)
744
+
745
+
746
+ class FlaxBertPreTrainingHeads(nn.Module):
747
+ config: BertConfig
748
+ dtype: jnp.dtype = jnp.float32
749
+
750
+ def setup(self):
751
+ self.predictions = FlaxBertLMPredictionHead(self.config, dtype=self.dtype)
752
+ self.seq_relationship = nn.Dense(2, dtype=self.dtype)
753
+
754
+ def __call__(self, hidden_states, pooled_output, shared_embedding=None):
755
+ prediction_scores = self.predictions(hidden_states, shared_embedding=shared_embedding)
756
+ seq_relationship_score = self.seq_relationship(pooled_output)
757
+ return prediction_scores, seq_relationship_score
758
+
759
+
760
+ class FlaxBertPreTrainedModel(FlaxPreTrainedModel):
761
+ """
762
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
763
+ models.
764
+ """
765
+
766
+ config_class = BertConfig
767
+ base_model_prefix = "bert"
768
+ module_class: nn.Module = None
769
+
770
+ def __init__(
771
+ self,
772
+ config: BertConfig,
773
+ input_shape: Tuple = (1, 1),
774
+ seed: int = 0,
775
+ dtype: jnp.dtype = jnp.float32,
776
+ _do_init: bool = True,
777
+ gradient_checkpointing: bool = False,
778
+ **kwargs,
779
+ ):
780
+ module = self.module_class(
781
+ config=config,
782
+ dtype=dtype,
783
+ gradient_checkpointing=gradient_checkpointing,
784
+ **kwargs,
785
+ )
786
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
787
+
788
+ def enable_gradient_checkpointing(self):
789
+ self._module = self.module_class(
790
+ config=self.config,
791
+ dtype=self.dtype,
792
+ gradient_checkpointing=True,
793
+ )
794
+
795
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
796
+ # init input tensors
797
+ input_ids = jnp.zeros(input_shape, dtype="i4")
798
+ token_type_ids = jnp.zeros_like(input_ids)
799
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_shape)
800
+ attention_mask = jnp.ones_like(input_ids)
801
+ head_mask = jnp.ones((self.config.num_hidden_layers, self.config.num_attention_heads))
802
+
803
+ params_rng, dropout_rng = jax.random.split(rng)
804
+ rngs = {"params": params_rng, "dropout": dropout_rng}
805
+
806
+ if self.config.add_cross_attention:
807
+ encoder_hidden_states = jnp.zeros(input_shape + (self.config.hidden_size,))
808
+ encoder_attention_mask = attention_mask
809
+ module_init_outputs = self.module.init(
810
+ rngs,
811
+ input_ids,
812
+ attention_mask,
813
+ token_type_ids,
814
+ position_ids,
815
+ head_mask,
816
+ encoder_hidden_states,
817
+ encoder_attention_mask,
818
+ return_dict=False,
819
+ )
820
+ else:
821
+ module_init_outputs = self.module.init(
822
+ rngs, input_ids, attention_mask, token_type_ids, position_ids, head_mask, return_dict=False
823
+ )
824
+
825
+ random_params = module_init_outputs["params"]
826
+
827
+ if params is not None:
828
+ random_params = flatten_dict(unfreeze(random_params))
829
+ params = flatten_dict(unfreeze(params))
830
+ for missing_key in self._missing_keys:
831
+ params[missing_key] = random_params[missing_key]
832
+ self._missing_keys = set()
833
+ return freeze(unflatten_dict(params))
834
+ else:
835
+ return random_params
836
+
837
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartDecoderPreTrainedModel.init_cache
838
+ def init_cache(self, batch_size, max_length):
839
+ r"""
840
+ Args:
841
+ batch_size (`int`):
842
+ batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
843
+ max_length (`int`):
844
+ maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
845
+ cache.
846
+ """
847
+ # init input variables to retrieve cache
848
+ input_ids = jnp.ones((batch_size, max_length), dtype="i4")
849
+ attention_mask = jnp.ones_like(input_ids, dtype="i4")
850
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
851
+
852
+ init_variables = self.module.init(
853
+ jax.random.PRNGKey(0), input_ids, attention_mask, position_ids, return_dict=False, init_cache=True
854
+ )
855
+ return unfreeze(init_variables["cache"])
856
+
857
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
858
+ def __call__(
859
+ self,
860
+ input_ids,
861
+ attention_mask=None,
862
+ token_type_ids=None,
863
+ position_ids=None,
864
+ head_mask=None,
865
+ encoder_hidden_states=None,
866
+ encoder_attention_mask=None,
867
+ params: dict = None,
868
+ dropout_rng: jax.random.PRNGKey = None,
869
+ train: bool = False,
870
+ output_attentions: Optional[bool] = None,
871
+ output_hidden_states: Optional[bool] = None,
872
+ return_dict: Optional[bool] = None,
873
+ past_key_values: dict = None,
874
+ ):
875
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
876
+ output_hidden_states = (
877
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
878
+ )
879
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
880
+
881
+ # init input tensors if not passed
882
+ if token_type_ids is None:
883
+ token_type_ids = jnp.zeros_like(input_ids)
884
+
885
+ if position_ids is None:
886
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
887
+
888
+ if attention_mask is None:
889
+ attention_mask = jnp.ones_like(input_ids)
890
+
891
+ if head_mask is None:
892
+ head_mask = jnp.ones((self.config.num_hidden_layers, self.config.num_attention_heads))
893
+
894
+ # Handle any PRNG if needed
895
+ rngs = {}
896
+ if dropout_rng is not None:
897
+ rngs["dropout"] = dropout_rng
898
+
899
+ inputs = {"params": params or self.params}
900
+
901
+ if self.config.add_cross_attention:
902
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be passed
903
+ # down to ensure cache is used. It has to be made sure that cache is marked as mutable so that it can be
904
+ # changed by FlaxBertAttention module
905
+ if past_key_values:
906
+ inputs["cache"] = past_key_values
907
+ mutable = ["cache"]
908
+ else:
909
+ mutable = False
910
+
911
+ outputs = self.module.apply(
912
+ inputs,
913
+ jnp.array(input_ids, dtype="i4"),
914
+ jnp.array(attention_mask, dtype="i4"),
915
+ token_type_ids=jnp.array(token_type_ids, dtype="i4"),
916
+ position_ids=jnp.array(position_ids, dtype="i4"),
917
+ head_mask=jnp.array(head_mask, dtype="i4"),
918
+ encoder_hidden_states=encoder_hidden_states,
919
+ encoder_attention_mask=encoder_attention_mask,
920
+ deterministic=not train,
921
+ output_attentions=output_attentions,
922
+ output_hidden_states=output_hidden_states,
923
+ return_dict=return_dict,
924
+ rngs=rngs,
925
+ mutable=mutable,
926
+ )
927
+
928
+ # add updated cache to model output
929
+ if past_key_values is not None and return_dict:
930
+ outputs, past_key_values = outputs
931
+ outputs["past_key_values"] = unfreeze(past_key_values["cache"])
932
+ return outputs
933
+ elif past_key_values is not None and not return_dict:
934
+ outputs, past_key_values = outputs
935
+ outputs = outputs[:1] + (unfreeze(past_key_values["cache"]),) + outputs[1:]
936
+
937
+ else:
938
+ outputs = self.module.apply(
939
+ inputs,
940
+ jnp.array(input_ids, dtype="i4"),
941
+ jnp.array(attention_mask, dtype="i4"),
942
+ token_type_ids=jnp.array(token_type_ids, dtype="i4"),
943
+ position_ids=jnp.array(position_ids, dtype="i4"),
944
+ head_mask=jnp.array(head_mask, dtype="i4"),
945
+ deterministic=not train,
946
+ output_attentions=output_attentions,
947
+ output_hidden_states=output_hidden_states,
948
+ return_dict=return_dict,
949
+ rngs=rngs,
950
+ )
951
+
952
+ return outputs
953
+
954
+
955
+ class FlaxBertModule(nn.Module):
956
+ config: BertConfig
957
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
958
+ add_pooling_layer: bool = True
959
+ gradient_checkpointing: bool = False
960
+
961
+ def setup(self):
962
+ self.embeddings = FlaxBertEmbeddings(self.config, dtype=self.dtype)
963
+ self.encoder = FlaxBertEncoder(
964
+ self.config,
965
+ dtype=self.dtype,
966
+ gradient_checkpointing=self.gradient_checkpointing,
967
+ )
968
+ self.pooler = FlaxBertPooler(self.config, dtype=self.dtype)
969
+
970
+ def __call__(
971
+ self,
972
+ input_ids,
973
+ attention_mask,
974
+ token_type_ids: Optional[jnp.ndarray] = None,
975
+ position_ids: Optional[jnp.ndarray] = None,
976
+ head_mask: Optional[jnp.ndarray] = None,
977
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
978
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
979
+ init_cache: bool = False,
980
+ deterministic: bool = True,
981
+ output_attentions: bool = False,
982
+ output_hidden_states: bool = False,
983
+ return_dict: bool = True,
984
+ ):
985
+ # make sure `token_type_ids` is correctly initialized when not passed
986
+ if token_type_ids is None:
987
+ token_type_ids = jnp.zeros_like(input_ids)
988
+
989
+ # make sure `position_ids` is correctly initialized when not passed
990
+ if position_ids is None:
991
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
992
+
993
+ hidden_states = self.embeddings(
994
+ input_ids, token_type_ids, position_ids, attention_mask, deterministic=deterministic
995
+ )
996
+ outputs = self.encoder(
997
+ hidden_states,
998
+ attention_mask,
999
+ head_mask=head_mask,
1000
+ deterministic=deterministic,
1001
+ encoder_hidden_states=encoder_hidden_states,
1002
+ encoder_attention_mask=encoder_attention_mask,
1003
+ init_cache=init_cache,
1004
+ output_attentions=output_attentions,
1005
+ output_hidden_states=output_hidden_states,
1006
+ return_dict=return_dict,
1007
+ )
1008
+ hidden_states = outputs[0]
1009
+ pooled = self.pooler(hidden_states) if self.add_pooling_layer else None
1010
+
1011
+ if not return_dict:
1012
+ # if pooled is None, don't return it
1013
+ if pooled is None:
1014
+ return (hidden_states,) + outputs[1:]
1015
+ return (hidden_states, pooled) + outputs[1:]
1016
+
1017
+ return FlaxBaseModelOutputWithPoolingAndCrossAttentions(
1018
+ last_hidden_state=hidden_states,
1019
+ pooler_output=pooled,
1020
+ hidden_states=outputs.hidden_states,
1021
+ attentions=outputs.attentions,
1022
+ cross_attentions=outputs.cross_attentions,
1023
+ )
1024
+
1025
+
1026
+ @add_start_docstrings(
1027
+ "The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
1028
+ BERT_START_DOCSTRING,
1029
+ )
1030
+ class FlaxBertModel(FlaxBertPreTrainedModel):
1031
+ module_class = FlaxBertModule
1032
+
1033
+
1034
+ append_call_sample_docstring(FlaxBertModel, _CHECKPOINT_FOR_DOC, FlaxBaseModelOutputWithPooling, _CONFIG_FOR_DOC)
1035
+
1036
+
1037
+ class FlaxBertForPreTrainingModule(nn.Module):
1038
+ config: BertConfig
1039
+ dtype: jnp.dtype = jnp.float32
1040
+ gradient_checkpointing: bool = False
1041
+
1042
+ def setup(self):
1043
+ self.bert = FlaxBertModule(
1044
+ config=self.config,
1045
+ dtype=self.dtype,
1046
+ gradient_checkpointing=self.gradient_checkpointing,
1047
+ )
1048
+ self.cls = FlaxBertPreTrainingHeads(config=self.config, dtype=self.dtype)
1049
+
1050
+ def __call__(
1051
+ self,
1052
+ input_ids,
1053
+ attention_mask,
1054
+ token_type_ids,
1055
+ position_ids,
1056
+ head_mask,
1057
+ deterministic: bool = True,
1058
+ output_attentions: bool = False,
1059
+ output_hidden_states: bool = False,
1060
+ return_dict: bool = True,
1061
+ ):
1062
+ # Model
1063
+ outputs = self.bert(
1064
+ input_ids,
1065
+ attention_mask,
1066
+ token_type_ids,
1067
+ position_ids,
1068
+ head_mask,
1069
+ deterministic=deterministic,
1070
+ output_attentions=output_attentions,
1071
+ output_hidden_states=output_hidden_states,
1072
+ return_dict=return_dict,
1073
+ )
1074
+
1075
+ if self.config.tie_word_embeddings:
1076
+ shared_embedding = self.bert.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
1077
+ else:
1078
+ shared_embedding = None
1079
+
1080
+ hidden_states = outputs[0]
1081
+ pooled_output = outputs[1]
1082
+
1083
+ prediction_scores, seq_relationship_score = self.cls(
1084
+ hidden_states, pooled_output, shared_embedding=shared_embedding
1085
+ )
1086
+
1087
+ if not return_dict:
1088
+ return (prediction_scores, seq_relationship_score) + outputs[2:]
1089
+
1090
+ return FlaxBertForPreTrainingOutput(
1091
+ prediction_logits=prediction_scores,
1092
+ seq_relationship_logits=seq_relationship_score,
1093
+ hidden_states=outputs.hidden_states,
1094
+ attentions=outputs.attentions,
1095
+ )
1096
+
1097
+
1098
+ @add_start_docstrings(
1099
+ """
1100
+ Bert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
1101
+ sentence prediction (classification)` head.
1102
+ """,
1103
+ BERT_START_DOCSTRING,
1104
+ )
1105
+ class FlaxBertForPreTraining(FlaxBertPreTrainedModel):
1106
+ module_class = FlaxBertForPreTrainingModule
1107
+
1108
+
1109
+ FLAX_BERT_FOR_PRETRAINING_DOCSTRING = """
1110
+ Returns:
1111
+
1112
+ Example:
1113
+
1114
+ ```python
1115
+ >>> from transformers import AutoTokenizer, FlaxBertForPreTraining
1116
+
1117
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
1118
+ >>> model = FlaxBertForPreTraining.from_pretrained("google-bert/bert-base-uncased")
1119
+
1120
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="np")
1121
+ >>> outputs = model(**inputs)
1122
+
1123
+ >>> prediction_logits = outputs.prediction_logits
1124
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
1125
+ ```
1126
+ """
1127
+
1128
+ overwrite_call_docstring(
1129
+ FlaxBertForPreTraining,
1130
+ BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length") + FLAX_BERT_FOR_PRETRAINING_DOCSTRING,
1131
+ )
1132
+ append_replace_return_docstrings(
1133
+ FlaxBertForPreTraining, output_type=FlaxBertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC
1134
+ )
1135
+
1136
+
1137
+ class FlaxBertForMaskedLMModule(nn.Module):
1138
+ config: BertConfig
1139
+ dtype: jnp.dtype = jnp.float32
1140
+ gradient_checkpointing: bool = False
1141
+
1142
+ def setup(self):
1143
+ self.bert = FlaxBertModule(
1144
+ config=self.config,
1145
+ add_pooling_layer=False,
1146
+ dtype=self.dtype,
1147
+ gradient_checkpointing=self.gradient_checkpointing,
1148
+ )
1149
+ self.cls = FlaxBertOnlyMLMHead(config=self.config, dtype=self.dtype)
1150
+
1151
+ def __call__(
1152
+ self,
1153
+ input_ids,
1154
+ attention_mask,
1155
+ token_type_ids,
1156
+ position_ids,
1157
+ head_mask,
1158
+ deterministic: bool = True,
1159
+ output_attentions: bool = False,
1160
+ output_hidden_states: bool = False,
1161
+ return_dict: bool = True,
1162
+ ):
1163
+ # Model
1164
+ outputs = self.bert(
1165
+ input_ids,
1166
+ attention_mask,
1167
+ token_type_ids,
1168
+ position_ids,
1169
+ head_mask,
1170
+ deterministic=deterministic,
1171
+ output_attentions=output_attentions,
1172
+ output_hidden_states=output_hidden_states,
1173
+ return_dict=return_dict,
1174
+ )
1175
+
1176
+ hidden_states = outputs[0]
1177
+ if self.config.tie_word_embeddings:
1178
+ shared_embedding = self.bert.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
1179
+ else:
1180
+ shared_embedding = None
1181
+
1182
+ # Compute the prediction scores
1183
+ logits = self.cls(hidden_states, shared_embedding=shared_embedding)
1184
+
1185
+ if not return_dict:
1186
+ return (logits,) + outputs[1:]
1187
+
1188
+ return FlaxMaskedLMOutput(
1189
+ logits=logits,
1190
+ hidden_states=outputs.hidden_states,
1191
+ attentions=outputs.attentions,
1192
+ )
1193
+
1194
+
1195
+ @add_start_docstrings("""Bert Model with a `language modeling` head on top.""", BERT_START_DOCSTRING)
1196
+ class FlaxBertForMaskedLM(FlaxBertPreTrainedModel):
1197
+ module_class = FlaxBertForMaskedLMModule
1198
+
1199
+
1200
+ append_call_sample_docstring(FlaxBertForMaskedLM, _CHECKPOINT_FOR_DOC, FlaxMaskedLMOutput, _CONFIG_FOR_DOC)
1201
+
1202
+
1203
+ class FlaxBertForNextSentencePredictionModule(nn.Module):
1204
+ config: BertConfig
1205
+ dtype: jnp.dtype = jnp.float32
1206
+ gradient_checkpointing: bool = False
1207
+
1208
+ def setup(self):
1209
+ self.bert = FlaxBertModule(
1210
+ config=self.config,
1211
+ dtype=self.dtype,
1212
+ gradient_checkpointing=self.gradient_checkpointing,
1213
+ )
1214
+ self.cls = FlaxBertOnlyNSPHead(dtype=self.dtype)
1215
+
1216
+ def __call__(
1217
+ self,
1218
+ input_ids,
1219
+ attention_mask,
1220
+ token_type_ids,
1221
+ position_ids,
1222
+ head_mask,
1223
+ deterministic: bool = True,
1224
+ output_attentions: bool = False,
1225
+ output_hidden_states: bool = False,
1226
+ return_dict: bool = True,
1227
+ ):
1228
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1229
+
1230
+ # Model
1231
+ outputs = self.bert(
1232
+ input_ids,
1233
+ attention_mask,
1234
+ token_type_ids,
1235
+ position_ids,
1236
+ head_mask,
1237
+ deterministic=deterministic,
1238
+ output_attentions=output_attentions,
1239
+ output_hidden_states=output_hidden_states,
1240
+ return_dict=return_dict,
1241
+ )
1242
+
1243
+ pooled_output = outputs[1]
1244
+ seq_relationship_scores = self.cls(pooled_output)
1245
+
1246
+ if not return_dict:
1247
+ return (seq_relationship_scores,) + outputs[2:]
1248
+
1249
+ return FlaxNextSentencePredictorOutput(
1250
+ logits=seq_relationship_scores,
1251
+ hidden_states=outputs.hidden_states,
1252
+ attentions=outputs.attentions,
1253
+ )
1254
+
1255
+
1256
+ @add_start_docstrings(
1257
+ """Bert Model with a `next sentence prediction (classification)` head on top.""",
1258
+ BERT_START_DOCSTRING,
1259
+ )
1260
+ class FlaxBertForNextSentencePrediction(FlaxBertPreTrainedModel):
1261
+ module_class = FlaxBertForNextSentencePredictionModule
1262
+
1263
+
1264
+ FLAX_BERT_FOR_NEXT_SENT_PRED_DOCSTRING = """
1265
+ Returns:
1266
+
1267
+ Example:
1268
+
1269
+ ```python
1270
+ >>> from transformers import AutoTokenizer, FlaxBertForNextSentencePrediction
1271
+
1272
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
1273
+ >>> model = FlaxBertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")
1274
+
1275
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1276
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
1277
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="jax")
1278
+
1279
+ >>> outputs = model(**encoding)
1280
+ >>> logits = outputs.logits
1281
+ >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
1282
+ ```
1283
+ """
1284
+
1285
+
1286
+ overwrite_call_docstring(
1287
+ FlaxBertForNextSentencePrediction,
1288
+ BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length") + FLAX_BERT_FOR_NEXT_SENT_PRED_DOCSTRING,
1289
+ )
1290
+ append_replace_return_docstrings(
1291
+ FlaxBertForNextSentencePrediction, output_type=FlaxNextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC
1292
+ )
1293
+
1294
+
1295
+ class FlaxBertForSequenceClassificationModule(nn.Module):
1296
+ config: BertConfig
1297
+ dtype: jnp.dtype = jnp.float32
1298
+ gradient_checkpointing: bool = False
1299
+
1300
+ def setup(self):
1301
+ self.bert = FlaxBertModule(
1302
+ config=self.config,
1303
+ dtype=self.dtype,
1304
+ gradient_checkpointing=self.gradient_checkpointing,
1305
+ )
1306
+ classifier_dropout = (
1307
+ self.config.classifier_dropout
1308
+ if self.config.classifier_dropout is not None
1309
+ else self.config.hidden_dropout_prob
1310
+ )
1311
+ self.dropout = nn.Dropout(rate=classifier_dropout)
1312
+ self.classifier = nn.Dense(
1313
+ self.config.num_labels,
1314
+ dtype=self.dtype,
1315
+ )
1316
+
1317
+ def __call__(
1318
+ self,
1319
+ input_ids,
1320
+ attention_mask,
1321
+ token_type_ids,
1322
+ position_ids,
1323
+ head_mask,
1324
+ deterministic: bool = True,
1325
+ output_attentions: bool = False,
1326
+ output_hidden_states: bool = False,
1327
+ return_dict: bool = True,
1328
+ ):
1329
+ # Model
1330
+ outputs = self.bert(
1331
+ input_ids,
1332
+ attention_mask,
1333
+ token_type_ids,
1334
+ position_ids,
1335
+ head_mask,
1336
+ deterministic=deterministic,
1337
+ output_attentions=output_attentions,
1338
+ output_hidden_states=output_hidden_states,
1339
+ return_dict=return_dict,
1340
+ )
1341
+
1342
+ pooled_output = outputs[1]
1343
+ pooled_output = self.dropout(pooled_output, deterministic=deterministic)
1344
+ logits = self.classifier(pooled_output)
1345
+
1346
+ if not return_dict:
1347
+ return (logits,) + outputs[2:]
1348
+
1349
+ return FlaxSequenceClassifierOutput(
1350
+ logits=logits,
1351
+ hidden_states=outputs.hidden_states,
1352
+ attentions=outputs.attentions,
1353
+ )
1354
+
1355
+
1356
+ @add_start_docstrings(
1357
+ """
1358
+ Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
1359
+ output) e.g. for GLUE tasks.
1360
+ """,
1361
+ BERT_START_DOCSTRING,
1362
+ )
1363
+ class FlaxBertForSequenceClassification(FlaxBertPreTrainedModel):
1364
+ module_class = FlaxBertForSequenceClassificationModule
1365
+
1366
+
1367
+ append_call_sample_docstring(
1368
+ FlaxBertForSequenceClassification,
1369
+ _CHECKPOINT_FOR_DOC,
1370
+ FlaxSequenceClassifierOutput,
1371
+ _CONFIG_FOR_DOC,
1372
+ )
1373
+
1374
+
1375
+ class FlaxBertForMultipleChoiceModule(nn.Module):
1376
+ config: BertConfig
1377
+ dtype: jnp.dtype = jnp.float32
1378
+ gradient_checkpointing: bool = False
1379
+
1380
+ def setup(self):
1381
+ self.bert = FlaxBertModule(
1382
+ config=self.config,
1383
+ dtype=self.dtype,
1384
+ gradient_checkpointing=self.gradient_checkpointing,
1385
+ )
1386
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
1387
+ self.classifier = nn.Dense(1, dtype=self.dtype)
1388
+
1389
+ def __call__(
1390
+ self,
1391
+ input_ids,
1392
+ attention_mask,
1393
+ token_type_ids,
1394
+ position_ids,
1395
+ head_mask,
1396
+ deterministic: bool = True,
1397
+ output_attentions: bool = False,
1398
+ output_hidden_states: bool = False,
1399
+ return_dict: bool = True,
1400
+ ):
1401
+ num_choices = input_ids.shape[1]
1402
+ input_ids = input_ids.reshape(-1, input_ids.shape[-1]) if input_ids is not None else None
1403
+ attention_mask = attention_mask.reshape(-1, attention_mask.shape[-1]) if attention_mask is not None else None
1404
+ token_type_ids = token_type_ids.reshape(-1, token_type_ids.shape[-1]) if token_type_ids is not None else None
1405
+ position_ids = position_ids.reshape(-1, position_ids.shape[-1]) if position_ids is not None else None
1406
+
1407
+ # Model
1408
+ outputs = self.bert(
1409
+ input_ids,
1410
+ attention_mask,
1411
+ token_type_ids,
1412
+ position_ids,
1413
+ head_mask,
1414
+ deterministic=deterministic,
1415
+ output_attentions=output_attentions,
1416
+ output_hidden_states=output_hidden_states,
1417
+ return_dict=return_dict,
1418
+ )
1419
+
1420
+ pooled_output = outputs[1]
1421
+ pooled_output = self.dropout(pooled_output, deterministic=deterministic)
1422
+ logits = self.classifier(pooled_output)
1423
+
1424
+ reshaped_logits = logits.reshape(-1, num_choices)
1425
+
1426
+ if not return_dict:
1427
+ return (reshaped_logits,) + outputs[2:]
1428
+
1429
+ return FlaxMultipleChoiceModelOutput(
1430
+ logits=reshaped_logits,
1431
+ hidden_states=outputs.hidden_states,
1432
+ attentions=outputs.attentions,
1433
+ )
1434
+
1435
+
1436
+ @add_start_docstrings(
1437
+ """
1438
+ Bert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1439
+ softmax) e.g. for RocStories/SWAG tasks.
1440
+ """,
1441
+ BERT_START_DOCSTRING,
1442
+ )
1443
+ class FlaxBertForMultipleChoice(FlaxBertPreTrainedModel):
1444
+ module_class = FlaxBertForMultipleChoiceModule
1445
+
1446
+
1447
+ overwrite_call_docstring(
1448
+ FlaxBertForMultipleChoice, BERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
1449
+ )
1450
+ append_call_sample_docstring(
1451
+ FlaxBertForMultipleChoice, _CHECKPOINT_FOR_DOC, FlaxMultipleChoiceModelOutput, _CONFIG_FOR_DOC
1452
+ )
1453
+
1454
+
1455
+ class FlaxBertForTokenClassificationModule(nn.Module):
1456
+ config: BertConfig
1457
+ dtype: jnp.dtype = jnp.float32
1458
+ gradient_checkpointing: bool = False
1459
+
1460
+ def setup(self):
1461
+ self.bert = FlaxBertModule(
1462
+ config=self.config,
1463
+ dtype=self.dtype,
1464
+ add_pooling_layer=False,
1465
+ gradient_checkpointing=self.gradient_checkpointing,
1466
+ )
1467
+ classifier_dropout = (
1468
+ self.config.classifier_dropout
1469
+ if self.config.classifier_dropout is not None
1470
+ else self.config.hidden_dropout_prob
1471
+ )
1472
+ self.dropout = nn.Dropout(rate=classifier_dropout)
1473
+ self.classifier = nn.Dense(self.config.num_labels, dtype=self.dtype)
1474
+
1475
+ def __call__(
1476
+ self,
1477
+ input_ids,
1478
+ attention_mask,
1479
+ token_type_ids,
1480
+ position_ids,
1481
+ head_mask,
1482
+ deterministic: bool = True,
1483
+ output_attentions: bool = False,
1484
+ output_hidden_states: bool = False,
1485
+ return_dict: bool = True,
1486
+ ):
1487
+ # Model
1488
+ outputs = self.bert(
1489
+ input_ids,
1490
+ attention_mask,
1491
+ token_type_ids,
1492
+ position_ids,
1493
+ head_mask,
1494
+ deterministic=deterministic,
1495
+ output_attentions=output_attentions,
1496
+ output_hidden_states=output_hidden_states,
1497
+ return_dict=return_dict,
1498
+ )
1499
+
1500
+ hidden_states = outputs[0]
1501
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
1502
+ logits = self.classifier(hidden_states)
1503
+
1504
+ if not return_dict:
1505
+ return (logits,) + outputs[1:]
1506
+
1507
+ return FlaxTokenClassifierOutput(
1508
+ logits=logits,
1509
+ hidden_states=outputs.hidden_states,
1510
+ attentions=outputs.attentions,
1511
+ )
1512
+
1513
+
1514
+ @add_start_docstrings(
1515
+ """
1516
+ Bert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1517
+ Named-Entity-Recognition (NER) tasks.
1518
+ """,
1519
+ BERT_START_DOCSTRING,
1520
+ )
1521
+ class FlaxBertForTokenClassification(FlaxBertPreTrainedModel):
1522
+ module_class = FlaxBertForTokenClassificationModule
1523
+
1524
+
1525
+ append_call_sample_docstring(
1526
+ FlaxBertForTokenClassification, _CHECKPOINT_FOR_DOC, FlaxTokenClassifierOutput, _CONFIG_FOR_DOC
1527
+ )
1528
+
1529
+
1530
+ class FlaxBertForQuestionAnsweringModule(nn.Module):
1531
+ config: BertConfig
1532
+ dtype: jnp.dtype = jnp.float32
1533
+ gradient_checkpointing: bool = False
1534
+
1535
+ def setup(self):
1536
+ self.bert = FlaxBertModule(
1537
+ config=self.config,
1538
+ dtype=self.dtype,
1539
+ add_pooling_layer=False,
1540
+ gradient_checkpointing=self.gradient_checkpointing,
1541
+ )
1542
+ self.qa_outputs = nn.Dense(self.config.num_labels, dtype=self.dtype)
1543
+
1544
+ def __call__(
1545
+ self,
1546
+ input_ids,
1547
+ attention_mask,
1548
+ token_type_ids,
1549
+ position_ids,
1550
+ head_mask,
1551
+ deterministic: bool = True,
1552
+ output_attentions: bool = False,
1553
+ output_hidden_states: bool = False,
1554
+ return_dict: bool = True,
1555
+ ):
1556
+ # Model
1557
+ outputs = self.bert(
1558
+ input_ids,
1559
+ attention_mask,
1560
+ token_type_ids,
1561
+ position_ids,
1562
+ head_mask,
1563
+ deterministic=deterministic,
1564
+ output_attentions=output_attentions,
1565
+ output_hidden_states=output_hidden_states,
1566
+ return_dict=return_dict,
1567
+ )
1568
+
1569
+ hidden_states = outputs[0]
1570
+
1571
+ logits = self.qa_outputs(hidden_states)
1572
+ start_logits, end_logits = jnp.split(logits, self.config.num_labels, axis=-1)
1573
+ start_logits = start_logits.squeeze(-1)
1574
+ end_logits = end_logits.squeeze(-1)
1575
+
1576
+ if not return_dict:
1577
+ return (start_logits, end_logits) + outputs[1:]
1578
+
1579
+ return FlaxQuestionAnsweringModelOutput(
1580
+ start_logits=start_logits,
1581
+ end_logits=end_logits,
1582
+ hidden_states=outputs.hidden_states,
1583
+ attentions=outputs.attentions,
1584
+ )
1585
+
1586
+
1587
+ @add_start_docstrings(
1588
+ """
1589
+ Bert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1590
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1591
+ """,
1592
+ BERT_START_DOCSTRING,
1593
+ )
1594
+ class FlaxBertForQuestionAnswering(FlaxBertPreTrainedModel):
1595
+ module_class = FlaxBertForQuestionAnsweringModule
1596
+
1597
+
1598
+ append_call_sample_docstring(
1599
+ FlaxBertForQuestionAnswering,
1600
+ _CHECKPOINT_FOR_DOC,
1601
+ FlaxQuestionAnsweringModelOutput,
1602
+ _CONFIG_FOR_DOC,
1603
+ )
1604
+
1605
+
1606
+ class FlaxBertForCausalLMModule(nn.Module):
1607
+ config: BertConfig
1608
+ dtype: jnp.dtype = jnp.float32
1609
+ gradient_checkpointing: bool = False
1610
+
1611
+ def setup(self):
1612
+ self.bert = FlaxBertModule(
1613
+ config=self.config,
1614
+ add_pooling_layer=False,
1615
+ dtype=self.dtype,
1616
+ gradient_checkpointing=self.gradient_checkpointing,
1617
+ )
1618
+ self.cls = FlaxBertOnlyMLMHead(config=self.config, dtype=self.dtype)
1619
+
1620
+ def __call__(
1621
+ self,
1622
+ input_ids,
1623
+ attention_mask,
1624
+ position_ids,
1625
+ token_type_ids: Optional[jnp.ndarray] = None,
1626
+ head_mask: Optional[jnp.ndarray] = None,
1627
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
1628
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
1629
+ init_cache: bool = False,
1630
+ deterministic: bool = True,
1631
+ output_attentions: bool = False,
1632
+ output_hidden_states: bool = False,
1633
+ return_dict: bool = True,
1634
+ ):
1635
+ # Model
1636
+ outputs = self.bert(
1637
+ input_ids,
1638
+ attention_mask,
1639
+ token_type_ids,
1640
+ position_ids,
1641
+ head_mask,
1642
+ encoder_hidden_states=encoder_hidden_states,
1643
+ encoder_attention_mask=encoder_attention_mask,
1644
+ init_cache=init_cache,
1645
+ deterministic=deterministic,
1646
+ output_attentions=output_attentions,
1647
+ output_hidden_states=output_hidden_states,
1648
+ return_dict=return_dict,
1649
+ )
1650
+
1651
+ hidden_states = outputs[0]
1652
+ if self.config.tie_word_embeddings:
1653
+ shared_embedding = self.bert.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
1654
+ else:
1655
+ shared_embedding = None
1656
+
1657
+ # Compute the prediction scores
1658
+ logits = self.cls(hidden_states, shared_embedding=shared_embedding)
1659
+
1660
+ if not return_dict:
1661
+ return (logits,) + outputs[1:]
1662
+
1663
+ return FlaxCausalLMOutputWithCrossAttentions(
1664
+ logits=logits,
1665
+ hidden_states=outputs.hidden_states,
1666
+ attentions=outputs.attentions,
1667
+ cross_attentions=outputs.cross_attentions,
1668
+ )
1669
+
1670
+
1671
+ @add_start_docstrings(
1672
+ """
1673
+ Bert Model with a language modeling head on top (a linear layer on top of the hidden-states output) e.g for
1674
+ autoregressive tasks.
1675
+ """,
1676
+ BERT_START_DOCSTRING,
1677
+ )
1678
+ class FlaxBertForCausalLM(FlaxBertPreTrainedModel):
1679
+ module_class = FlaxBertForCausalLMModule
1680
+
1681
+ def prepare_inputs_for_generation(self, input_ids, max_length, attention_mask: Optional[jax.Array] = None):
1682
+ # initializing the cache
1683
+ batch_size, seq_length = input_ids.shape
1684
+
1685
+ past_key_values = self.init_cache(batch_size, max_length)
1686
+ # Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
1687
+ # But since the decoder uses a causal mask, those positions are masked anyway.
1688
+ # Thus, we can create a single static attention_mask here, which is more efficient for compilation
1689
+ extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
1690
+ if attention_mask is not None:
1691
+ position_ids = attention_mask.cumsum(axis=-1) - 1
1692
+ extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, attention_mask, (0, 0))
1693
+ else:
1694
+ position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
1695
+
1696
+ return {
1697
+ "past_key_values": past_key_values,
1698
+ "attention_mask": extended_attention_mask,
1699
+ "position_ids": position_ids,
1700
+ }
1701
+
1702
+ def update_inputs_for_generation(self, model_outputs, model_kwargs):
1703
+ model_kwargs["past_key_values"] = model_outputs.past_key_values
1704
+ model_kwargs["position_ids"] = model_kwargs["position_ids"][:, -1:] + 1
1705
+ return model_kwargs
1706
+
1707
+
1708
+ append_call_sample_docstring(
1709
+ FlaxBertForCausalLM,
1710
+ _CHECKPOINT_FOR_DOC,
1711
+ FlaxCausalLMOutputWithCrossAttentions,
1712
+ _CONFIG_FOR_DOC,
1713
+ )
1714
+
1715
+
1716
+ __all__ = [
1717
+ "FlaxBertForCausalLM",
1718
+ "FlaxBertForMaskedLM",
1719
+ "FlaxBertForMultipleChoice",
1720
+ "FlaxBertForNextSentencePrediction",
1721
+ "FlaxBertForPreTraining",
1722
+ "FlaxBertForQuestionAnswering",
1723
+ "FlaxBertForSequenceClassification",
1724
+ "FlaxBertForTokenClassification",
1725
+ "FlaxBertModel",
1726
+ "FlaxBertPreTrainedModel",
1727
+ ]
janus/lib/python3.10/site-packages/transformers/models/bert/tokenization_bert_fast.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Fast Tokenization classes for Bert."""
16
+
17
+ import json
18
+ from typing import List, Optional, Tuple
19
+
20
+ from tokenizers import normalizers
21
+
22
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
23
+ from ...utils import logging
24
+ from .tokenization_bert import BertTokenizer
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
30
+
31
+
32
+ class BertTokenizerFast(PreTrainedTokenizerFast):
33
+ r"""
34
+ Construct a "fast" BERT tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
35
+
36
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
37
+ refer to this superclass for more information regarding those methods.
38
+
39
+ Args:
40
+ vocab_file (`str`):
41
+ File containing the vocabulary.
42
+ do_lower_case (`bool`, *optional*, defaults to `True`):
43
+ Whether or not to lowercase the input when tokenizing.
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
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
48
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
49
+ sequence classification or for a text and a question for question answering. It is also used as the last
50
+ token of a sequence built with special tokens.
51
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
52
+ The token used for padding, for example when batching sequences of different lengths.
53
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
54
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
55
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
56
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
57
+ The token used for masking values. This is the token used when training this model with masked language
58
+ modeling. This is the token which the model will try to predict.
59
+ clean_text (`bool`, *optional*, defaults to `True`):
60
+ Whether or not to clean the text before tokenization by removing any control characters and replacing all
61
+ whitespaces by the classic one.
62
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
63
+ Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
64
+ issue](https://github.com/huggingface/transformers/issues/328)).
65
+ strip_accents (`bool`, *optional*):
66
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
67
+ value for `lowercase` (as in the original BERT).
68
+ wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
69
+ The prefix for subwords.
70
+ """
71
+
72
+ vocab_files_names = VOCAB_FILES_NAMES
73
+ slow_tokenizer_class = BertTokenizer
74
+
75
+ def __init__(
76
+ self,
77
+ vocab_file=None,
78
+ tokenizer_file=None,
79
+ do_lower_case=True,
80
+ unk_token="[UNK]",
81
+ sep_token="[SEP]",
82
+ pad_token="[PAD]",
83
+ cls_token="[CLS]",
84
+ mask_token="[MASK]",
85
+ tokenize_chinese_chars=True,
86
+ strip_accents=None,
87
+ **kwargs,
88
+ ):
89
+ super().__init__(
90
+ vocab_file,
91
+ tokenizer_file=tokenizer_file,
92
+ do_lower_case=do_lower_case,
93
+ unk_token=unk_token,
94
+ sep_token=sep_token,
95
+ pad_token=pad_token,
96
+ cls_token=cls_token,
97
+ mask_token=mask_token,
98
+ tokenize_chinese_chars=tokenize_chinese_chars,
99
+ strip_accents=strip_accents,
100
+ **kwargs,
101
+ )
102
+
103
+ normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
104
+ if (
105
+ normalizer_state.get("lowercase", do_lower_case) != do_lower_case
106
+ or normalizer_state.get("strip_accents", strip_accents) != strip_accents
107
+ or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
108
+ ):
109
+ normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
110
+ normalizer_state["lowercase"] = do_lower_case
111
+ normalizer_state["strip_accents"] = strip_accents
112
+ normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
113
+ self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
114
+
115
+ self.do_lower_case = do_lower_case
116
+
117
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
118
+ """
119
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
120
+ adding special tokens. A BERT sequence has the following format:
121
+
122
+ - single sequence: `[CLS] X [SEP]`
123
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
124
+
125
+ Args:
126
+ token_ids_0 (`List[int]`):
127
+ List of IDs to which the special tokens will be added.
128
+ token_ids_1 (`List[int]`, *optional*):
129
+ Optional second list of IDs for sequence pairs.
130
+
131
+ Returns:
132
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
133
+ """
134
+ output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
135
+
136
+ if token_ids_1 is not None:
137
+ output += token_ids_1 + [self.sep_token_id]
138
+
139
+ return output
140
+
141
+ def create_token_type_ids_from_sequences(
142
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
143
+ ) -> List[int]:
144
+ """
145
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence
146
+ pair mask has the following format:
147
+
148
+ ```
149
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
150
+ | first sequence | second sequence |
151
+ ```
152
+
153
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
154
+
155
+ Args:
156
+ token_ids_0 (`List[int]`):
157
+ List of IDs.
158
+ token_ids_1 (`List[int]`, *optional*):
159
+ Optional second list of IDs for sequence pairs.
160
+
161
+ Returns:
162
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
163
+ """
164
+ sep = [self.sep_token_id]
165
+ cls = [self.cls_token_id]
166
+ if token_ids_1 is None:
167
+ return len(cls + token_ids_0 + sep) * [0]
168
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
169
+
170
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
171
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
172
+ return tuple(files)
173
+
174
+
175
+ __all__ = ["BertTokenizerFast"]
janus/lib/python3.10/site-packages/transformers/models/blip/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (619 Bytes). View file
 
janus/lib/python3.10/site-packages/transformers/models/blip/__pycache__/modeling_blip_text.cpython-310.pyc ADDED
Binary file (28 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip.cpython-310.pyc ADDED
Binary file (54.5 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip_text.cpython-310.pyc ADDED
Binary file (32.3 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/blip/image_processing_blip.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_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: 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
+
235
+ images = make_list_of_images(images)
236
+
237
+ if not valid_images(images):
238
+ raise ValueError(
239
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
240
+ "torch.Tensor, tf.Tensor or jax.ndarray."
241
+ )
242
+
243
+ validate_preprocess_arguments(
244
+ do_rescale=do_rescale,
245
+ rescale_factor=rescale_factor,
246
+ do_normalize=do_normalize,
247
+ image_mean=image_mean,
248
+ image_std=image_std,
249
+ do_resize=do_resize,
250
+ size=size,
251
+ resample=resample,
252
+ )
253
+ # PIL RGBA images are converted to RGB
254
+ if do_convert_rgb:
255
+ images = [convert_to_rgb(image) for image in images]
256
+
257
+ # All transformations expect numpy arrays.
258
+ images = [to_numpy_array(image) for image in images]
259
+
260
+ if do_rescale and is_scaled_image(images[0]):
261
+ logger.warning_once(
262
+ "It looks like you are trying to rescale already rescaled images. If the input"
263
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
264
+ )
265
+
266
+ if input_data_format is None:
267
+ # We assume that all images have the same channel dimension format.
268
+ input_data_format = infer_channel_dimension_format(images[0])
269
+
270
+ if do_resize:
271
+ images = [
272
+ self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
273
+ for image in images
274
+ ]
275
+
276
+ if do_rescale:
277
+ images = [
278
+ self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
279
+ for image in images
280
+ ]
281
+
282
+ if do_normalize:
283
+ images = [
284
+ self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
285
+ for image in images
286
+ ]
287
+
288
+ images = [
289
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
290
+ ]
291
+
292
+ encoded_outputs = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors)
293
+
294
+ return encoded_outputs
295
+
296
+
297
+ __all__ = ["BlipImageProcessor"]
janus/lib/python3.10/site-packages/transformers/models/blip/modeling_blip.py ADDED
@@ -0,0 +1,1596 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: 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: 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: 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: torch.FloatTensor = None
204
+ logits_per_text: torch.FloatTensor = None
205
+ text_embeds: torch.FloatTensor = None
206
+ image_embeds: 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
+
313
+ if position_ids is None:
314
+ position_ids = self.position_ids[:, :seq_length]
315
+
316
+ if inputs_embeds is None:
317
+ inputs_embeds = self.token_embedding(input_ids)
318
+
319
+ position_embeddings = self.position_embedding(position_ids)
320
+ embeddings = inputs_embeds + position_embeddings
321
+
322
+ return embeddings
323
+
324
+
325
+ class BlipAttention(nn.Module):
326
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
327
+
328
+ def __init__(self, config):
329
+ super().__init__()
330
+ self.config = config
331
+ self.embed_dim = config.hidden_size
332
+ self.num_heads = config.num_attention_heads
333
+ self.head_dim = self.embed_dim // self.num_heads
334
+ if self.head_dim * self.num_heads != self.embed_dim:
335
+ raise ValueError(
336
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
337
+ f" {self.num_heads})."
338
+ )
339
+ self.scale = self.head_dim**-0.5
340
+ self.dropout = nn.Dropout(config.attention_dropout)
341
+
342
+ self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim)
343
+
344
+ self.projection = nn.Linear(self.embed_dim, self.embed_dim)
345
+
346
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
347
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
348
+
349
+ def forward(
350
+ self,
351
+ hidden_states: torch.Tensor,
352
+ head_mask: Optional[torch.Tensor] = None,
353
+ output_attentions: Optional[bool] = False,
354
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
355
+ """Input shape: Batch x Time x Channel"""
356
+
357
+ bsz, tgt_len, embed_dim = hidden_states.size()
358
+
359
+ mixed_qkv = (
360
+ self.qkv(hidden_states)
361
+ .reshape(bsz, tgt_len, 3, self.num_heads, embed_dim // self.num_heads)
362
+ .permute(2, 0, 3, 1, 4)
363
+ )
364
+ query_states, key_states, value_states = mixed_qkv[0], mixed_qkv[1], mixed_qkv[2]
365
+
366
+ # Take the dot product between "query" and "key" to get the raw attention scores.
367
+ attention_scores = torch.matmul(query_states, key_states.transpose(-1, -2))
368
+
369
+ attention_scores = attention_scores * self.scale
370
+
371
+ # Normalize the attention scores to probabilities.
372
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
373
+
374
+ # This is actually dropping out entire tokens to attend to, which might
375
+ # seem a bit unusual, but is taken from the original Transformer paper.
376
+ attention_probs = self.dropout(attention_probs)
377
+
378
+ # Mask heads if we want to
379
+ if head_mask is not None:
380
+ attention_probs = attention_probs * head_mask
381
+
382
+ context_layer = torch.matmul(attention_probs, value_states).permute(0, 2, 1, 3)
383
+
384
+ new_context_layer_shape = context_layer.size()[:-2] + (self.embed_dim,)
385
+ context_layer = context_layer.reshape(new_context_layer_shape)
386
+
387
+ output = self.projection(context_layer)
388
+
389
+ outputs = (output, attention_probs) if output_attentions else (output, None)
390
+
391
+ return outputs
392
+
393
+
394
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Blip
395
+ class BlipMLP(nn.Module):
396
+ def __init__(self, config):
397
+ super().__init__()
398
+ self.config = config
399
+ self.activation_fn = ACT2FN[config.hidden_act]
400
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
401
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
402
+
403
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
404
+ hidden_states = self.fc1(hidden_states)
405
+ hidden_states = self.activation_fn(hidden_states)
406
+ hidden_states = self.fc2(hidden_states)
407
+ return hidden_states
408
+
409
+
410
+ class BlipEncoderLayer(nn.Module):
411
+ def __init__(self, config: BlipConfig):
412
+ super().__init__()
413
+ self.embed_dim = config.hidden_size
414
+ self.self_attn = BlipAttention(config)
415
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
416
+ self.mlp = BlipMLP(config)
417
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
418
+
419
+ def forward(
420
+ self,
421
+ hidden_states: torch.Tensor,
422
+ attention_mask: torch.Tensor,
423
+ output_attentions: Optional[bool] = False,
424
+ ) -> Tuple[torch.FloatTensor]:
425
+ """
426
+ Args:
427
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
428
+ attention_mask (`torch.FloatTensor`): attention mask of size
429
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
430
+ `(config.encoder_attention_heads,)`.
431
+ output_attentions (`bool`, *optional*):
432
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
433
+ returned tensors for more detail.
434
+ """
435
+ residual = hidden_states
436
+
437
+ hidden_states = self.layer_norm1(hidden_states)
438
+ hidden_states, attn_weights = self.self_attn(
439
+ hidden_states=hidden_states,
440
+ head_mask=attention_mask,
441
+ output_attentions=output_attentions,
442
+ )
443
+ hidden_states = hidden_states + residual
444
+ residual = hidden_states
445
+ hidden_states = self.layer_norm2(hidden_states)
446
+ hidden_states = self.mlp(hidden_states)
447
+
448
+ hidden_states = hidden_states + residual
449
+
450
+ outputs = (hidden_states,)
451
+
452
+ if output_attentions:
453
+ outputs += (attn_weights,)
454
+
455
+ return outputs
456
+
457
+
458
+ class BlipPreTrainedModel(PreTrainedModel):
459
+ """
460
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
461
+ models.
462
+ """
463
+
464
+ config_class = BlipConfig
465
+ base_model_prefix = "blip"
466
+ supports_gradient_checkpointing = True
467
+ _no_split_modules = ["BlipEncoderLayer", "BlipTextEmbeddings"]
468
+ _skip_keys_device_placement = ["past_key_value"]
469
+
470
+ def _init_weights(self, module):
471
+ """Initialize the weights"""
472
+ factor = self.config.initializer_range
473
+ if isinstance(module, nn.Conv2d) or isinstance(module, nn.Embedding) or isinstance(module, nn.Linear):
474
+ module.weight.data.normal_(mean=0.0, std=factor)
475
+ if hasattr(module, "bias") and module.bias is not None:
476
+ module.bias.data.zero_()
477
+
478
+ if isinstance(module, BlipVisionEmbeddings):
479
+ if hasattr(self.config, "vision_config"):
480
+ factor = self.config.vision_config.initializer_range
481
+ nn.init.trunc_normal_(
482
+ module.position_embedding,
483
+ mean=0.0,
484
+ std=factor,
485
+ )
486
+
487
+ nn.init.trunc_normal_(
488
+ module.class_embedding,
489
+ mean=0.0,
490
+ std=factor,
491
+ )
492
+
493
+ elif isinstance(module, nn.LayerNorm):
494
+ module.bias.data.zero_()
495
+ module.weight.data.fill_(1.0)
496
+ elif isinstance(module, nn.Linear) and module.bias is not None:
497
+ module.bias.data.zero_()
498
+
499
+
500
+ BLIP_START_DOCSTRING = r"""
501
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
502
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
503
+ etc.)
504
+
505
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
506
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
507
+ and behavior.
508
+
509
+ Parameters:
510
+ config ([`BlipConfig`]): Model configuration class with all the parameters of the model.
511
+ Initializing with a config file does not load the weights associated with the model, only the
512
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
513
+ """
514
+
515
+ BLIP_TEXT_INPUTS_DOCSTRING = r"""
516
+ Args:
517
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
518
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
519
+ it.
520
+
521
+ Indices can be obtained using [`AutoProcessor`]. See [`BlipProcessor.__call__`] for details.
522
+
523
+ [What are input IDs?](../glossary#input-ids)
524
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
525
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
526
+
527
+ - 1 for tokens that are **not masked**,
528
+ - 0 for tokens that are **masked**.
529
+
530
+ [What are attention masks?](../glossary#attention-mask)
531
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
532
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
533
+ config.max_position_embeddings - 1]`.
534
+
535
+ [What are position IDs?](../glossary#position-ids)
536
+ output_attentions (`bool`, *optional*):
537
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
538
+ tensors for more detail.
539
+ output_hidden_states (`bool`, *optional*):
540
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
541
+ more detail.
542
+ return_dict (`bool`, *optional*):
543
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
544
+ """
545
+
546
+ BLIP_VISION_INPUTS_DOCSTRING = r"""
547
+ Args:
548
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
549
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
550
+ [`BlipImageProcessor`]. See [`BlipImageProcessor.__call__`] for details.
551
+ output_attentions (`bool`, *optional*):
552
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
553
+ tensors for more detail.
554
+ output_hidden_states (`bool`, *optional*):
555
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
556
+ more detail.
557
+ return_dict (`bool`, *optional*):
558
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
559
+ interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
560
+ Whether to interpolate the pre-trained position encodings.
561
+ """
562
+
563
+ BLIP_INPUTS_DOCSTRING = r"""
564
+ Args:
565
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
566
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
567
+ it.
568
+
569
+ Indices can be obtained using [`AutoProcessor`]. See [`BlipProcessor.__call__`] for details.
570
+
571
+ [What are input IDs?](../glossary#input-ids)
572
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
573
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
574
+
575
+ - 1 for tokens that are **not masked**,
576
+ - 0 for tokens that are **masked**.
577
+
578
+ [What are attention masks?](../glossary#attention-mask)
579
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
580
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
581
+ config.max_position_embeddings - 1]`.
582
+
583
+ [What are position IDs?](../glossary#position-ids)
584
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
585
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
586
+ [`BlipImageProcessor`]. See [`BlipImageProcessor.__call__`] for details.
587
+ return_loss (`bool`, *optional*):
588
+ Whether or not to return the contrastive loss.
589
+ output_attentions (`bool`, *optional*):
590
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
591
+ tensors for more detail.
592
+ output_hidden_states (`bool`, *optional*):
593
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
594
+ more detail.
595
+ return_dict (`bool`, *optional*):
596
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
597
+ interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
598
+ Whether to interpolate the pre-trained position encodings.
599
+ """
600
+
601
+
602
+ class BlipEncoder(nn.Module):
603
+ """
604
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
605
+ [`BlipEncoderLayer`].
606
+
607
+ Args:
608
+ config (`BlipConfig`):
609
+ The corresponding vision configuration for the `BlipEncoder`.
610
+ """
611
+
612
+ def __init__(self, config: BlipConfig):
613
+ super().__init__()
614
+ self.config = config
615
+ self.layers = nn.ModuleList([BlipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
616
+ self.gradient_checkpointing = False
617
+
618
+ def forward(
619
+ self,
620
+ inputs_embeds,
621
+ attention_mask: Optional[torch.Tensor] = None,
622
+ output_attentions: Optional[bool] = None,
623
+ output_hidden_states: Optional[bool] = None,
624
+ return_dict: Optional[bool] = None,
625
+ ) -> Union[Tuple, BaseModelOutput]:
626
+ r"""
627
+ Args:
628
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
629
+ Embedded representation of the inputs. Should be float, not int tokens.
630
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
631
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
632
+
633
+ - 1 for tokens that are **not masked**,
634
+ - 0 for tokens that are **masked**.
635
+
636
+ [What are attention masks?](../glossary#attention-mask)
637
+ output_attentions (`bool`, *optional*):
638
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
639
+ returned tensors for more detail.
640
+ output_hidden_states (`bool`, *optional*):
641
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
642
+ for more detail.
643
+ return_dict (`bool`, *optional*):
644
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
645
+ """
646
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
647
+ output_hidden_states = (
648
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
649
+ )
650
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
651
+
652
+ encoder_states = () if output_hidden_states else None
653
+ all_attentions = () if output_attentions else None
654
+
655
+ hidden_states = inputs_embeds
656
+ for idx, encoder_layer in enumerate(self.layers):
657
+ if output_hidden_states:
658
+ encoder_states = encoder_states + (hidden_states,)
659
+ if self.gradient_checkpointing and self.training:
660
+ layer_outputs = self._gradient_checkpointing_func(
661
+ encoder_layer.__call__,
662
+ hidden_states,
663
+ attention_mask,
664
+ output_attentions,
665
+ )
666
+ else:
667
+ layer_outputs = encoder_layer(
668
+ hidden_states,
669
+ attention_mask,
670
+ output_attentions=output_attentions,
671
+ )
672
+
673
+ hidden_states = layer_outputs[0]
674
+
675
+ if output_attentions:
676
+ all_attentions = all_attentions + (layer_outputs[1],)
677
+
678
+ if output_hidden_states:
679
+ encoder_states = encoder_states + (hidden_states,)
680
+
681
+ if not return_dict:
682
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
683
+ return BaseModelOutput(
684
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
685
+ )
686
+
687
+
688
+ class BlipVisionModel(BlipPreTrainedModel):
689
+ main_input_name = "pixel_values"
690
+ config_class = BlipVisionConfig
691
+
692
+ def __init__(self, config: BlipVisionConfig):
693
+ super().__init__(config)
694
+ self.config = config
695
+ embed_dim = config.hidden_size
696
+
697
+ self.embeddings = BlipVisionEmbeddings(config)
698
+ self.encoder = BlipEncoder(config)
699
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
700
+
701
+ self.post_init()
702
+
703
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
704
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=BlipVisionConfig)
705
+ def forward(
706
+ self,
707
+ pixel_values: Optional[torch.FloatTensor] = None,
708
+ output_attentions: Optional[bool] = None,
709
+ output_hidden_states: Optional[bool] = None,
710
+ return_dict: Optional[bool] = None,
711
+ interpolate_pos_encoding: bool = False,
712
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
713
+ r"""
714
+ Returns:
715
+
716
+ """
717
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
718
+ output_hidden_states = (
719
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
720
+ )
721
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
722
+
723
+ if pixel_values is None:
724
+ raise ValueError("You have to specify pixel_values")
725
+
726
+ hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
727
+
728
+ encoder_outputs = self.encoder(
729
+ inputs_embeds=hidden_states,
730
+ output_attentions=output_attentions,
731
+ output_hidden_states=output_hidden_states,
732
+ return_dict=return_dict,
733
+ )
734
+
735
+ last_hidden_state = encoder_outputs[0]
736
+ last_hidden_state = self.post_layernorm(last_hidden_state)
737
+
738
+ pooled_output = last_hidden_state[:, 0, :]
739
+ pooled_output = self.post_layernorm(pooled_output)
740
+
741
+ if not return_dict:
742
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
743
+
744
+ return BaseModelOutputWithPooling(
745
+ last_hidden_state=last_hidden_state,
746
+ pooler_output=pooled_output,
747
+ hidden_states=encoder_outputs.hidden_states,
748
+ attentions=encoder_outputs.attentions,
749
+ )
750
+
751
+ def get_input_embeddings(self):
752
+ return self.embeddings
753
+
754
+
755
+ @add_start_docstrings(
756
+ """
757
+ This model is going to be deprecated in future versions. Please use `BlipForConditionalGeneration`, `BlipForQuestionAnswering` or `BlipForImageTextRetrieval` depending on your usecase.
758
+ """,
759
+ BLIP_START_DOCSTRING,
760
+ )
761
+ class BlipModel(BlipPreTrainedModel):
762
+ config_class = BlipConfig
763
+
764
+ def __init__(self, config: BlipConfig):
765
+ super().__init__(config)
766
+
767
+ if not isinstance(config.text_config, BlipTextConfig):
768
+ raise TypeError(
769
+ "config.text_config is expected to be of type BlipTextConfig but is of type"
770
+ f" {type(config.text_config)}."
771
+ )
772
+
773
+ if not isinstance(config.vision_config, BlipVisionConfig):
774
+ raise TypeError(
775
+ "config.vision_config is expected to be of type BlipVisionConfig but is of type"
776
+ f" {type(config.vision_config)}."
777
+ )
778
+
779
+ text_config = config.text_config
780
+ vision_config = config.vision_config
781
+
782
+ self.projection_dim = config.projection_dim
783
+ self.text_embed_dim = text_config.hidden_size
784
+ self.vision_embed_dim = vision_config.hidden_size
785
+
786
+ self.text_model = BlipTextModel(text_config)
787
+ self.vision_model = BlipVisionModel(vision_config)
788
+
789
+ self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
790
+ self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
791
+ self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
792
+
793
+ logger.warning(
794
+ "`BlipModel` is going to be deprecated in future release, please use `BlipForConditionalGeneration`, `BlipForQuestionAnswering` or `BlipForImageTextRetrieval` depending on your usecase."
795
+ )
796
+
797
+ # Initialize weights and apply final processing
798
+ self.post_init()
799
+
800
+ def get_input_embeddings(self):
801
+ return self.text_model.get_input_embeddings()
802
+
803
+ def set_input_embeddings(self, value):
804
+ self.text_model.set_input_embeddings(value)
805
+
806
+ @add_start_docstrings_to_model_forward(BLIP_TEXT_INPUTS_DOCSTRING)
807
+ def get_text_features(
808
+ self,
809
+ input_ids: Optional[torch.Tensor] = None,
810
+ attention_mask: Optional[torch.Tensor] = None,
811
+ position_ids: Optional[torch.Tensor] = None,
812
+ return_dict: Optional[bool] = None,
813
+ ) -> torch.FloatTensor:
814
+ r"""
815
+ Returns:
816
+ text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
817
+ applying the projection layer to the pooled output of [`BlipTextModel`].
818
+
819
+ Examples:
820
+
821
+ ```python
822
+ >>> from transformers import AutoProcessor, BlipModel
823
+
824
+ >>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
825
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
826
+
827
+ >>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
828
+ >>> text_features = model.get_text_features(**inputs)
829
+ ```"""
830
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
831
+
832
+ text_outputs = self.text_model(
833
+ input_ids=input_ids,
834
+ attention_mask=attention_mask,
835
+ position_ids=position_ids,
836
+ return_dict=return_dict,
837
+ )
838
+
839
+ pooled_output = text_outputs[1]
840
+ text_features = self.text_projection(pooled_output)
841
+
842
+ return text_features
843
+
844
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
845
+ def get_image_features(
846
+ self,
847
+ pixel_values: Optional[torch.FloatTensor] = None,
848
+ return_dict: Optional[bool] = None,
849
+ interpolate_pos_encoding: bool = False,
850
+ ) -> torch.FloatTensor:
851
+ r"""
852
+ Returns:
853
+ image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
854
+ applying the projection layer to the pooled output of [`BlipVisionModel`].
855
+
856
+ Examples:
857
+
858
+ ```python
859
+ >>> from PIL import Image
860
+ >>> import requests
861
+ >>> from transformers import AutoProcessor, BlipModel
862
+
863
+ >>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
864
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
865
+
866
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
867
+ >>> image = Image.open(requests.get(url, stream=True).raw)
868
+
869
+ >>> inputs = processor(images=image, return_tensors="pt")
870
+
871
+ >>> image_features = model.get_image_features(**inputs)
872
+ ```"""
873
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
874
+
875
+ vision_outputs = self.vision_model(
876
+ pixel_values=pixel_values,
877
+ return_dict=return_dict,
878
+ interpolate_pos_encoding=interpolate_pos_encoding,
879
+ )
880
+
881
+ pooled_output = vision_outputs[1] # pooled_output
882
+ image_features = self.visual_projection(pooled_output)
883
+
884
+ return image_features
885
+
886
+ @add_start_docstrings_to_model_forward(BLIP_INPUTS_DOCSTRING)
887
+ def get_multimodal_features(
888
+ self,
889
+ input_ids: Optional[torch.LongTensor] = None,
890
+ pixel_values: Optional[torch.FloatTensor] = None,
891
+ attention_mask: Optional[torch.Tensor] = None,
892
+ return_dict: Optional[bool] = None,
893
+ interpolate_pos_encoding: bool = False,
894
+ ) -> torch.FloatTensor:
895
+ r"""
896
+ Returns:
897
+ multimodal_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The multimodal embeddings
898
+ obtained by applying the image embeddings to the text encoder using the cross-attention mechanism.
899
+
900
+ Examples:
901
+ ```python
902
+ >>> from PIL import Image
903
+ >>> import requests
904
+ >>> from transformers import AutoProcessor, BlipModel
905
+
906
+ >>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
907
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
908
+
909
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
910
+ >>> image = Image.open(requests.get(url, stream=True).raw)
911
+ >>> texts = ["a photo of a cat", "a photo of a dog"]
912
+ >>> inputs = processor(images=image, text=texts, padding=True, return_tensors="pt")
913
+
914
+ >>> multimodal_features = model.get_multimodal_features(**inputs)
915
+ ```"""
916
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
917
+ vision_outputs = self.vision_model(
918
+ pixel_values=pixel_values,
919
+ output_attentions=True,
920
+ output_hidden_states=True,
921
+ return_dict=return_dict,
922
+ interpolate_pos_encoding=interpolate_pos_encoding,
923
+ )
924
+
925
+ image_embeds = vision_outputs[0]
926
+ image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long)
927
+
928
+ text_outputs = self.text_model(
929
+ input_ids=input_ids,
930
+ attention_mask=attention_mask,
931
+ encoder_hidden_states=image_embeds,
932
+ encoder_attention_mask=image_atts,
933
+ return_dict=return_dict,
934
+ )
935
+
936
+ pooled_output = text_outputs[1] # pooled_output
937
+ multimodal_features = self.text_projection(pooled_output)
938
+
939
+ return multimodal_features
940
+
941
+ @add_start_docstrings_to_model_forward(BLIP_INPUTS_DOCSTRING)
942
+ @replace_return_docstrings(output_type=BlipOutput, config_class=BlipConfig)
943
+ def forward(
944
+ self,
945
+ input_ids: Optional[torch.LongTensor] = None,
946
+ pixel_values: Optional[torch.FloatTensor] = None,
947
+ attention_mask: Optional[torch.Tensor] = None,
948
+ position_ids: Optional[torch.LongTensor] = None,
949
+ return_loss: Optional[bool] = None,
950
+ output_attentions: Optional[bool] = None,
951
+ output_hidden_states: Optional[bool] = None,
952
+ return_dict: Optional[bool] = None,
953
+ interpolate_pos_encoding: bool = False,
954
+ ) -> Union[Tuple, BlipOutput]:
955
+ r"""
956
+ Returns:
957
+
958
+ Examples:
959
+
960
+ ```python
961
+ >>> from PIL import Image
962
+ >>> import requests
963
+ >>> from transformers import AutoProcessor, BlipModel
964
+
965
+ >>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
966
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
967
+
968
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
969
+ >>> image = Image.open(requests.get(url, stream=True).raw)
970
+
971
+ >>> inputs = processor(
972
+ ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
973
+ ... )
974
+
975
+ >>> outputs = model(**inputs)
976
+ >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
977
+ >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
978
+ ```"""
979
+ # Use BLIP model's config for some fields (if specified) instead of those of vision & text components.
980
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
981
+ output_hidden_states = (
982
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
983
+ )
984
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
985
+
986
+ vision_outputs = self.vision_model(
987
+ pixel_values=pixel_values,
988
+ output_attentions=output_attentions,
989
+ output_hidden_states=output_hidden_states,
990
+ return_dict=return_dict,
991
+ interpolate_pos_encoding=interpolate_pos_encoding,
992
+ )
993
+
994
+ text_outputs = self.text_model(
995
+ input_ids=input_ids,
996
+ attention_mask=attention_mask,
997
+ position_ids=position_ids,
998
+ output_attentions=output_attentions,
999
+ output_hidden_states=output_hidden_states,
1000
+ return_dict=return_dict,
1001
+ )
1002
+
1003
+ image_embeds = vision_outputs[1]
1004
+ image_embeds = self.visual_projection(image_embeds)
1005
+
1006
+ text_embeds = text_outputs[1]
1007
+ text_embeds = self.text_projection(text_embeds)
1008
+
1009
+ # normalized features
1010
+ image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
1011
+ text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
1012
+
1013
+ # cosine similarity as logits
1014
+ logit_scale = self.logit_scale.exp().to(device=text_embeds.device)
1015
+ image_embeds = image_embeds.to(device=text_embeds.device, dtype=text_embeds.dtype)
1016
+ logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
1017
+ logits_per_image = logits_per_text.t()
1018
+
1019
+ loss = None
1020
+ if return_loss:
1021
+ loss = blip_loss(logits_per_text)
1022
+
1023
+ if not return_dict:
1024
+ output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
1025
+ return ((loss,) + output) if loss is not None else output
1026
+
1027
+ return BlipOutput(
1028
+ loss=loss,
1029
+ logits_per_image=logits_per_image,
1030
+ logits_per_text=logits_per_text,
1031
+ text_embeds=text_embeds,
1032
+ image_embeds=image_embeds,
1033
+ text_model_output=text_outputs,
1034
+ vision_model_output=vision_outputs,
1035
+ )
1036
+
1037
+
1038
+ @add_start_docstrings(
1039
+ """
1040
+ BLIP Model for image captioning. The model consists of a vision encoder and a text decoder. One can optionally pass
1041
+ `input_ids` to the model, which serve as a text prompt, to make the text decoder continue the prompt. Otherwise,
1042
+ the decoder starts generating text from the [BOS] (beginning-of-sequence) token. will start generating the caption
1043
+ from the text input. If no text input is provided, the decoder will start with the [BOS] token only.
1044
+ """,
1045
+ BLIP_START_DOCSTRING,
1046
+ )
1047
+ class BlipForConditionalGeneration(BlipPreTrainedModel, GenerationMixin):
1048
+ config_class = BlipConfig
1049
+ _tied_weights_keys = ["text_decoder.cls.predictions.decoder.bias"]
1050
+ main_input_name = "pixel_values"
1051
+
1052
+ def __init__(self, config: BlipConfig):
1053
+ super().__init__(config)
1054
+
1055
+ self.vision_model = BlipVisionModel(config.vision_config)
1056
+
1057
+ self.text_decoder = BlipTextLMHeadModel(config.text_config)
1058
+
1059
+ self.decoder_input_ids = config.text_config.bos_token_id
1060
+ self.decoder_pad_token_id = config.text_config.pad_token_id
1061
+
1062
+ # Initialize weights and apply final processing
1063
+ self.post_init()
1064
+
1065
+ def get_input_embeddings(self):
1066
+ return self.text_decoder.get_input_embeddings()
1067
+
1068
+ def set_input_embeddings(self, value):
1069
+ self.text_decoder.set_input_embeddings(value)
1070
+
1071
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
1072
+ @replace_return_docstrings(output_type=BlipForConditionalGenerationModelOutput, config_class=BlipVisionConfig)
1073
+ def forward(
1074
+ self,
1075
+ pixel_values: torch.FloatTensor,
1076
+ input_ids: Optional[torch.LongTensor] = None,
1077
+ attention_mask: Optional[torch.LongTensor] = None,
1078
+ output_attentions: Optional[bool] = None,
1079
+ output_hidden_states: Optional[bool] = None,
1080
+ labels: Optional[torch.LongTensor] = None,
1081
+ return_dict: Optional[bool] = None,
1082
+ interpolate_pos_encoding: bool = False,
1083
+ ) -> Union[Tuple, BlipForConditionalGenerationModelOutput]:
1084
+ r"""
1085
+ Returns:
1086
+
1087
+ Examples:
1088
+
1089
+ ```python
1090
+ >>> from PIL import Image
1091
+ >>> import requests
1092
+ >>> from transformers import AutoProcessor, BlipForConditionalGeneration
1093
+
1094
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
1095
+ >>> model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
1096
+
1097
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1098
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1099
+ >>> text = "A picture of"
1100
+
1101
+ >>> inputs = processor(images=image, text=text, return_tensors="pt")
1102
+
1103
+ >>> outputs = model(**inputs)
1104
+ ```"""
1105
+
1106
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1107
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1108
+ output_hidden_states = (
1109
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1110
+ )
1111
+
1112
+ vision_outputs = self.vision_model(
1113
+ pixel_values=pixel_values,
1114
+ output_attentions=output_attentions,
1115
+ output_hidden_states=output_hidden_states,
1116
+ return_dict=return_dict,
1117
+ interpolate_pos_encoding=interpolate_pos_encoding,
1118
+ )
1119
+
1120
+ image_embeds = vision_outputs[0]
1121
+
1122
+ outputs = self.text_decoder(
1123
+ input_ids=input_ids,
1124
+ attention_mask=attention_mask,
1125
+ encoder_hidden_states=image_embeds,
1126
+ labels=labels,
1127
+ return_dict=return_dict,
1128
+ reduction="mean",
1129
+ )
1130
+
1131
+ if not return_dict:
1132
+ outputs = (outputs[0], outputs[1]) if labels is not None else (outputs[0],)
1133
+ outputs += (image_embeds, vision_outputs[0]) + vision_outputs[2:]
1134
+ return tuple(output for output in outputs if output is not None)
1135
+
1136
+ return BlipForConditionalGenerationModelOutput(
1137
+ loss=outputs.loss,
1138
+ logits=outputs.logits,
1139
+ image_embeds=image_embeds,
1140
+ last_hidden_state=vision_outputs.last_hidden_state,
1141
+ hidden_states=vision_outputs.hidden_states,
1142
+ attentions=vision_outputs.attentions,
1143
+ )
1144
+
1145
+ @torch.no_grad()
1146
+ def generate(
1147
+ self,
1148
+ pixel_values: torch.FloatTensor,
1149
+ input_ids: Optional[torch.LongTensor] = None,
1150
+ attention_mask: Optional[torch.LongTensor] = None,
1151
+ interpolate_pos_encoding: bool = False,
1152
+ **generate_kwargs,
1153
+ ) -> torch.LongTensor:
1154
+ r"""
1155
+ Overrides *generate* function to be able to use the model as a conditional generator
1156
+
1157
+ Parameters:
1158
+ pixel_values (*torch.FloatTensor* of shape *(batch_size, num_channels, image_height, image_width)*:
1159
+ Input image to be processed
1160
+ input_ids (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
1161
+ The sequence used as a prompt for the generation.
1162
+ attention_mask (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
1163
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1164
+
1165
+
1166
+ Examples:
1167
+ ```python
1168
+ >>> from PIL import Image
1169
+ >>> import requests
1170
+ >>> from transformers import AutoProcessor, BlipForConditionalGeneration
1171
+
1172
+ >>> model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
1173
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
1174
+
1175
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1176
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1177
+
1178
+ >>> inputs = processor(images=image, return_tensors="pt")
1179
+
1180
+ >>> outputs = model.generate(**inputs)
1181
+ >>> print(processor.decode(outputs[0], skip_special_tokens=True))
1182
+ two cats sleeping on a couch
1183
+ ```
1184
+ """
1185
+
1186
+ batch_size = pixel_values.shape[0]
1187
+ vision_outputs = self.vision_model(
1188
+ pixel_values=pixel_values,
1189
+ interpolate_pos_encoding=interpolate_pos_encoding,
1190
+ )
1191
+
1192
+ image_embeds = vision_outputs[0]
1193
+
1194
+ image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(image_embeds.device)
1195
+
1196
+ if isinstance(input_ids, list):
1197
+ input_ids = torch.LongTensor(input_ids)
1198
+ elif input_ids is None:
1199
+ input_ids = (
1200
+ torch.LongTensor([[self.decoder_input_ids, self.config.text_config.eos_token_id]])
1201
+ .repeat(batch_size, 1)
1202
+ .to(image_embeds.device)
1203
+ )
1204
+
1205
+ input_ids[:, 0] = self.config.text_config.bos_token_id
1206
+ attention_mask = attention_mask[:, :-1] if attention_mask is not None else None
1207
+
1208
+ outputs = self.text_decoder.generate(
1209
+ input_ids=input_ids[:, :-1],
1210
+ eos_token_id=self.config.text_config.sep_token_id,
1211
+ pad_token_id=self.config.text_config.pad_token_id,
1212
+ attention_mask=attention_mask,
1213
+ encoder_hidden_states=image_embeds,
1214
+ encoder_attention_mask=image_attention_mask,
1215
+ **generate_kwargs,
1216
+ )
1217
+
1218
+ return outputs
1219
+
1220
+
1221
+ @add_start_docstrings(
1222
+ """
1223
+ BLIP Model for visual question answering. The model consists of a vision encoder, a text encoder as well as a text
1224
+ decoder. The vision encoder will encode the input image, the text encoder will encode the input question together
1225
+ with the encoding of the image, and the text decoder will output the answer to the question.
1226
+ """,
1227
+ BLIP_START_DOCSTRING,
1228
+ )
1229
+ class BlipForQuestionAnswering(BlipPreTrainedModel):
1230
+ config_class = BlipConfig
1231
+ _tied_weights_keys = ["text_decoder.cls.predictions.decoder.bias"]
1232
+
1233
+ def __init__(self, config: BlipConfig):
1234
+ super().__init__(config)
1235
+
1236
+ self.vision_model = BlipVisionModel(config.vision_config)
1237
+
1238
+ self.text_encoder = BlipTextModel(config.text_config, add_pooling_layer=False)
1239
+
1240
+ self.text_decoder = BlipTextLMHeadModel(config.text_config)
1241
+
1242
+ self.decoder_pad_token_id = config.text_config.pad_token_id
1243
+ self.decoder_start_token_id = config.text_config.bos_token_id
1244
+
1245
+ # Initialize weights and apply final processing
1246
+ self.post_init()
1247
+
1248
+ def set_input_embeddings(self, value):
1249
+ self.text_encoder.set_input_embeddings(value)
1250
+
1251
+ def get_input_embeddings(self):
1252
+ # This will return shared embeddings if they are shared else specific to encoder.
1253
+ return self.text_encoder.get_input_embeddings()
1254
+
1255
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
1256
+ @replace_return_docstrings(output_type=BlipTextVisionModelOutput, config_class=BlipVisionConfig)
1257
+ def forward(
1258
+ self,
1259
+ input_ids: torch.LongTensor,
1260
+ pixel_values: torch.FloatTensor,
1261
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1262
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1263
+ attention_mask: Optional[torch.LongTensor] = None,
1264
+ output_attentions: Optional[bool] = None,
1265
+ output_hidden_states: Optional[bool] = None,
1266
+ labels: Optional[torch.LongTensor] = None,
1267
+ return_dict: Optional[bool] = None,
1268
+ interpolate_pos_encoding: bool = False,
1269
+ ) -> Union[Tuple, BlipTextVisionModelOutput]:
1270
+ r"""
1271
+ Returns:
1272
+
1273
+ Examples:
1274
+
1275
+ ```python
1276
+ >>> from PIL import Image
1277
+ >>> import requests
1278
+ >>> from transformers import AutoProcessor, BlipForQuestionAnswering
1279
+
1280
+ >>> model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
1281
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")
1282
+
1283
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1284
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1285
+
1286
+ >>> # training
1287
+ >>> text = "How many cats are in the picture?"
1288
+ >>> label = "2"
1289
+ >>> inputs = processor(images=image, text=text, return_tensors="pt")
1290
+ >>> labels = processor(text=label, return_tensors="pt").input_ids
1291
+
1292
+ >>> inputs["labels"] = labels
1293
+ >>> outputs = model(**inputs)
1294
+ >>> loss = outputs.loss
1295
+ >>> loss.backward()
1296
+
1297
+ >>> # inference
1298
+ >>> text = "How many cats are in the picture?"
1299
+ >>> inputs = processor(images=image, text=text, return_tensors="pt")
1300
+ >>> outputs = model.generate(**inputs)
1301
+ >>> print(processor.decode(outputs[0], skip_special_tokens=True))
1302
+ 2
1303
+ ```"""
1304
+ if labels is None and decoder_input_ids is None:
1305
+ raise ValueError(
1306
+ "Either `decoder_input_ids` or `labels` should be passed when calling `forward` with"
1307
+ " `BlipForQuestionAnswering`. if you are training the model make sure that `labels` is passed, if you"
1308
+ " are using the model for inference make sure that `decoder_input_ids` is passed or call `generate`"
1309
+ )
1310
+
1311
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1312
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1313
+ output_hidden_states = (
1314
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1315
+ )
1316
+
1317
+ vision_outputs = self.vision_model(
1318
+ pixel_values=pixel_values,
1319
+ output_attentions=output_attentions,
1320
+ output_hidden_states=output_hidden_states,
1321
+ return_dict=return_dict,
1322
+ interpolate_pos_encoding=interpolate_pos_encoding,
1323
+ )
1324
+
1325
+ image_embeds = vision_outputs[0]
1326
+ image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long)
1327
+
1328
+ question_embeds = self.text_encoder(
1329
+ input_ids=input_ids,
1330
+ attention_mask=attention_mask,
1331
+ encoder_hidden_states=image_embeds,
1332
+ encoder_attention_mask=image_attention_mask,
1333
+ return_dict=return_dict,
1334
+ )
1335
+
1336
+ if labels is not None and decoder_input_ids is None:
1337
+ # labels are already shifted right, see: https://github.com/huggingface/transformers/pull/23153
1338
+ decoder_input_ids = labels
1339
+
1340
+ question_embeds = question_embeds[0] if not return_dict else question_embeds.last_hidden_state
1341
+
1342
+ answer_output = self.text_decoder(
1343
+ input_ids=decoder_input_ids,
1344
+ attention_mask=decoder_attention_mask,
1345
+ encoder_hidden_states=question_embeds,
1346
+ encoder_attention_mask=attention_mask,
1347
+ labels=labels,
1348
+ return_dict=return_dict,
1349
+ reduction="mean",
1350
+ )
1351
+
1352
+ if labels is not None:
1353
+ decoder_loss = answer_output.loss.mean() if return_dict else answer_output[0].mean()
1354
+ else:
1355
+ decoder_loss = None
1356
+
1357
+ if not return_dict:
1358
+ outputs = (decoder_loss, image_embeds, vision_outputs[0]) + vision_outputs[2:]
1359
+ return tuple(output for output in outputs if output is not None)
1360
+
1361
+ return BlipTextVisionModelOutput(
1362
+ loss=decoder_loss,
1363
+ image_embeds=image_embeds,
1364
+ last_hidden_state=vision_outputs.last_hidden_state,
1365
+ hidden_states=vision_outputs.hidden_states,
1366
+ attentions=vision_outputs.attentions,
1367
+ )
1368
+
1369
+ @torch.no_grad()
1370
+ def generate(
1371
+ self,
1372
+ input_ids: torch.LongTensor,
1373
+ pixel_values: torch.FloatTensor,
1374
+ attention_mask: Optional[torch.LongTensor] = None,
1375
+ interpolate_pos_encoding: bool = False,
1376
+ **generate_kwargs,
1377
+ ) -> torch.LongTensor:
1378
+ r"""
1379
+ Overrides *generate* function to be able to use the model as a conditional generator
1380
+
1381
+ Parameters:
1382
+ input_ids (*torch.LongTensor* of shape *(batch_size, sequence_length)*):
1383
+ The sequence used as a prompt for the generation.
1384
+ pixel_values (*torch.FloatTensor* of shape *(batch_size, num_channels, image_height, image_width)*:
1385
+ Input image to be processed
1386
+ attention_mask (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
1387
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`. `1` for
1388
+ tokens that are NOT MASKED, `0` for MASKED tokens.
1389
+ **generate_kwargs:
1390
+ Additional arguments passed to the *generate* function of the decoder
1391
+
1392
+
1393
+ Examples:
1394
+ ```python
1395
+ >>> from PIL import Image
1396
+ >>> import requests
1397
+ >>> from transformers import AutoProcessor, BlipForQuestionAnswering
1398
+
1399
+ >>> model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
1400
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")
1401
+
1402
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1403
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1404
+ >>> text = "How many cats are in the picture?"
1405
+
1406
+ >>> inputs = processor(images=image, text=text, return_tensors="pt")
1407
+
1408
+ >>> outputs = model.generate(**inputs)
1409
+ >>> print(processor.decode(outputs[0], skip_special_tokens=True))
1410
+ 2
1411
+ ```
1412
+ """
1413
+ vision_outputs = self.vision_model(
1414
+ pixel_values=pixel_values,
1415
+ interpolate_pos_encoding=interpolate_pos_encoding,
1416
+ )
1417
+
1418
+ image_embeds = vision_outputs[0]
1419
+
1420
+ image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(image_embeds.device)
1421
+
1422
+ if isinstance(input_ids, list):
1423
+ input_ids = torch.LongTensor(input_ids)
1424
+
1425
+ question_outputs = self.text_encoder(
1426
+ input_ids=input_ids,
1427
+ attention_mask=attention_mask,
1428
+ encoder_hidden_states=image_embeds,
1429
+ encoder_attention_mask=image_attention_mask,
1430
+ return_dict=False,
1431
+ )
1432
+
1433
+ question_embeds = question_outputs[0]
1434
+
1435
+ question_attention_mask = torch.ones(question_embeds.size()[:-1], dtype=torch.long).to(question_embeds.device)
1436
+
1437
+ bos_ids = torch.full(
1438
+ (question_embeds.size(0), 1), fill_value=self.decoder_start_token_id, device=question_embeds.device
1439
+ )
1440
+
1441
+ outputs = self.text_decoder.generate(
1442
+ input_ids=bos_ids,
1443
+ eos_token_id=self.config.text_config.sep_token_id,
1444
+ pad_token_id=self.config.text_config.pad_token_id,
1445
+ encoder_hidden_states=question_embeds,
1446
+ encoder_attention_mask=question_attention_mask,
1447
+ **generate_kwargs,
1448
+ )
1449
+
1450
+ return outputs
1451
+
1452
+
1453
+ @add_start_docstrings(
1454
+ """
1455
+ BLIP Model with a vision and text projector, and a classification head on top. The model is used in the context of
1456
+ image-text retrieval. Given an image and a text, the model returns the probability of the text being relevant to
1457
+ the image.
1458
+ """,
1459
+ BLIP_START_DOCSTRING,
1460
+ )
1461
+ class BlipForImageTextRetrieval(BlipPreTrainedModel):
1462
+ config_class = BlipConfig
1463
+
1464
+ def __init__(self, config: BlipConfig):
1465
+ super().__init__(config)
1466
+
1467
+ self.vision_model = BlipVisionModel(config.vision_config)
1468
+
1469
+ self.text_encoder = BlipTextModel(config.text_config, add_pooling_layer=False)
1470
+
1471
+ # vision projection layer
1472
+ self.vision_proj = nn.Linear(config.vision_config.hidden_size, config.image_text_hidden_size)
1473
+
1474
+ # text projection layer
1475
+ self.text_proj = nn.Linear(config.text_config.hidden_size, config.image_text_hidden_size)
1476
+
1477
+ # image text matching head
1478
+ self.itm_head = nn.Linear(config.text_config.hidden_size, 2)
1479
+
1480
+ self.decoder_pad_token_id = (
1481
+ config.text_config.pad_token_id
1482
+ if not hasattr(config, "decoder_pad_token_id")
1483
+ else config.decoder_pad_token_id
1484
+ )
1485
+ self.decoder_start_token_id = (
1486
+ config.text_config.bos_token_id
1487
+ if not hasattr(config, "decoder_start_token_id")
1488
+ else config.decoder_start_token_id
1489
+ )
1490
+
1491
+ # Initialize weights and apply final processing
1492
+ self.post_init()
1493
+
1494
+ def get_input_embeddings(self):
1495
+ return self.text_encoder.get_input_embeddings()
1496
+
1497
+ def set_input_embeddings(self, value):
1498
+ self.text_encoder.set_input_embeddings(value)
1499
+
1500
+ @add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
1501
+ @replace_return_docstrings(output_type=BlipTextVisionModelOutput, config_class=BlipVisionConfig)
1502
+ def forward(
1503
+ self,
1504
+ input_ids: torch.LongTensor,
1505
+ pixel_values: torch.FloatTensor,
1506
+ use_itm_head: Optional[bool] = True,
1507
+ attention_mask: Optional[torch.LongTensor] = None,
1508
+ output_attentions: Optional[bool] = None,
1509
+ output_hidden_states: Optional[bool] = None,
1510
+ return_dict: Optional[bool] = None,
1511
+ interpolate_pos_encoding: bool = False,
1512
+ ) -> Union[Tuple, BlipTextVisionModelOutput]:
1513
+ r"""
1514
+ Returns:
1515
+
1516
+ Examples:
1517
+
1518
+ ```python
1519
+ >>> from PIL import Image
1520
+ >>> import requests
1521
+ >>> from transformers import AutoProcessor, BlipForImageTextRetrieval
1522
+
1523
+ >>> model = BlipForImageTextRetrieval.from_pretrained("Salesforce/blip-itm-base-coco")
1524
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip-itm-base-coco")
1525
+
1526
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1527
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1528
+ >>> text = "an image of a cat"
1529
+
1530
+ >>> inputs = processor(images=image, text=text, return_tensors="pt")
1531
+ >>> outputs = model(**inputs)
1532
+ ```
1533
+ """
1534
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1535
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1536
+ output_hidden_states = (
1537
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1538
+ )
1539
+
1540
+ vision_outputs = self.vision_model(
1541
+ pixel_values=pixel_values,
1542
+ output_attentions=output_attentions,
1543
+ output_hidden_states=output_hidden_states,
1544
+ return_dict=return_dict,
1545
+ interpolate_pos_encoding=interpolate_pos_encoding,
1546
+ )
1547
+
1548
+ image_embeds = vision_outputs[0]
1549
+ image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long)
1550
+
1551
+ if use_itm_head:
1552
+ question_embeds = self.text_encoder(
1553
+ input_ids=input_ids,
1554
+ attention_mask=attention_mask,
1555
+ encoder_hidden_states=image_embeds,
1556
+ encoder_attention_mask=image_atts,
1557
+ return_dict=return_dict,
1558
+ )
1559
+ question_embeds = question_embeds[0] if not return_dict else question_embeds.last_hidden_state
1560
+
1561
+ output = self.itm_head(question_embeds[:, 0, :])
1562
+ else:
1563
+ question_embeds = self.text_encoder(
1564
+ input_ids=input_ids,
1565
+ attention_mask=attention_mask,
1566
+ return_dict=return_dict,
1567
+ )
1568
+ question_embeds = question_embeds[0] if not return_dict else question_embeds.last_hidden_state
1569
+
1570
+ image_feat = normalize(self.vision_proj(image_embeds[:, 0, :]), dim=-1)
1571
+ text_feat = normalize(self.text_proj(question_embeds[:, 0, :]), dim=-1)
1572
+
1573
+ output = image_feat @ text_feat.t()
1574
+
1575
+ if not return_dict:
1576
+ outputs = (output, vision_outputs[0]) + vision_outputs[2:] + (question_embeds,)
1577
+ return tuple(output for output in outputs if output is not None)
1578
+
1579
+ return BlipImageTextMatchingModelOutput(
1580
+ itm_score=output,
1581
+ last_hidden_state=vision_outputs.last_hidden_state,
1582
+ hidden_states=vision_outputs.hidden_states,
1583
+ attentions=vision_outputs.attentions,
1584
+ question_embeds=question_embeds,
1585
+ )
1586
+
1587
+
1588
+ __all__ = [
1589
+ "BlipModel",
1590
+ "BlipPreTrainedModel",
1591
+ "BlipForConditionalGeneration",
1592
+ "BlipForQuestionAnswering",
1593
+ "BlipVisionModel",
1594
+ "BlipTextModel",
1595
+ "BlipForImageTextRetrieval",
1596
+ ]
janus/lib/python3.10/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: 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: 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: 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: tf.Tensor = None
213
+ logits_per_text: tf.Tensor = None
214
+ text_embeds: tf.Tensor = None
215
+ image_embeds: 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: tf.Tensor = None,
313
+ position_ids: tf.Tensor = None,
314
+ inputs_embeds: 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
+ ]
janus/lib/python3.10/site-packages/transformers/models/decision_transformer/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_decision_transformer import *
22
+ from .modeling_decision_transformer import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
janus/lib/python3.10/site-packages/transformers/models/decision_transformer/__pycache__/modeling_decision_transformer.cpython-310.pyc ADDED
Binary file (25.7 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/decision_transformer/modeling_decision_transformer.py ADDED
@@ -0,0 +1,963 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Team 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 DecisionTransformer model."""
16
+
17
+ import math
18
+ import os
19
+ from dataclasses import dataclass
20
+ from typing import Callable, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+
26
+ from ...activations import ACT2FN
27
+ from ...modeling_outputs import BaseModelOutputWithPastAndCrossAttentions
28
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
29
+ from ...pytorch_utils import Conv1D, find_pruneable_heads_and_indices, prune_conv1d_layer
30
+ from ...utils import (
31
+ ModelOutput,
32
+ add_start_docstrings,
33
+ add_start_docstrings_to_model_forward,
34
+ logging,
35
+ replace_return_docstrings,
36
+ )
37
+ from .configuration_decision_transformer import DecisionTransformerConfig
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+ _CHECKPOINT_FOR_DOC = "edbeeching/decision-transformer-gym-hopper-medium"
43
+ _CONFIG_FOR_DOC = "DecisionTransformerConfig"
44
+
45
+
46
+ # Copied from transformers.models.gpt2.modeling_gpt2.load_tf_weights_in_gpt2
47
+ def load_tf_weights_in_gpt2(model, config, gpt2_checkpoint_path):
48
+ """Load tf checkpoints in a pytorch model"""
49
+ try:
50
+ import re
51
+
52
+ import tensorflow as tf
53
+ except ImportError:
54
+ logger.error(
55
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
56
+ "https://www.tensorflow.org/install/ for installation instructions."
57
+ )
58
+ raise
59
+ tf_path = os.path.abspath(gpt2_checkpoint_path)
60
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
61
+ # Load weights from TF model
62
+ init_vars = tf.train.list_variables(tf_path)
63
+ names = []
64
+ arrays = []
65
+ for name, shape in init_vars:
66
+ logger.info(f"Loading TF weight {name} with shape {shape}")
67
+ array = tf.train.load_variable(tf_path, name)
68
+ names.append(name)
69
+ arrays.append(array.squeeze())
70
+
71
+ for name, array in zip(names, arrays):
72
+ name = name[6:] # skip "model/"
73
+ name = name.split("/")
74
+ pointer = model
75
+ for m_name in name:
76
+ if re.fullmatch(r"[A-Za-z]+\d+", m_name):
77
+ scope_names = re.split(r"(\d+)", m_name)
78
+ else:
79
+ scope_names = [m_name]
80
+ if scope_names[0] == "w" or scope_names[0] == "g":
81
+ pointer = getattr(pointer, "weight")
82
+ elif scope_names[0] == "b":
83
+ pointer = getattr(pointer, "bias")
84
+ elif scope_names[0] == "wpe" or scope_names[0] == "wte":
85
+ pointer = getattr(pointer, scope_names[0])
86
+ pointer = getattr(pointer, "weight")
87
+ else:
88
+ pointer = getattr(pointer, scope_names[0])
89
+ if len(scope_names) >= 2:
90
+ num = int(scope_names[1])
91
+ pointer = pointer[num]
92
+ try:
93
+ if pointer.shape != array.shape:
94
+ raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
95
+ except ValueError as e:
96
+ e.args += (pointer.shape, array.shape)
97
+ raise
98
+ logger.info(f"Initialize PyTorch weight {name}")
99
+ pointer.data = torch.from_numpy(array)
100
+ return model
101
+
102
+
103
+ # Copied from transformers.models.gpt2.modeling_gpt2.eager_attention_forward
104
+ def eager_attention_forward(module, query, key, value, attention_mask, head_mask=None, **kwargs):
105
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
106
+
107
+ if module.scale_attn_weights:
108
+ attn_weights = attn_weights / torch.full(
109
+ [], value.size(-1) ** 0.5, dtype=attn_weights.dtype, device=attn_weights.device
110
+ )
111
+
112
+ # Layer-wise attention scaling
113
+ if module.scale_attn_by_inverse_layer_idx:
114
+ attn_weights = attn_weights / float(module.layer_idx + 1)
115
+
116
+ if not module.is_cross_attention:
117
+ # if only "normal" attention layer implements causal mask
118
+ query_length, key_length = query.size(-2), key.size(-2)
119
+ causal_mask = module.bias[:, :, key_length - query_length : key_length, :key_length]
120
+ mask_value = torch.finfo(attn_weights.dtype).min
121
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
122
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
123
+ mask_value = torch.full([], mask_value, dtype=attn_weights.dtype, device=attn_weights.device)
124
+ attn_weights = torch.where(causal_mask, attn_weights.to(attn_weights.dtype), mask_value)
125
+
126
+ if attention_mask is not None:
127
+ # Apply the attention mask
128
+ attn_weights = attn_weights + attention_mask
129
+
130
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
131
+
132
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise
133
+ attn_weights = attn_weights.type(value.dtype)
134
+ attn_weights = module.attn_dropout(attn_weights)
135
+
136
+ # Mask heads if we want to
137
+ if head_mask is not None:
138
+ attn_weights = attn_weights * head_mask
139
+
140
+ attn_output = torch.matmul(attn_weights, value)
141
+ attn_output = attn_output.transpose(1, 2)
142
+
143
+ return attn_output, attn_weights
144
+
145
+
146
+ # Copied from transformers.models.gpt2.modeling_gpt2.GPT2Attention with GPT2->DecisionTransformerGPT2
147
+ class DecisionTransformerGPT2Attention(nn.Module):
148
+ def __init__(self, config, is_cross_attention=False, layer_idx=None):
149
+ super().__init__()
150
+ self.config = config
151
+ max_positions = config.max_position_embeddings
152
+ self.register_buffer(
153
+ "bias",
154
+ torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
155
+ 1, 1, max_positions, max_positions
156
+ ),
157
+ persistent=False,
158
+ )
159
+ self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
160
+
161
+ self.embed_dim = config.hidden_size
162
+ self.num_heads = config.num_attention_heads
163
+ self.head_dim = self.embed_dim // self.num_heads
164
+ self.split_size = self.embed_dim
165
+ if self.head_dim * self.num_heads != self.embed_dim:
166
+ raise ValueError(
167
+ f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
168
+ f" {self.num_heads})."
169
+ )
170
+
171
+ self.scale_attn_weights = config.scale_attn_weights
172
+ self.is_cross_attention = is_cross_attention
173
+
174
+ # Layer-wise attention scaling, reordering, and upcasting
175
+ self.scale_attn_by_inverse_layer_idx = config.scale_attn_by_inverse_layer_idx
176
+ self.layer_idx = layer_idx
177
+ self.reorder_and_upcast_attn = config.reorder_and_upcast_attn
178
+
179
+ if self.is_cross_attention:
180
+ self.c_attn = Conv1D(2 * self.embed_dim, self.embed_dim)
181
+ self.q_attn = Conv1D(self.embed_dim, self.embed_dim)
182
+ else:
183
+ self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim)
184
+ self.c_proj = Conv1D(self.embed_dim, self.embed_dim)
185
+
186
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
187
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
188
+ self.is_causal = True
189
+
190
+ self.pruned_heads = set()
191
+
192
+ def prune_heads(self, heads):
193
+ if len(heads) == 0:
194
+ return
195
+ heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, self.head_dim, self.pruned_heads)
196
+ index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
197
+
198
+ # Prune conv1d layers
199
+ self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
200
+ self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
201
+
202
+ # Update hyper params
203
+ self.split_size = (self.split_size // self.num_heads) * (self.num_heads - len(heads))
204
+ self.num_heads = self.num_heads - len(heads)
205
+ self.pruned_heads = self.pruned_heads.union(heads)
206
+
207
+ def _upcast_and_reordered_attn(self, query, key, value, attention_mask=None, head_mask=None):
208
+ # Use `torch.baddbmm` (a bit more efficient w/ alpha param for scaling -- from Megatron-LM)
209
+ bsz, num_heads, q_seq_len, dk = query.size()
210
+ _, _, k_seq_len, _ = key.size()
211
+
212
+ # Preallocate attn_weights for `baddbmm`
213
+ attn_weights = torch.empty(bsz * num_heads, q_seq_len, k_seq_len, dtype=torch.float32, device=query.device)
214
+
215
+ # Compute Scale Factor
216
+ scale_factor = 1.0
217
+ if self.scale_attn_weights:
218
+ scale_factor /= float(value.size(-1)) ** 0.5
219
+
220
+ if self.scale_attn_by_inverse_layer_idx:
221
+ scale_factor /= float(self.layer_idx + 1)
222
+
223
+ # Upcast (turn off autocast) and reorder (Scale K by 1 / root(dk))
224
+ with torch.amp.autocast(query.device.type, enabled=False):
225
+ q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len)
226
+ attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor)
227
+ attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
228
+
229
+ if not self.is_cross_attention:
230
+ # if only "normal" attention layer implements causal mask
231
+ query_length, key_length = query.size(-2), key.size(-2)
232
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
233
+ mask_value = torch.finfo(attn_weights.dtype).min
234
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
235
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
236
+ mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
237
+ attn_weights = torch.where(causal_mask, attn_weights, mask_value)
238
+
239
+ if attention_mask is not None:
240
+ # Apply the attention mask
241
+ attn_weights = attn_weights + attention_mask
242
+
243
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
244
+
245
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op if otherwise
246
+ if attn_weights.dtype != torch.float32:
247
+ raise RuntimeError("Error with upcasting, attn_weights does not have dtype torch.float32")
248
+ attn_weights = attn_weights.type(value.dtype)
249
+ attn_weights = self.attn_dropout(attn_weights)
250
+
251
+ # Mask heads if we want to
252
+ if head_mask is not None:
253
+ attn_weights = attn_weights * head_mask
254
+
255
+ attn_output = torch.matmul(attn_weights, value)
256
+ attn_output = attn_output.transpose(1, 2)
257
+
258
+ return attn_output, attn_weights
259
+
260
+ def forward(
261
+ self,
262
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
263
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
264
+ attention_mask: Optional[torch.FloatTensor] = None,
265
+ head_mask: Optional[torch.FloatTensor] = None,
266
+ encoder_hidden_states: Optional[torch.Tensor] = None,
267
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
268
+ use_cache: Optional[bool] = False,
269
+ output_attentions: Optional[bool] = False,
270
+ **kwargs,
271
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
272
+ if encoder_hidden_states is not None:
273
+ if not hasattr(self, "q_attn"):
274
+ raise ValueError(
275
+ "If class is used as cross attention, the weights `q_attn` have to be defined. "
276
+ "Please make sure to instantiate class with `DecisionTransformerGPT2Attention(..., is_cross_attention=True)`."
277
+ )
278
+
279
+ query_states = self.q_attn(hidden_states)
280
+ key_states, value_states = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
281
+ attention_mask = encoder_attention_mask
282
+ else:
283
+ query_states, key_states, value_states = self.c_attn(hidden_states).split(self.split_size, dim=2)
284
+
285
+ shape_q = (*query_states.shape[:-1], -1, self.head_dim)
286
+ shape_kv = (*key_states.shape[:-1], -1, self.head_dim)
287
+
288
+ query_states = query_states.view(shape_q).transpose(1, 2)
289
+ key_states = key_states.view(shape_kv).transpose(1, 2)
290
+ value_states = value_states.view(shape_kv).transpose(1, 2)
291
+
292
+ if layer_past is not None:
293
+ past_key, past_value = layer_past
294
+ key_states = torch.cat((past_key, key_states), dim=-2)
295
+ value_states = torch.cat((past_value, value_states), dim=-2)
296
+
297
+ if use_cache is True:
298
+ present = (key_states, value_states)
299
+ else:
300
+ present = None
301
+
302
+ is_cross_attention = encoder_hidden_states is not None
303
+ is_causal = attention_mask is None and query_states.shape[-2] > 1 and not is_cross_attention
304
+
305
+ using_eager = self.config._attn_implementation == "eager"
306
+ attention_interface: Callable = eager_attention_forward
307
+ if self.config._attn_implementation != "eager":
308
+ if self.config._attn_implementation == "sdpa" and (output_attentions or head_mask is not None):
309
+ using_eager = True
310
+ logger.warning_once(
311
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
312
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
313
+ )
314
+ else:
315
+ # Attention functions are consistent with previous equivalent attention classes, however they do not support some options
316
+ # (e.g. layer scaling, head mask) that eager supports. These implementations are thus equivalent to previous code, but
317
+ # not necessarily to eager (if mentionned options are provided).
318
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
319
+
320
+ if using_eager and self.reorder_and_upcast_attn:
321
+ attn_output, attn_weights = self._upcast_and_reordered_attn(
322
+ query_states, key_states, value_states, attention_mask, head_mask
323
+ )
324
+ else:
325
+ attn_output, attn_weights = attention_interface(
326
+ self,
327
+ query_states,
328
+ key_states,
329
+ value_states,
330
+ attention_mask,
331
+ head_mask=head_mask,
332
+ dropout=self.attn_dropout.p if self.training else 0.0,
333
+ is_causal=is_causal,
334
+ **kwargs,
335
+ )
336
+
337
+ attn_output = attn_output.reshape(*attn_output.shape[:-2], -1).contiguous()
338
+ attn_output = self.c_proj(attn_output)
339
+ attn_output = self.resid_dropout(attn_output)
340
+
341
+ outputs = (attn_output, present)
342
+ if output_attentions:
343
+ outputs += (attn_weights,)
344
+
345
+ return outputs # a, present, (attentions)
346
+
347
+
348
+ # Copied from transformers.models.gpt2.modeling_gpt2.GPT2MLP with GPT2->DecisionTransformerGPT2
349
+ class DecisionTransformerGPT2MLP(nn.Module):
350
+ def __init__(self, intermediate_size, config):
351
+ super().__init__()
352
+ embed_dim = config.hidden_size
353
+ self.c_fc = Conv1D(intermediate_size, embed_dim)
354
+ self.c_proj = Conv1D(embed_dim, intermediate_size)
355
+ self.act = ACT2FN[config.activation_function]
356
+ self.dropout = nn.Dropout(config.resid_pdrop)
357
+
358
+ def forward(self, hidden_states: Optional[Tuple[torch.FloatTensor]]) -> torch.FloatTensor:
359
+ hidden_states = self.c_fc(hidden_states)
360
+ hidden_states = self.act(hidden_states)
361
+ hidden_states = self.c_proj(hidden_states)
362
+ hidden_states = self.dropout(hidden_states)
363
+ return hidden_states
364
+
365
+
366
+ # Copied from transformers.models.gpt2.modeling_gpt2.GPT2Block with GPT2->DecisionTransformerGPT2
367
+ class DecisionTransformerGPT2Block(nn.Module):
368
+ # Ignore copy
369
+ def __init__(self, config, layer_idx=None):
370
+ super().__init__()
371
+ hidden_size = config.hidden_size
372
+ inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
373
+
374
+ self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
375
+ self.attn = DecisionTransformerGPT2Attention(config, layer_idx=layer_idx)
376
+ self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
377
+
378
+ if config.add_cross_attention:
379
+ self.crossattention = DecisionTransformerGPT2Attention(
380
+ config, is_cross_attention=True, layer_idx=layer_idx
381
+ )
382
+ self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
383
+
384
+ self.mlp = DecisionTransformerGPT2MLP(inner_dim, config)
385
+
386
+ def forward(
387
+ self,
388
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
389
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
390
+ attention_mask: Optional[torch.FloatTensor] = None,
391
+ head_mask: Optional[torch.FloatTensor] = None,
392
+ encoder_hidden_states: Optional[torch.Tensor] = None,
393
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
394
+ use_cache: Optional[bool] = False,
395
+ output_attentions: Optional[bool] = False,
396
+ ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
397
+ residual = hidden_states
398
+ hidden_states = self.ln_1(hidden_states)
399
+ attn_outputs = self.attn(
400
+ hidden_states,
401
+ layer_past=layer_past,
402
+ attention_mask=attention_mask,
403
+ head_mask=head_mask,
404
+ use_cache=use_cache,
405
+ output_attentions=output_attentions,
406
+ )
407
+ attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
408
+ outputs = attn_outputs[1:]
409
+ # residual connection
410
+ hidden_states = attn_output + residual
411
+
412
+ if encoder_hidden_states is not None:
413
+ # add one self-attention block for cross-attention
414
+ if not hasattr(self, "crossattention"):
415
+ raise ValueError(
416
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
417
+ "cross-attention layers by setting `config.add_cross_attention=True`"
418
+ )
419
+ residual = hidden_states
420
+ hidden_states = self.ln_cross_attn(hidden_states)
421
+ cross_attn_outputs = self.crossattention(
422
+ hidden_states,
423
+ attention_mask=attention_mask,
424
+ head_mask=head_mask,
425
+ encoder_hidden_states=encoder_hidden_states,
426
+ encoder_attention_mask=encoder_attention_mask,
427
+ output_attentions=output_attentions,
428
+ )
429
+ attn_output = cross_attn_outputs[0]
430
+ # residual connection
431
+ hidden_states = residual + attn_output
432
+ outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
433
+
434
+ residual = hidden_states
435
+ hidden_states = self.ln_2(hidden_states)
436
+ feed_forward_hidden_states = self.mlp(hidden_states)
437
+ # residual connection
438
+ hidden_states = residual + feed_forward_hidden_states
439
+
440
+ if use_cache:
441
+ outputs = (hidden_states,) + outputs
442
+ else:
443
+ outputs = (hidden_states,) + outputs[1:]
444
+
445
+ return outputs # hidden_states, present, (attentions, cross_attentions)
446
+
447
+
448
+ class DecisionTransformerGPT2PreTrainedModel(PreTrainedModel):
449
+ """
450
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
451
+ models.
452
+ """
453
+
454
+ config_class = DecisionTransformerConfig
455
+ load_tf_weights = load_tf_weights_in_gpt2
456
+ base_model_prefix = "transformer"
457
+ is_parallelizable = True
458
+ supports_gradient_checkpointing = True
459
+
460
+ def __init__(self, *inputs, **kwargs):
461
+ super().__init__(*inputs, **kwargs)
462
+
463
+ def _init_weights(self, module):
464
+ """Initialize the weights."""
465
+ if isinstance(module, (nn.Linear, Conv1D)):
466
+ # Slightly different from the TF version which uses truncated_normal for initialization
467
+ # cf https://github.com/pytorch/pytorch/pull/5617
468
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
469
+ if module.bias is not None:
470
+ module.bias.data.zero_()
471
+ elif isinstance(module, nn.Embedding):
472
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
473
+ if module.padding_idx is not None:
474
+ module.weight.data[module.padding_idx].zero_()
475
+ elif isinstance(module, nn.LayerNorm):
476
+ module.bias.data.zero_()
477
+ module.weight.data.fill_(1.0)
478
+
479
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
480
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
481
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
482
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
483
+ #
484
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
485
+ for name, p in module.named_parameters():
486
+ if "c_proj" in name and "weight" in name:
487
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
488
+ p.data.normal_(mean=0.0, std=(self.config.initializer_range / math.sqrt(2 * self.config.n_layer)))
489
+
490
+
491
+ class DecisionTransformerGPT2Model(DecisionTransformerGPT2PreTrainedModel):
492
+ def __init__(self, config):
493
+ super().__init__(config)
494
+
495
+ self.embed_dim = config.hidden_size
496
+
497
+ self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
498
+ self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
499
+
500
+ self.drop = nn.Dropout(config.embd_pdrop)
501
+ self.h = nn.ModuleList(
502
+ [DecisionTransformerGPT2Block(config, layer_idx=i) for i in range(config.num_hidden_layers)]
503
+ )
504
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
505
+
506
+ # Model parallel
507
+ self.model_parallel = False
508
+ self.device_map = None
509
+ self.gradient_checkpointing = False
510
+
511
+ # Initialize weights and apply final processing
512
+ self.post_init()
513
+
514
+ def get_input_embeddings(self):
515
+ return self.wte
516
+
517
+ def set_input_embeddings(self, new_embeddings):
518
+ self.wte = new_embeddings
519
+
520
+ def forward(
521
+ self,
522
+ input_ids: Optional[torch.LongTensor] = None,
523
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
524
+ attention_mask: Optional[torch.FloatTensor] = None,
525
+ token_type_ids: Optional[torch.LongTensor] = None,
526
+ position_ids: Optional[torch.LongTensor] = None,
527
+ head_mask: Optional[torch.FloatTensor] = None,
528
+ inputs_embeds: Optional[torch.FloatTensor] = None,
529
+ encoder_hidden_states: Optional[torch.Tensor] = None,
530
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
531
+ use_cache: Optional[bool] = None,
532
+ output_attentions: Optional[bool] = None,
533
+ output_hidden_states: Optional[bool] = None,
534
+ return_dict: Optional[bool] = None,
535
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
536
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
537
+ output_hidden_states = (
538
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
539
+ )
540
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
541
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
542
+
543
+ if input_ids is not None and inputs_embeds is not None:
544
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
545
+ elif input_ids is not None:
546
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
547
+ input_shape = input_ids.size()
548
+ input_ids = input_ids.view(-1, input_shape[-1])
549
+ batch_size = input_ids.shape[0]
550
+ elif inputs_embeds is not None:
551
+ input_shape = inputs_embeds.size()[:-1]
552
+ batch_size = inputs_embeds.shape[0]
553
+ else:
554
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
555
+
556
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
557
+
558
+ if token_type_ids is not None:
559
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
560
+
561
+ if past_key_values is None:
562
+ past_length = 0
563
+ past_key_values = tuple([None] * len(self.h))
564
+ else:
565
+ past_length = past_key_values[0][0].size(-2)
566
+ if position_ids is None:
567
+ position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
568
+ position_ids = position_ids.unsqueeze(0)
569
+
570
+ # Attention mask.
571
+ if attention_mask is not None:
572
+ if batch_size <= 0:
573
+ raise ValueError("batch_size has to be defined and > 0")
574
+ attention_mask = attention_mask.view(batch_size, -1)
575
+ # We create a 3D attention mask from a 2D tensor mask.
576
+ # Sizes are [batch_size, 1, 1, to_seq_length]
577
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
578
+ # this attention mask is more simple than the triangular masking of causal attention
579
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
580
+ attention_mask = attention_mask[:, None, None, :]
581
+
582
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
583
+ # masked positions, this operation will create a tensor which is 0.0 for
584
+ # positions we want to attend and the dtype's smallest value for masked positions.
585
+ # Since we are adding it to the raw scores before the softmax, this is
586
+ # effectively the same as removing these entirely.
587
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
588
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
589
+
590
+ # If a 2D or 3D attention mask is provided for the cross-attention
591
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
592
+ if self.config.add_cross_attention and encoder_hidden_states is not None:
593
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
594
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
595
+ if encoder_attention_mask is None:
596
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
597
+ encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
598
+ else:
599
+ encoder_attention_mask = None
600
+
601
+ # Prepare head mask if needed
602
+ # 1.0 in head_mask indicate we keep the head
603
+ # attention_probs has shape bsz x n_heads x N x N
604
+ # head_mask has shape n_layer x batch x n_heads x N x N
605
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
606
+
607
+ if inputs_embeds is None:
608
+ inputs_embeds = self.wte(input_ids)
609
+ position_embeds = self.wpe(position_ids)
610
+ hidden_states = inputs_embeds + position_embeds
611
+
612
+ if token_type_ids is not None:
613
+ token_type_embeds = self.wte(token_type_ids)
614
+ hidden_states = hidden_states + token_type_embeds
615
+
616
+ hidden_states = self.drop(hidden_states)
617
+
618
+ output_shape = (-1,) + input_shape[1:] + (hidden_states.size(-1),)
619
+
620
+ if self.gradient_checkpointing and self.training:
621
+ if use_cache:
622
+ logger.warning_once(
623
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
624
+ )
625
+ use_cache = False
626
+
627
+ presents = () if use_cache else None
628
+ all_self_attentions = () if output_attentions else None
629
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
630
+ all_hidden_states = () if output_hidden_states else None
631
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
632
+ # Model parallel
633
+ if self.model_parallel:
634
+ torch.cuda.set_device(hidden_states.device)
635
+ # Ensure layer_past is on same device as hidden_states (might not be correct)
636
+ if layer_past is not None:
637
+ layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)
638
+ # Ensure that attention_mask is always on the same device as hidden_states
639
+ if attention_mask is not None:
640
+ attention_mask = attention_mask.to(hidden_states.device)
641
+ if isinstance(head_mask, torch.Tensor):
642
+ head_mask = head_mask.to(hidden_states.device)
643
+ if output_hidden_states:
644
+ all_hidden_states = all_hidden_states + (hidden_states,)
645
+
646
+ if self.gradient_checkpointing and self.training:
647
+ outputs = self._gradient_checkpointing_func(
648
+ block.__call__,
649
+ hidden_states,
650
+ None,
651
+ attention_mask,
652
+ head_mask[i],
653
+ encoder_hidden_states,
654
+ encoder_attention_mask,
655
+ use_cache,
656
+ output_attentions,
657
+ )
658
+ else:
659
+ outputs = block(
660
+ hidden_states,
661
+ layer_past=layer_past,
662
+ attention_mask=attention_mask,
663
+ head_mask=head_mask[i],
664
+ encoder_hidden_states=encoder_hidden_states,
665
+ encoder_attention_mask=encoder_attention_mask,
666
+ use_cache=use_cache,
667
+ output_attentions=output_attentions,
668
+ )
669
+
670
+ hidden_states = outputs[0]
671
+ if use_cache is True:
672
+ presents = presents + (outputs[1],)
673
+
674
+ if output_attentions:
675
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
676
+ if self.config.add_cross_attention:
677
+ all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
678
+
679
+ # Model Parallel: If it's the last layer for that device, put things on the next device
680
+ if self.model_parallel:
681
+ for k, v in self.device_map.items():
682
+ if i == v[-1] and "cuda:" + str(k) != self.last_device:
683
+ hidden_states = hidden_states.to("cuda:" + str(k + 1))
684
+
685
+ hidden_states = self.ln_f(hidden_states)
686
+
687
+ hidden_states = hidden_states.view(output_shape)
688
+ # Add last hidden state
689
+ if output_hidden_states:
690
+ all_hidden_states = all_hidden_states + (hidden_states,)
691
+
692
+ if not return_dict:
693
+ return tuple(
694
+ v
695
+ for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions]
696
+ if v is not None
697
+ )
698
+
699
+ return BaseModelOutputWithPastAndCrossAttentions(
700
+ last_hidden_state=hidden_states,
701
+ past_key_values=presents,
702
+ hidden_states=all_hidden_states,
703
+ attentions=all_self_attentions,
704
+ cross_attentions=all_cross_attentions,
705
+ )
706
+
707
+
708
+ @dataclass
709
+ class DecisionTransformerOutput(ModelOutput):
710
+ """
711
+ Base class for model's outputs that also contains a pooling of the last hidden states.
712
+
713
+ Args:
714
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
715
+ Sequence of hidden-states at the output of the last layer of the model.
716
+ state_preds (`torch.FloatTensor` of shape `(batch_size, sequence_length, state_dim)`):
717
+ Environment state predictions
718
+ action_preds (`torch.FloatTensor` of shape `(batch_size, sequence_length, action_dim)`):
719
+ Model action predictions
720
+ return_preds (`torch.FloatTensor` of shape `(batch_size, sequence_length, 1)`):
721
+ Predicted returns for each state
722
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
723
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
724
+ shape `(batch_size, sequence_length, hidden_size)`.
725
+
726
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
727
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
728
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
729
+ sequence_length)`.
730
+
731
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
732
+ heads.
733
+ """
734
+
735
+ state_preds: torch.FloatTensor = None
736
+ action_preds: torch.FloatTensor = None
737
+ return_preds: torch.FloatTensor = None
738
+ hidden_states: torch.FloatTensor = None
739
+ attentions: torch.FloatTensor = None
740
+ last_hidden_state: torch.FloatTensor = None
741
+
742
+
743
+ class DecisionTransformerPreTrainedModel(PreTrainedModel):
744
+ """
745
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
746
+ models.
747
+ """
748
+
749
+ config_class = DecisionTransformerConfig
750
+ base_model_prefix = "decision_transformer"
751
+ main_input_name = "states"
752
+ supports_gradient_checkpointing = False
753
+
754
+ def _init_weights(self, module):
755
+ """Initialize the weights"""
756
+ if isinstance(module, nn.Linear):
757
+ # Slightly different from the TF version which uses truncated_normal for initialization
758
+ # cf https://github.com/pytorch/pytorch/pull/5617
759
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
760
+ if module.bias is not None:
761
+ module.bias.data.zero_()
762
+ elif isinstance(module, nn.Embedding):
763
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
764
+ if module.padding_idx is not None:
765
+ module.weight.data[module.padding_idx].zero_()
766
+ elif isinstance(module, nn.LayerNorm):
767
+ module.bias.data.zero_()
768
+ module.weight.data.fill_(1.0)
769
+
770
+
771
+ DECISION_TRANSFORMER_START_DOCSTRING = r"""
772
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
773
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
774
+ behavior.
775
+
776
+ Parameters:
777
+ config ([`~DecisionTransformerConfig`]): Model configuration class with all the parameters of the model.
778
+ Initializing with a config file does not load the weights associated with the model, only the
779
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
780
+ """
781
+
782
+ DECISION_TRANSFORMER_INPUTS_DOCSTRING = r"""
783
+ Args:
784
+ states (`torch.FloatTensor` of shape `(batch_size, episode_length, state_dim)`):
785
+ The states for each step in the trajectory
786
+ actions (`torch.FloatTensor` of shape `(batch_size, episode_length, act_dim)`):
787
+ The actions taken by the "expert" policy for the current state, these are masked for auto regressive
788
+ prediction
789
+ rewards (`torch.FloatTensor` of shape `(batch_size, episode_length, 1)`):
790
+ The rewards for each state, action
791
+ returns_to_go (`torch.FloatTensor` of shape `(batch_size, episode_length, 1)`):
792
+ The returns for each state in the trajectory
793
+ timesteps (`torch.LongTensor` of shape `(batch_size, episode_length)`):
794
+ The timestep for each step in the trajectory
795
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, episode_length)`):
796
+ Masking, used to mask the actions when performing autoregressive prediction
797
+ """
798
+
799
+
800
+ @add_start_docstrings("The Decision Transformer Model", DECISION_TRANSFORMER_START_DOCSTRING)
801
+ class DecisionTransformerModel(DecisionTransformerPreTrainedModel):
802
+ """
803
+
804
+ The model builds upon the GPT2 architecture to perform autoregressive prediction of actions in an offline RL
805
+ setting. Refer to the paper for more details: https://arxiv.org/abs/2106.01345
806
+
807
+ """
808
+
809
+ def __init__(self, config):
810
+ super().__init__(config)
811
+ self.config = config
812
+ self.hidden_size = config.hidden_size
813
+ # note: the only difference between this GPT2Model and the default Huggingface version
814
+ # is that the positional embeddings are removed (since we'll add those ourselves)
815
+ self.encoder = DecisionTransformerGPT2Model(config)
816
+
817
+ self.embed_timestep = nn.Embedding(config.max_ep_len, config.hidden_size)
818
+ self.embed_return = torch.nn.Linear(1, config.hidden_size)
819
+ self.embed_state = torch.nn.Linear(config.state_dim, config.hidden_size)
820
+ self.embed_action = torch.nn.Linear(config.act_dim, config.hidden_size)
821
+
822
+ self.embed_ln = nn.LayerNorm(config.hidden_size)
823
+
824
+ # note: we don't predict states or returns for the paper
825
+ self.predict_state = torch.nn.Linear(config.hidden_size, config.state_dim)
826
+ self.predict_action = nn.Sequential(
827
+ *([nn.Linear(config.hidden_size, config.act_dim)] + ([nn.Tanh()] if config.action_tanh else []))
828
+ )
829
+ self.predict_return = torch.nn.Linear(config.hidden_size, 1)
830
+
831
+ # Initialize weights and apply final processing
832
+ self.post_init()
833
+
834
+ @add_start_docstrings_to_model_forward(DECISION_TRANSFORMER_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
835
+ @replace_return_docstrings(output_type=DecisionTransformerOutput, config_class=_CONFIG_FOR_DOC)
836
+ def forward(
837
+ self,
838
+ states: Optional[torch.FloatTensor] = None,
839
+ actions: Optional[torch.FloatTensor] = None,
840
+ rewards: Optional[torch.FloatTensor] = None,
841
+ returns_to_go: Optional[torch.FloatTensor] = None,
842
+ timesteps: Optional[torch.LongTensor] = None,
843
+ attention_mask: Optional[torch.FloatTensor] = None,
844
+ output_hidden_states: Optional[bool] = None,
845
+ output_attentions: Optional[bool] = None,
846
+ return_dict: Optional[bool] = None,
847
+ ) -> Union[Tuple[torch.FloatTensor], DecisionTransformerOutput]:
848
+ r"""
849
+ Returns:
850
+
851
+ Examples:
852
+
853
+ ```python
854
+ >>> from transformers import DecisionTransformerModel
855
+ >>> import torch
856
+
857
+ >>> model = DecisionTransformerModel.from_pretrained("edbeeching/decision-transformer-gym-hopper-medium")
858
+ >>> # evaluation
859
+ >>> model = model.to(device)
860
+ >>> model.eval()
861
+
862
+ >>> env = gym.make("Hopper-v3")
863
+ >>> state_dim = env.observation_space.shape[0]
864
+ >>> act_dim = env.action_space.shape[0]
865
+
866
+ >>> state = env.reset()
867
+ >>> states = torch.from_numpy(state).reshape(1, 1, state_dim).to(device=device, dtype=torch.float32)
868
+ >>> actions = torch.zeros((1, 1, act_dim), device=device, dtype=torch.float32)
869
+ >>> rewards = torch.zeros(1, 1, device=device, dtype=torch.float32)
870
+ >>> target_return = torch.tensor(TARGET_RETURN, dtype=torch.float32).reshape(1, 1)
871
+ >>> timesteps = torch.tensor(0, device=device, dtype=torch.long).reshape(1, 1)
872
+ >>> attention_mask = torch.zeros(1, 1, device=device, dtype=torch.float32)
873
+
874
+ >>> # forward pass
875
+ >>> with torch.no_grad():
876
+ ... state_preds, action_preds, return_preds = model(
877
+ ... states=states,
878
+ ... actions=actions,
879
+ ... rewards=rewards,
880
+ ... returns_to_go=target_return,
881
+ ... timesteps=timesteps,
882
+ ... attention_mask=attention_mask,
883
+ ... return_dict=False,
884
+ ... )
885
+ ```"""
886
+
887
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
888
+ output_hidden_states = (
889
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
890
+ )
891
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
892
+
893
+ batch_size, seq_length = states.shape[0], states.shape[1]
894
+
895
+ if attention_mask is None:
896
+ # attention mask for GPT: 1 if can be attended to, 0 if not
897
+ attention_mask = torch.ones((batch_size, seq_length), dtype=torch.long)
898
+
899
+ # embed each modality with a different head
900
+ state_embeddings = self.embed_state(states)
901
+ action_embeddings = self.embed_action(actions)
902
+ returns_embeddings = self.embed_return(returns_to_go)
903
+ time_embeddings = self.embed_timestep(timesteps)
904
+
905
+ # time embeddings are treated similar to positional embeddings
906
+ state_embeddings = state_embeddings + time_embeddings
907
+ action_embeddings = action_embeddings + time_embeddings
908
+ returns_embeddings = returns_embeddings + time_embeddings
909
+
910
+ # this makes the sequence look like (R_1, s_1, a_1, R_2, s_2, a_2, ...)
911
+ # which works nice in an autoregressive sense since states predict actions
912
+ stacked_inputs = (
913
+ torch.stack((returns_embeddings, state_embeddings, action_embeddings), dim=1)
914
+ .permute(0, 2, 1, 3)
915
+ .reshape(batch_size, 3 * seq_length, self.hidden_size)
916
+ )
917
+ stacked_inputs = self.embed_ln(stacked_inputs)
918
+
919
+ # to make the attention mask fit the stacked inputs, have to stack it as well
920
+ stacked_attention_mask = (
921
+ torch.stack((attention_mask, attention_mask, attention_mask), dim=1)
922
+ .permute(0, 2, 1)
923
+ .reshape(batch_size, 3 * seq_length)
924
+ )
925
+ device = stacked_inputs.device
926
+ # we feed in the input embeddings (not word indices as in NLP) to the model
927
+ encoder_outputs = self.encoder(
928
+ inputs_embeds=stacked_inputs,
929
+ attention_mask=stacked_attention_mask,
930
+ position_ids=torch.zeros(stacked_attention_mask.shape, device=device, dtype=torch.long),
931
+ output_attentions=output_attentions,
932
+ output_hidden_states=output_hidden_states,
933
+ return_dict=return_dict,
934
+ )
935
+ x = encoder_outputs[0]
936
+
937
+ # reshape x so that the second dimension corresponds to the original
938
+ # returns (0), states (1), or actions (2); i.e. x[:,1,t] is the token for s_t
939
+ x = x.reshape(batch_size, seq_length, 3, self.hidden_size).permute(0, 2, 1, 3)
940
+
941
+ # get predictions
942
+ return_preds = self.predict_return(x[:, 2]) # predict next return given state and action
943
+ state_preds = self.predict_state(x[:, 2]) # predict next state given state and action
944
+ action_preds = self.predict_action(x[:, 1]) # predict next action given state
945
+ if not return_dict:
946
+ return (state_preds, action_preds, return_preds)
947
+
948
+ return DecisionTransformerOutput(
949
+ last_hidden_state=encoder_outputs.last_hidden_state,
950
+ state_preds=state_preds,
951
+ action_preds=action_preds,
952
+ return_preds=return_preds,
953
+ hidden_states=encoder_outputs.hidden_states,
954
+ attentions=encoder_outputs.attentions,
955
+ )
956
+
957
+
958
+ __all__ = [
959
+ "DecisionTransformerGPT2Model",
960
+ "DecisionTransformerGPT2PreTrainedModel",
961
+ "DecisionTransformerModel",
962
+ "DecisionTransformerPreTrainedModel",
963
+ ]
janus/lib/python3.10/site-packages/transformers/models/ernie/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_ernie import *
22
+ from .modeling_ernie import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
janus/lib/python3.10/site-packages/transformers/models/ernie/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (534 Bytes). View file
 
janus/lib/python3.10/site-packages/transformers/models/ernie/__pycache__/configuration_ernie.cpython-310.pyc ADDED
Binary file (6.8 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/ernie/__pycache__/modeling_ernie.cpython-310.pyc ADDED
Binary file (52.9 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/ernie/configuration_ernie.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ERNIE model configuration"""
17
+
18
+ from collections import OrderedDict
19
+ from typing import Mapping
20
+
21
+ from ...configuration_utils import PretrainedConfig
22
+ from ...onnx import OnnxConfig
23
+ from ...utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ class ErnieConfig(PretrainedConfig):
30
+ r"""
31
+ This is the configuration class to store the configuration of a [`ErnieModel`] or a [`TFErnieModel`]. It is used to
32
+ instantiate a ERNIE model according to the specified arguments, defining the model architecture. Instantiating a
33
+ configuration with the defaults will yield a similar configuration to that of the ERNIE
34
+ [nghuyong/ernie-3.0-base-zh](https://huggingface.co/nghuyong/ernie-3.0-base-zh) architecture.
35
+
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+
39
+
40
+ Args:
41
+ vocab_size (`int`, *optional*, defaults to 30522):
42
+ Vocabulary size of the ERNIE model. Defines the number of different tokens that can be represented by the
43
+ `inputs_ids` passed when calling [`ErnieModel`] or [`TFErnieModel`].
44
+ hidden_size (`int`, *optional*, defaults to 768):
45
+ Dimensionality of the encoder layers and the pooler layer.
46
+ num_hidden_layers (`int`, *optional*, defaults to 12):
47
+ Number of hidden layers in the Transformer encoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 12):
49
+ Number of attention heads for each attention layer in the Transformer encoder.
50
+ intermediate_size (`int`, *optional*, defaults to 3072):
51
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
52
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
53
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
54
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
55
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
56
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
57
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
58
+ The dropout ratio for the attention probabilities.
59
+ max_position_embeddings (`int`, *optional*, defaults to 512):
60
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
61
+ just in case (e.g., 512 or 1024 or 2048).
62
+ type_vocab_size (`int`, *optional*, defaults to 2):
63
+ The vocabulary size of the `token_type_ids` passed when calling [`ErnieModel`] or [`TFErnieModel`].
64
+ task_type_vocab_size (`int`, *optional*, defaults to 3):
65
+ The vocabulary size of the `task_type_ids` for ERNIE2.0/ERNIE3.0 model
66
+ use_task_id (`bool`, *optional*, defaults to `False`):
67
+ Whether or not the model support `task_type_ids`
68
+ initializer_range (`float`, *optional*, defaults to 0.02):
69
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
70
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
71
+ The epsilon used by the layer normalization layers.
72
+ pad_token_id (`int`, *optional*, defaults to 0):
73
+ Padding token id.
74
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
75
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
76
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
77
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
78
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
79
+ with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
80
+ use_cache (`bool`, *optional*, defaults to `True`):
81
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
82
+ relevant if `config.is_decoder=True`.
83
+ classifier_dropout (`float`, *optional*):
84
+ The dropout ratio for the classification head.
85
+
86
+ Examples:
87
+
88
+ ```python
89
+ >>> from transformers import ErnieConfig, ErnieModel
90
+
91
+ >>> # Initializing a ERNIE nghuyong/ernie-3.0-base-zh style configuration
92
+ >>> configuration = ErnieConfig()
93
+
94
+ >>> # Initializing a model (with random weights) from the nghuyong/ernie-3.0-base-zh style configuration
95
+ >>> model = ErnieModel(configuration)
96
+
97
+ >>> # Accessing the model configuration
98
+ >>> configuration = model.config
99
+ ```"""
100
+
101
+ model_type = "ernie"
102
+
103
+ def __init__(
104
+ self,
105
+ vocab_size=30522,
106
+ hidden_size=768,
107
+ num_hidden_layers=12,
108
+ num_attention_heads=12,
109
+ intermediate_size=3072,
110
+ hidden_act="gelu",
111
+ hidden_dropout_prob=0.1,
112
+ attention_probs_dropout_prob=0.1,
113
+ max_position_embeddings=512,
114
+ type_vocab_size=2,
115
+ task_type_vocab_size=3,
116
+ use_task_id=False,
117
+ initializer_range=0.02,
118
+ layer_norm_eps=1e-12,
119
+ pad_token_id=0,
120
+ position_embedding_type="absolute",
121
+ use_cache=True,
122
+ classifier_dropout=None,
123
+ **kwargs,
124
+ ):
125
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
126
+
127
+ self.vocab_size = vocab_size
128
+ self.hidden_size = hidden_size
129
+ self.num_hidden_layers = num_hidden_layers
130
+ self.num_attention_heads = num_attention_heads
131
+ self.hidden_act = hidden_act
132
+ self.intermediate_size = intermediate_size
133
+ self.hidden_dropout_prob = hidden_dropout_prob
134
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
135
+ self.max_position_embeddings = max_position_embeddings
136
+ self.type_vocab_size = type_vocab_size
137
+ self.task_type_vocab_size = task_type_vocab_size
138
+ self.use_task_id = use_task_id
139
+ self.initializer_range = initializer_range
140
+ self.layer_norm_eps = layer_norm_eps
141
+ self.position_embedding_type = position_embedding_type
142
+ self.use_cache = use_cache
143
+ self.classifier_dropout = classifier_dropout
144
+
145
+
146
+ class ErnieOnnxConfig(OnnxConfig):
147
+ @property
148
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
149
+ if self.task == "multiple-choice":
150
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
151
+ else:
152
+ dynamic_axis = {0: "batch", 1: "sequence"}
153
+ return OrderedDict(
154
+ [
155
+ ("input_ids", dynamic_axis),
156
+ ("attention_mask", dynamic_axis),
157
+ ("token_type_ids", dynamic_axis),
158
+ ("task_type_ids", dynamic_axis),
159
+ ]
160
+ )
161
+
162
+
163
+ __all__ = ["ErnieConfig", "ErnieOnnxConfig"]
janus/lib/python3.10/site-packages/transformers/models/ernie/modeling_ernie.py ADDED
@@ -0,0 +1,1815 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """PyTorch ERNIE model."""
16
+
17
+ import math
18
+ import warnings
19
+ from dataclasses import dataclass
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+
27
+ from ...activations import ACT2FN
28
+ from ...generation import GenerationMixin
29
+ from ...modeling_outputs import (
30
+ BaseModelOutputWithPastAndCrossAttentions,
31
+ BaseModelOutputWithPoolingAndCrossAttentions,
32
+ CausalLMOutputWithCrossAttentions,
33
+ MaskedLMOutput,
34
+ MultipleChoiceModelOutput,
35
+ NextSentencePredictorOutput,
36
+ QuestionAnsweringModelOutput,
37
+ SequenceClassifierOutput,
38
+ TokenClassifierOutput,
39
+ )
40
+ from ...modeling_utils import PreTrainedModel
41
+ from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
42
+ from ...utils import (
43
+ ModelOutput,
44
+ add_code_sample_docstrings,
45
+ add_start_docstrings,
46
+ add_start_docstrings_to_model_forward,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from .configuration_ernie import ErnieConfig
51
+
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CHECKPOINT_FOR_DOC = "nghuyong/ernie-1.0-base-zh"
56
+ _CONFIG_FOR_DOC = "ErnieConfig"
57
+
58
+
59
+ class ErnieEmbeddings(nn.Module):
60
+ """Construct the embeddings from word, position and token_type embeddings."""
61
+
62
+ def __init__(self, config):
63
+ super().__init__()
64
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
65
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
66
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
67
+ self.use_task_id = config.use_task_id
68
+ if config.use_task_id:
69
+ self.task_type_embeddings = nn.Embedding(config.task_type_vocab_size, config.hidden_size)
70
+
71
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
72
+ # any TensorFlow checkpoint file
73
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
74
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
75
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
76
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
77
+ self.register_buffer(
78
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
79
+ )
80
+ self.register_buffer(
81
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
82
+ )
83
+
84
+ def forward(
85
+ self,
86
+ input_ids: Optional[torch.LongTensor] = None,
87
+ token_type_ids: Optional[torch.LongTensor] = None,
88
+ task_type_ids: Optional[torch.LongTensor] = None,
89
+ position_ids: Optional[torch.LongTensor] = None,
90
+ inputs_embeds: Optional[torch.FloatTensor] = None,
91
+ past_key_values_length: int = 0,
92
+ ) -> torch.Tensor:
93
+ if input_ids is not None:
94
+ input_shape = input_ids.size()
95
+ else:
96
+ input_shape = inputs_embeds.size()[:-1]
97
+
98
+ seq_length = input_shape[1]
99
+
100
+ if position_ids is None:
101
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
102
+
103
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
104
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
105
+ # issue #5664
106
+ if token_type_ids is None:
107
+ if hasattr(self, "token_type_ids"):
108
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
109
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
110
+ token_type_ids = buffered_token_type_ids_expanded
111
+ else:
112
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
113
+
114
+ if inputs_embeds is None:
115
+ inputs_embeds = self.word_embeddings(input_ids)
116
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
117
+
118
+ embeddings = inputs_embeds + token_type_embeddings
119
+ if self.position_embedding_type == "absolute":
120
+ position_embeddings = self.position_embeddings(position_ids)
121
+ embeddings += position_embeddings
122
+
123
+ # add `task_type_id` for ERNIE model
124
+ if self.use_task_id:
125
+ if task_type_ids is None:
126
+ task_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
127
+ task_type_embeddings = self.task_type_embeddings(task_type_ids)
128
+ embeddings += task_type_embeddings
129
+
130
+ embeddings = self.LayerNorm(embeddings)
131
+ embeddings = self.dropout(embeddings)
132
+ return embeddings
133
+
134
+
135
+ # Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->Ernie
136
+ class ErnieSelfAttention(nn.Module):
137
+ def __init__(self, config, position_embedding_type=None):
138
+ super().__init__()
139
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
140
+ raise ValueError(
141
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
142
+ f"heads ({config.num_attention_heads})"
143
+ )
144
+
145
+ self.num_attention_heads = config.num_attention_heads
146
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
147
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
148
+
149
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
150
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
151
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
152
+
153
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
154
+ self.position_embedding_type = position_embedding_type or getattr(
155
+ config, "position_embedding_type", "absolute"
156
+ )
157
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
158
+ self.max_position_embeddings = config.max_position_embeddings
159
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
160
+
161
+ self.is_decoder = config.is_decoder
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,
170
+ hidden_states: torch.Tensor,
171
+ attention_mask: Optional[torch.FloatTensor] = None,
172
+ head_mask: Optional[torch.FloatTensor] = None,
173
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
174
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
175
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
176
+ output_attentions: Optional[bool] = False,
177
+ ) -> Tuple[torch.Tensor]:
178
+ mixed_query_layer = self.query(hidden_states)
179
+
180
+ # If this is instantiated as a cross-attention module, the keys
181
+ # and values come from an encoder; the attention mask needs to be
182
+ # such that the encoder's padding tokens are not attended to.
183
+ is_cross_attention = encoder_hidden_states is not None
184
+
185
+ if is_cross_attention and past_key_value is not None:
186
+ # reuse k,v, cross_attentions
187
+ key_layer = past_key_value[0]
188
+ value_layer = past_key_value[1]
189
+ attention_mask = encoder_attention_mask
190
+ elif is_cross_attention:
191
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
192
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
193
+ attention_mask = encoder_attention_mask
194
+ elif past_key_value is not None:
195
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
196
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
197
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
198
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
199
+ else:
200
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
201
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
202
+
203
+ query_layer = self.transpose_for_scores(mixed_query_layer)
204
+
205
+ use_cache = past_key_value is not None
206
+ if self.is_decoder:
207
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
208
+ # Further calls to cross_attention layer can then reuse all cross-attention
209
+ # key/value_states (first "if" case)
210
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
211
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
212
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
213
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
214
+ past_key_value = (key_layer, value_layer)
215
+
216
+ # Take the dot product between "query" and "key" to get the raw attention scores.
217
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
218
+
219
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
220
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
221
+ if use_cache:
222
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
223
+ -1, 1
224
+ )
225
+ else:
226
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
227
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
228
+ distance = position_ids_l - position_ids_r
229
+
230
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
231
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
232
+
233
+ if self.position_embedding_type == "relative_key":
234
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
235
+ attention_scores = attention_scores + relative_position_scores
236
+ elif self.position_embedding_type == "relative_key_query":
237
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
238
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
239
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
240
+
241
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
242
+ if attention_mask is not None:
243
+ # Apply the attention mask is (precomputed for all layers in ErnieModel forward() function)
244
+ attention_scores = attention_scores + attention_mask
245
+
246
+ # Normalize the attention scores to probabilities.
247
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
248
+
249
+ # This is actually dropping out entire tokens to attend to, which might
250
+ # seem a bit unusual, but is taken from the original Transformer paper.
251
+ attention_probs = self.dropout(attention_probs)
252
+
253
+ # Mask heads if we want to
254
+ if head_mask is not None:
255
+ attention_probs = attention_probs * head_mask
256
+
257
+ context_layer = torch.matmul(attention_probs, value_layer)
258
+
259
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
260
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
261
+ context_layer = context_layer.view(new_context_layer_shape)
262
+
263
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
264
+
265
+ if self.is_decoder:
266
+ outputs = outputs + (past_key_value,)
267
+ return outputs
268
+
269
+
270
+ # Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->Ernie
271
+ class ErnieSelfOutput(nn.Module):
272
+ def __init__(self, config):
273
+ super().__init__()
274
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
275
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
276
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
277
+
278
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
279
+ hidden_states = self.dense(hidden_states)
280
+ hidden_states = self.dropout(hidden_states)
281
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
282
+ return hidden_states
283
+
284
+
285
+ ERNIE_SELF_ATTENTION_CLASSES = {
286
+ "eager": ErnieSelfAttention,
287
+ }
288
+
289
+
290
+ # Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->Ernie,BERT->ERNIE
291
+ class ErnieAttention(nn.Module):
292
+ def __init__(self, config, position_embedding_type=None):
293
+ super().__init__()
294
+ self.self = ERNIE_SELF_ATTENTION_CLASSES[config._attn_implementation](
295
+ config, position_embedding_type=position_embedding_type
296
+ )
297
+ self.output = ErnieSelfOutput(config)
298
+ self.pruned_heads = set()
299
+
300
+ def prune_heads(self, heads):
301
+ if len(heads) == 0:
302
+ return
303
+ heads, index = find_pruneable_heads_and_indices(
304
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
305
+ )
306
+
307
+ # Prune linear layers
308
+ self.self.query = prune_linear_layer(self.self.query, index)
309
+ self.self.key = prune_linear_layer(self.self.key, index)
310
+ self.self.value = prune_linear_layer(self.self.value, index)
311
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
312
+
313
+ # Update hyper params and store pruned heads
314
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
315
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
316
+ self.pruned_heads = self.pruned_heads.union(heads)
317
+
318
+ def forward(
319
+ self,
320
+ hidden_states: torch.Tensor,
321
+ attention_mask: Optional[torch.FloatTensor] = None,
322
+ head_mask: Optional[torch.FloatTensor] = None,
323
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
324
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
325
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
326
+ output_attentions: Optional[bool] = False,
327
+ ) -> Tuple[torch.Tensor]:
328
+ self_outputs = self.self(
329
+ hidden_states,
330
+ attention_mask,
331
+ head_mask,
332
+ encoder_hidden_states,
333
+ encoder_attention_mask,
334
+ past_key_value,
335
+ output_attentions,
336
+ )
337
+ attention_output = self.output(self_outputs[0], hidden_states)
338
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
339
+ return outputs
340
+
341
+
342
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Ernie
343
+ class ErnieIntermediate(nn.Module):
344
+ def __init__(self, config):
345
+ super().__init__()
346
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
347
+ if isinstance(config.hidden_act, str):
348
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
349
+ else:
350
+ self.intermediate_act_fn = config.hidden_act
351
+
352
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
353
+ hidden_states = self.dense(hidden_states)
354
+ hidden_states = self.intermediate_act_fn(hidden_states)
355
+ return hidden_states
356
+
357
+
358
+ # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->Ernie
359
+ class ErnieOutput(nn.Module):
360
+ def __init__(self, config):
361
+ super().__init__()
362
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
363
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
364
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
365
+
366
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
367
+ hidden_states = self.dense(hidden_states)
368
+ hidden_states = self.dropout(hidden_states)
369
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
370
+ return hidden_states
371
+
372
+
373
+ # Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->Ernie
374
+ class ErnieLayer(nn.Module):
375
+ def __init__(self, config):
376
+ super().__init__()
377
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
378
+ self.seq_len_dim = 1
379
+ self.attention = ErnieAttention(config)
380
+ self.is_decoder = config.is_decoder
381
+ self.add_cross_attention = config.add_cross_attention
382
+ if self.add_cross_attention:
383
+ if not self.is_decoder:
384
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
385
+ self.crossattention = ErnieAttention(config, position_embedding_type="absolute")
386
+ self.intermediate = ErnieIntermediate(config)
387
+ self.output = ErnieOutput(config)
388
+
389
+ def forward(
390
+ self,
391
+ hidden_states: torch.Tensor,
392
+ attention_mask: Optional[torch.FloatTensor] = None,
393
+ head_mask: Optional[torch.FloatTensor] = None,
394
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
395
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
396
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
397
+ output_attentions: Optional[bool] = False,
398
+ ) -> Tuple[torch.Tensor]:
399
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
400
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
401
+ self_attention_outputs = self.attention(
402
+ hidden_states,
403
+ attention_mask,
404
+ head_mask,
405
+ output_attentions=output_attentions,
406
+ past_key_value=self_attn_past_key_value,
407
+ )
408
+ attention_output = self_attention_outputs[0]
409
+
410
+ # if decoder, the last output is tuple of self-attn cache
411
+ if self.is_decoder:
412
+ outputs = self_attention_outputs[1:-1]
413
+ present_key_value = self_attention_outputs[-1]
414
+ else:
415
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
416
+
417
+ cross_attn_present_key_value = None
418
+ if self.is_decoder and encoder_hidden_states is not None:
419
+ if not hasattr(self, "crossattention"):
420
+ raise ValueError(
421
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
422
+ " by setting `config.add_cross_attention=True`"
423
+ )
424
+
425
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
426
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
427
+ cross_attention_outputs = self.crossattention(
428
+ attention_output,
429
+ attention_mask,
430
+ head_mask,
431
+ encoder_hidden_states,
432
+ encoder_attention_mask,
433
+ cross_attn_past_key_value,
434
+ output_attentions,
435
+ )
436
+ attention_output = cross_attention_outputs[0]
437
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
438
+
439
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
440
+ cross_attn_present_key_value = cross_attention_outputs[-1]
441
+ present_key_value = present_key_value + cross_attn_present_key_value
442
+
443
+ layer_output = apply_chunking_to_forward(
444
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
445
+ )
446
+ outputs = (layer_output,) + outputs
447
+
448
+ # if decoder, return the attn key/values as the last output
449
+ if self.is_decoder:
450
+ outputs = outputs + (present_key_value,)
451
+
452
+ return outputs
453
+
454
+ def feed_forward_chunk(self, attention_output):
455
+ intermediate_output = self.intermediate(attention_output)
456
+ layer_output = self.output(intermediate_output, attention_output)
457
+ return layer_output
458
+
459
+
460
+ # Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->Ernie
461
+ class ErnieEncoder(nn.Module):
462
+ def __init__(self, config):
463
+ super().__init__()
464
+ self.config = config
465
+ self.layer = nn.ModuleList([ErnieLayer(config) for _ in range(config.num_hidden_layers)])
466
+ self.gradient_checkpointing = False
467
+
468
+ def forward(
469
+ self,
470
+ hidden_states: torch.Tensor,
471
+ attention_mask: Optional[torch.FloatTensor] = None,
472
+ head_mask: Optional[torch.FloatTensor] = None,
473
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
474
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
475
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
476
+ use_cache: Optional[bool] = None,
477
+ output_attentions: Optional[bool] = False,
478
+ output_hidden_states: Optional[bool] = False,
479
+ return_dict: Optional[bool] = True,
480
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
481
+ all_hidden_states = () if output_hidden_states else None
482
+ all_self_attentions = () if output_attentions else None
483
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
484
+
485
+ if self.gradient_checkpointing and self.training:
486
+ if use_cache:
487
+ logger.warning_once(
488
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
489
+ )
490
+ use_cache = False
491
+
492
+ next_decoder_cache = () if use_cache else None
493
+ for i, layer_module in enumerate(self.layer):
494
+ if output_hidden_states:
495
+ all_hidden_states = all_hidden_states + (hidden_states,)
496
+
497
+ layer_head_mask = head_mask[i] if head_mask is not None else None
498
+ past_key_value = past_key_values[i] if past_key_values is not None else None
499
+
500
+ if self.gradient_checkpointing and self.training:
501
+ layer_outputs = self._gradient_checkpointing_func(
502
+ layer_module.__call__,
503
+ hidden_states,
504
+ attention_mask,
505
+ layer_head_mask,
506
+ encoder_hidden_states,
507
+ encoder_attention_mask,
508
+ past_key_value,
509
+ output_attentions,
510
+ )
511
+ else:
512
+ layer_outputs = layer_module(
513
+ hidden_states,
514
+ attention_mask,
515
+ layer_head_mask,
516
+ encoder_hidden_states,
517
+ encoder_attention_mask,
518
+ past_key_value,
519
+ output_attentions,
520
+ )
521
+
522
+ hidden_states = layer_outputs[0]
523
+ if use_cache:
524
+ next_decoder_cache += (layer_outputs[-1],)
525
+ if output_attentions:
526
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
527
+ if self.config.add_cross_attention:
528
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
529
+
530
+ if output_hidden_states:
531
+ all_hidden_states = all_hidden_states + (hidden_states,)
532
+
533
+ if not return_dict:
534
+ return tuple(
535
+ v
536
+ for v in [
537
+ hidden_states,
538
+ next_decoder_cache,
539
+ all_hidden_states,
540
+ all_self_attentions,
541
+ all_cross_attentions,
542
+ ]
543
+ if v is not None
544
+ )
545
+ return BaseModelOutputWithPastAndCrossAttentions(
546
+ last_hidden_state=hidden_states,
547
+ past_key_values=next_decoder_cache,
548
+ hidden_states=all_hidden_states,
549
+ attentions=all_self_attentions,
550
+ cross_attentions=all_cross_attentions,
551
+ )
552
+
553
+
554
+ # Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->Ernie
555
+ class ErniePooler(nn.Module):
556
+ def __init__(self, config):
557
+ super().__init__()
558
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
559
+ self.activation = nn.Tanh()
560
+
561
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
562
+ # We "pool" the model by simply taking the hidden state corresponding
563
+ # to the first token.
564
+ first_token_tensor = hidden_states[:, 0]
565
+ pooled_output = self.dense(first_token_tensor)
566
+ pooled_output = self.activation(pooled_output)
567
+ return pooled_output
568
+
569
+
570
+ # Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->Ernie
571
+ class ErniePredictionHeadTransform(nn.Module):
572
+ def __init__(self, config):
573
+ super().__init__()
574
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
575
+ if isinstance(config.hidden_act, str):
576
+ self.transform_act_fn = ACT2FN[config.hidden_act]
577
+ else:
578
+ self.transform_act_fn = config.hidden_act
579
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
580
+
581
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
582
+ hidden_states = self.dense(hidden_states)
583
+ hidden_states = self.transform_act_fn(hidden_states)
584
+ hidden_states = self.LayerNorm(hidden_states)
585
+ return hidden_states
586
+
587
+
588
+ # Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->Ernie
589
+ class ErnieLMPredictionHead(nn.Module):
590
+ def __init__(self, config):
591
+ super().__init__()
592
+ self.transform = ErniePredictionHeadTransform(config)
593
+
594
+ # The output weights are the same as the input embeddings, but there is
595
+ # an output-only bias for each token.
596
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
597
+
598
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
599
+
600
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
601
+ self.decoder.bias = self.bias
602
+
603
+ def _tie_weights(self):
604
+ self.decoder.bias = self.bias
605
+
606
+ def forward(self, hidden_states):
607
+ hidden_states = self.transform(hidden_states)
608
+ hidden_states = self.decoder(hidden_states)
609
+ return hidden_states
610
+
611
+
612
+ # Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->Ernie
613
+ class ErnieOnlyMLMHead(nn.Module):
614
+ def __init__(self, config):
615
+ super().__init__()
616
+ self.predictions = ErnieLMPredictionHead(config)
617
+
618
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
619
+ prediction_scores = self.predictions(sequence_output)
620
+ return prediction_scores
621
+
622
+
623
+ # Copied from transformers.models.bert.modeling_bert.BertOnlyNSPHead with Bert->Ernie
624
+ class ErnieOnlyNSPHead(nn.Module):
625
+ def __init__(self, config):
626
+ super().__init__()
627
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
628
+
629
+ def forward(self, pooled_output):
630
+ seq_relationship_score = self.seq_relationship(pooled_output)
631
+ return seq_relationship_score
632
+
633
+
634
+ # Copied from transformers.models.bert.modeling_bert.BertPreTrainingHeads with Bert->Ernie
635
+ class ErniePreTrainingHeads(nn.Module):
636
+ def __init__(self, config):
637
+ super().__init__()
638
+ self.predictions = ErnieLMPredictionHead(config)
639
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
640
+
641
+ def forward(self, sequence_output, pooled_output):
642
+ prediction_scores = self.predictions(sequence_output)
643
+ seq_relationship_score = self.seq_relationship(pooled_output)
644
+ return prediction_scores, seq_relationship_score
645
+
646
+
647
+ class ErniePreTrainedModel(PreTrainedModel):
648
+ """
649
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
650
+ models.
651
+ """
652
+
653
+ config_class = ErnieConfig
654
+ base_model_prefix = "ernie"
655
+ supports_gradient_checkpointing = True
656
+
657
+ def _init_weights(self, module):
658
+ """Initialize the weights"""
659
+ if isinstance(module, nn.Linear):
660
+ # Slightly different from the TF version which uses truncated_normal for initialization
661
+ # cf https://github.com/pytorch/pytorch/pull/5617
662
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
663
+ if module.bias is not None:
664
+ module.bias.data.zero_()
665
+ elif isinstance(module, nn.Embedding):
666
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
667
+ if module.padding_idx is not None:
668
+ module.weight.data[module.padding_idx].zero_()
669
+ elif isinstance(module, nn.LayerNorm):
670
+ module.bias.data.zero_()
671
+ module.weight.data.fill_(1.0)
672
+
673
+
674
+ @dataclass
675
+ # Copied from transformers.models.bert.modeling_bert.BertForPreTrainingOutput with Bert->Ernie
676
+ class ErnieForPreTrainingOutput(ModelOutput):
677
+ """
678
+ Output type of [`ErnieForPreTraining`].
679
+
680
+ Args:
681
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
682
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
683
+ (classification) loss.
684
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
685
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
686
+ seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
687
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
688
+ before SoftMax).
689
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
690
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
691
+ shape `(batch_size, sequence_length, hidden_size)`.
692
+
693
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
694
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
695
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
696
+ sequence_length)`.
697
+
698
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
699
+ heads.
700
+ """
701
+
702
+ loss: Optional[torch.FloatTensor] = None
703
+ prediction_logits: torch.FloatTensor = None
704
+ seq_relationship_logits: torch.FloatTensor = None
705
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
706
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
707
+
708
+
709
+ ERNIE_START_DOCSTRING = r"""
710
+
711
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
712
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
713
+ etc.)
714
+
715
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
716
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
717
+ and behavior.
718
+
719
+ Parameters:
720
+ config ([`ErnieConfig`]): Model configuration class with all the parameters of the model.
721
+ Initializing with a config file does not load the weights associated with the model, only the
722
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
723
+ """
724
+
725
+ ERNIE_INPUTS_DOCSTRING = r"""
726
+ Args:
727
+ input_ids (`torch.LongTensor` of shape `({0})`):
728
+ Indices of input sequence tokens in the vocabulary.
729
+
730
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
731
+ [`PreTrainedTokenizer.__call__`] for details.
732
+
733
+ [What are input IDs?](../glossary#input-ids)
734
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
735
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
736
+
737
+ - 1 for tokens that are **not masked**,
738
+ - 0 for tokens that are **masked**.
739
+
740
+ [What are attention masks?](../glossary#attention-mask)
741
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
742
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
743
+ 1]`:
744
+
745
+ - 0 corresponds to a *sentence A* token,
746
+ - 1 corresponds to a *sentence B* token.
747
+
748
+ [What are token type IDs?](../glossary#token-type-ids)
749
+ task_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
750
+ Task type embedding is a special embedding to represent the characteristic of different tasks, such as
751
+ word-aware pre-training task, structure-aware pre-training task and semantic-aware pre-training task. We
752
+ assign a `task_type_id` to each task and the `task_type_id` is in the range `[0,
753
+ config.task_type_vocab_size-1]
754
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
755
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
756
+ config.max_position_embeddings - 1]`.
757
+
758
+ [What are position IDs?](../glossary#position-ids)
759
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
760
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
761
+
762
+ - 1 indicates the head is **not masked**,
763
+ - 0 indicates the head is **masked**.
764
+
765
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
766
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
767
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
768
+ model's internal embedding lookup matrix.
769
+ output_attentions (`bool`, *optional*):
770
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
771
+ tensors for more detail.
772
+ output_hidden_states (`bool`, *optional*):
773
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
774
+ more detail.
775
+ return_dict (`bool`, *optional*):
776
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
777
+ """
778
+
779
+
780
+ @add_start_docstrings(
781
+ "The bare Ernie Model transformer outputting raw hidden-states without any specific head on top.",
782
+ ERNIE_START_DOCSTRING,
783
+ )
784
+ class ErnieModel(ErniePreTrainedModel):
785
+ """
786
+
787
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
788
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
789
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
790
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
791
+
792
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
793
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
794
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
795
+ """
796
+
797
+ # Copied from transformers.models.clap.modeling_clap.ClapTextModel.__init__ with ClapText->Ernie
798
+ def __init__(self, config, add_pooling_layer=True):
799
+ super().__init__(config)
800
+ self.config = config
801
+
802
+ self.embeddings = ErnieEmbeddings(config)
803
+ self.encoder = ErnieEncoder(config)
804
+
805
+ self.pooler = ErniePooler(config) if add_pooling_layer else None
806
+
807
+ # Initialize weights and apply final processing
808
+ self.post_init()
809
+
810
+ # Copied from transformers.models.bert.modeling_bert.BertModel.get_input_embeddings
811
+ def get_input_embeddings(self):
812
+ return self.embeddings.word_embeddings
813
+
814
+ # Copied from transformers.models.bert.modeling_bert.BertModel.set_input_embeddings
815
+ def set_input_embeddings(self, value):
816
+ self.embeddings.word_embeddings = value
817
+
818
+ # Copied from transformers.models.bert.modeling_bert.BertModel._prune_heads
819
+ def _prune_heads(self, heads_to_prune):
820
+ """
821
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
822
+ class PreTrainedModel
823
+ """
824
+ for layer, heads in heads_to_prune.items():
825
+ self.encoder.layer[layer].attention.prune_heads(heads)
826
+
827
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
828
+ @add_code_sample_docstrings(
829
+ checkpoint=_CHECKPOINT_FOR_DOC,
830
+ output_type=BaseModelOutputWithPoolingAndCrossAttentions,
831
+ config_class=_CONFIG_FOR_DOC,
832
+ )
833
+ def forward(
834
+ self,
835
+ input_ids: Optional[torch.Tensor] = None,
836
+ attention_mask: Optional[torch.Tensor] = None,
837
+ token_type_ids: Optional[torch.Tensor] = None,
838
+ task_type_ids: Optional[torch.Tensor] = None,
839
+ position_ids: Optional[torch.Tensor] = None,
840
+ head_mask: Optional[torch.Tensor] = None,
841
+ inputs_embeds: Optional[torch.Tensor] = None,
842
+ encoder_hidden_states: Optional[torch.Tensor] = None,
843
+ encoder_attention_mask: Optional[torch.Tensor] = None,
844
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
845
+ use_cache: Optional[bool] = None,
846
+ output_attentions: Optional[bool] = None,
847
+ output_hidden_states: Optional[bool] = None,
848
+ return_dict: Optional[bool] = None,
849
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
850
+ r"""
851
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
852
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
853
+ the model is configured as a decoder.
854
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
855
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
856
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
857
+
858
+ - 1 for tokens that are **not masked**,
859
+ - 0 for tokens that are **masked**.
860
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
861
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
862
+
863
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
864
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
865
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
866
+ use_cache (`bool`, *optional*):
867
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
868
+ `past_key_values`).
869
+ """
870
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
871
+ output_hidden_states = (
872
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
873
+ )
874
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
875
+
876
+ if self.config.is_decoder:
877
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
878
+ else:
879
+ use_cache = False
880
+
881
+ if input_ids is not None and inputs_embeds is not None:
882
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
883
+ elif input_ids is not None:
884
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
885
+ input_shape = input_ids.size()
886
+ elif inputs_embeds is not None:
887
+ input_shape = inputs_embeds.size()[:-1]
888
+ else:
889
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
890
+
891
+ batch_size, seq_length = input_shape
892
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
893
+
894
+ # past_key_values_length
895
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
896
+
897
+ if attention_mask is None:
898
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
899
+
900
+ if token_type_ids is None:
901
+ if hasattr(self.embeddings, "token_type_ids"):
902
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
903
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
904
+ token_type_ids = buffered_token_type_ids_expanded
905
+ else:
906
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
907
+
908
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
909
+ # ourselves in which case we just need to make it broadcastable to all heads.
910
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
911
+
912
+ # If a 2D or 3D attention mask is provided for the cross-attention
913
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
914
+ if self.config.is_decoder and encoder_hidden_states is not None:
915
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
916
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
917
+ if encoder_attention_mask is None:
918
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
919
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
920
+ else:
921
+ encoder_extended_attention_mask = None
922
+
923
+ # Prepare head mask if needed
924
+ # 1.0 in head_mask indicate we keep the head
925
+ # attention_probs has shape bsz x n_heads x N x N
926
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
927
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
928
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
929
+
930
+ embedding_output = self.embeddings(
931
+ input_ids=input_ids,
932
+ position_ids=position_ids,
933
+ token_type_ids=token_type_ids,
934
+ task_type_ids=task_type_ids,
935
+ inputs_embeds=inputs_embeds,
936
+ past_key_values_length=past_key_values_length,
937
+ )
938
+ encoder_outputs = self.encoder(
939
+ embedding_output,
940
+ attention_mask=extended_attention_mask,
941
+ head_mask=head_mask,
942
+ encoder_hidden_states=encoder_hidden_states,
943
+ encoder_attention_mask=encoder_extended_attention_mask,
944
+ past_key_values=past_key_values,
945
+ use_cache=use_cache,
946
+ output_attentions=output_attentions,
947
+ output_hidden_states=output_hidden_states,
948
+ return_dict=return_dict,
949
+ )
950
+ sequence_output = encoder_outputs[0]
951
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
952
+
953
+ if not return_dict:
954
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
955
+
956
+ return BaseModelOutputWithPoolingAndCrossAttentions(
957
+ last_hidden_state=sequence_output,
958
+ pooler_output=pooled_output,
959
+ past_key_values=encoder_outputs.past_key_values,
960
+ hidden_states=encoder_outputs.hidden_states,
961
+ attentions=encoder_outputs.attentions,
962
+ cross_attentions=encoder_outputs.cross_attentions,
963
+ )
964
+
965
+
966
+ @add_start_docstrings(
967
+ """
968
+ Ernie Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
969
+ sentence prediction (classification)` head.
970
+ """,
971
+ ERNIE_START_DOCSTRING,
972
+ )
973
+ class ErnieForPreTraining(ErniePreTrainedModel):
974
+ _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
975
+
976
+ # Copied from transformers.models.bert.modeling_bert.BertForPreTraining.__init__ with Bert->Ernie,bert->ernie
977
+ def __init__(self, config):
978
+ super().__init__(config)
979
+
980
+ self.ernie = ErnieModel(config)
981
+ self.cls = ErniePreTrainingHeads(config)
982
+
983
+ # Initialize weights and apply final processing
984
+ self.post_init()
985
+
986
+ # Copied from transformers.models.bert.modeling_bert.BertForPreTraining.get_output_embeddings
987
+ def get_output_embeddings(self):
988
+ return self.cls.predictions.decoder
989
+
990
+ # Copied from transformers.models.bert.modeling_bert.BertForPreTraining.set_output_embeddings
991
+ def set_output_embeddings(self, new_embeddings):
992
+ self.cls.predictions.decoder = new_embeddings
993
+ self.cls.predictions.bias = new_embeddings.bias
994
+
995
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
996
+ @replace_return_docstrings(output_type=ErnieForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
997
+ def forward(
998
+ self,
999
+ input_ids: Optional[torch.Tensor] = None,
1000
+ attention_mask: Optional[torch.Tensor] = None,
1001
+ token_type_ids: Optional[torch.Tensor] = None,
1002
+ task_type_ids: Optional[torch.Tensor] = None,
1003
+ position_ids: Optional[torch.Tensor] = None,
1004
+ head_mask: Optional[torch.Tensor] = None,
1005
+ inputs_embeds: Optional[torch.Tensor] = None,
1006
+ labels: Optional[torch.Tensor] = None,
1007
+ next_sentence_label: Optional[torch.Tensor] = None,
1008
+ output_attentions: Optional[bool] = None,
1009
+ output_hidden_states: Optional[bool] = None,
1010
+ return_dict: Optional[bool] = None,
1011
+ ) -> Union[Tuple[torch.Tensor], ErnieForPreTrainingOutput]:
1012
+ r"""
1013
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1014
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1015
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
1016
+ the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1017
+ next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1018
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
1019
+ pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
1020
+
1021
+ - 0 indicates sequence B is a continuation of sequence A,
1022
+ - 1 indicates sequence B is a random sequence.
1023
+ kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
1024
+ Used to hide legacy arguments that have been deprecated.
1025
+
1026
+ Returns:
1027
+
1028
+ Example:
1029
+
1030
+ ```python
1031
+ >>> from transformers import AutoTokenizer, ErnieForPreTraining
1032
+ >>> import torch
1033
+
1034
+ >>> tokenizer = AutoTokenizer.from_pretrained("nghuyong/ernie-1.0-base-zh")
1035
+ >>> model = ErnieForPreTraining.from_pretrained("nghuyong/ernie-1.0-base-zh")
1036
+
1037
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1038
+ >>> outputs = model(**inputs)
1039
+
1040
+ >>> prediction_logits = outputs.prediction_logits
1041
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
1042
+ ```
1043
+ """
1044
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1045
+
1046
+ outputs = self.ernie(
1047
+ input_ids,
1048
+ attention_mask=attention_mask,
1049
+ token_type_ids=token_type_ids,
1050
+ task_type_ids=task_type_ids,
1051
+ position_ids=position_ids,
1052
+ head_mask=head_mask,
1053
+ inputs_embeds=inputs_embeds,
1054
+ output_attentions=output_attentions,
1055
+ output_hidden_states=output_hidden_states,
1056
+ return_dict=return_dict,
1057
+ )
1058
+
1059
+ sequence_output, pooled_output = outputs[:2]
1060
+ prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
1061
+
1062
+ total_loss = None
1063
+ if labels is not None and next_sentence_label is not None:
1064
+ loss_fct = CrossEntropyLoss()
1065
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1066
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
1067
+ total_loss = masked_lm_loss + next_sentence_loss
1068
+
1069
+ if not return_dict:
1070
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
1071
+ return ((total_loss,) + output) if total_loss is not None else output
1072
+
1073
+ return ErnieForPreTrainingOutput(
1074
+ loss=total_loss,
1075
+ prediction_logits=prediction_scores,
1076
+ seq_relationship_logits=seq_relationship_score,
1077
+ hidden_states=outputs.hidden_states,
1078
+ attentions=outputs.attentions,
1079
+ )
1080
+
1081
+
1082
+ @add_start_docstrings(
1083
+ """Ernie Model with a `language modeling` head on top for CLM fine-tuning.""", ERNIE_START_DOCSTRING
1084
+ )
1085
+ class ErnieForCausalLM(ErniePreTrainedModel, GenerationMixin):
1086
+ _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
1087
+
1088
+ # Copied from transformers.models.bert.modeling_bert.BertLMHeadModel.__init__ with BertLMHeadModel->ErnieForCausalLM,Bert->Ernie,bert->ernie
1089
+ def __init__(self, config):
1090
+ super().__init__(config)
1091
+
1092
+ if not config.is_decoder:
1093
+ logger.warning("If you want to use `ErnieForCausalLM` as a standalone, add `is_decoder=True.`")
1094
+
1095
+ self.ernie = ErnieModel(config, add_pooling_layer=False)
1096
+ self.cls = ErnieOnlyMLMHead(config)
1097
+
1098
+ # Initialize weights and apply final processing
1099
+ self.post_init()
1100
+
1101
+ # Copied from transformers.models.bert.modeling_bert.BertLMHeadModel.get_output_embeddings
1102
+ def get_output_embeddings(self):
1103
+ return self.cls.predictions.decoder
1104
+
1105
+ # Copied from transformers.models.bert.modeling_bert.BertLMHeadModel.set_output_embeddings
1106
+ def set_output_embeddings(self, new_embeddings):
1107
+ self.cls.predictions.decoder = new_embeddings
1108
+ self.cls.predictions.bias = new_embeddings.bias
1109
+
1110
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1111
+ @add_code_sample_docstrings(
1112
+ checkpoint=_CHECKPOINT_FOR_DOC,
1113
+ output_type=CausalLMOutputWithCrossAttentions,
1114
+ config_class=_CONFIG_FOR_DOC,
1115
+ )
1116
+ def forward(
1117
+ self,
1118
+ input_ids: Optional[torch.Tensor] = None,
1119
+ attention_mask: Optional[torch.Tensor] = None,
1120
+ token_type_ids: Optional[torch.Tensor] = None,
1121
+ task_type_ids: Optional[torch.Tensor] = None,
1122
+ position_ids: Optional[torch.Tensor] = None,
1123
+ head_mask: Optional[torch.Tensor] = None,
1124
+ inputs_embeds: Optional[torch.Tensor] = None,
1125
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1126
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1127
+ labels: Optional[torch.Tensor] = None,
1128
+ past_key_values: Optional[List[torch.Tensor]] = None,
1129
+ use_cache: Optional[bool] = None,
1130
+ output_attentions: Optional[bool] = None,
1131
+ output_hidden_states: Optional[bool] = None,
1132
+ return_dict: Optional[bool] = None,
1133
+ ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
1134
+ r"""
1135
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1136
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1137
+ the model is configured as a decoder.
1138
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1139
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1140
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1141
+
1142
+ - 1 for tokens that are **not masked**,
1143
+ - 0 for tokens that are **masked**.
1144
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1145
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1146
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
1147
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
1148
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
1149
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1150
+
1151
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1152
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1153
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1154
+ use_cache (`bool`, *optional*):
1155
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1156
+ `past_key_values`).
1157
+ """
1158
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1159
+ if labels is not None:
1160
+ use_cache = False
1161
+
1162
+ outputs = self.ernie(
1163
+ input_ids,
1164
+ attention_mask=attention_mask,
1165
+ token_type_ids=token_type_ids,
1166
+ task_type_ids=task_type_ids,
1167
+ position_ids=position_ids,
1168
+ head_mask=head_mask,
1169
+ inputs_embeds=inputs_embeds,
1170
+ encoder_hidden_states=encoder_hidden_states,
1171
+ encoder_attention_mask=encoder_attention_mask,
1172
+ past_key_values=past_key_values,
1173
+ use_cache=use_cache,
1174
+ output_attentions=output_attentions,
1175
+ output_hidden_states=output_hidden_states,
1176
+ return_dict=return_dict,
1177
+ )
1178
+
1179
+ sequence_output = outputs[0]
1180
+ prediction_scores = self.cls(sequence_output)
1181
+
1182
+ lm_loss = None
1183
+ if labels is not None:
1184
+ # we are doing next-token prediction; shift prediction scores and input ids by one
1185
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
1186
+ labels = labels[:, 1:].contiguous()
1187
+ loss_fct = CrossEntropyLoss()
1188
+ lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1189
+
1190
+ if not return_dict:
1191
+ output = (prediction_scores,) + outputs[2:]
1192
+ return ((lm_loss,) + output) if lm_loss is not None else output
1193
+
1194
+ return CausalLMOutputWithCrossAttentions(
1195
+ loss=lm_loss,
1196
+ logits=prediction_scores,
1197
+ past_key_values=outputs.past_key_values,
1198
+ hidden_states=outputs.hidden_states,
1199
+ attentions=outputs.attentions,
1200
+ cross_attentions=outputs.cross_attentions,
1201
+ )
1202
+
1203
+ # Copied from transformers.models.bert.modeling_bert.BertLMHeadModel._reorder_cache
1204
+ def _reorder_cache(self, past_key_values, beam_idx):
1205
+ reordered_past = ()
1206
+ for layer_past in past_key_values:
1207
+ reordered_past += (
1208
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1209
+ )
1210
+ return reordered_past
1211
+
1212
+
1213
+ @add_start_docstrings("""Ernie Model with a `language modeling` head on top.""", ERNIE_START_DOCSTRING)
1214
+ class ErnieForMaskedLM(ErniePreTrainedModel):
1215
+ _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
1216
+
1217
+ # Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.__init__ with Bert->Ernie,bert->ernie
1218
+ def __init__(self, config):
1219
+ super().__init__(config)
1220
+
1221
+ if config.is_decoder:
1222
+ logger.warning(
1223
+ "If you want to use `ErnieForMaskedLM` make sure `config.is_decoder=False` for "
1224
+ "bi-directional self-attention."
1225
+ )
1226
+
1227
+ self.ernie = ErnieModel(config, add_pooling_layer=False)
1228
+ self.cls = ErnieOnlyMLMHead(config)
1229
+
1230
+ # Initialize weights and apply final processing
1231
+ self.post_init()
1232
+
1233
+ # Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.get_output_embeddings
1234
+ def get_output_embeddings(self):
1235
+ return self.cls.predictions.decoder
1236
+
1237
+ # Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.set_output_embeddings
1238
+ def set_output_embeddings(self, new_embeddings):
1239
+ self.cls.predictions.decoder = new_embeddings
1240
+ self.cls.predictions.bias = new_embeddings.bias
1241
+
1242
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1243
+ @add_code_sample_docstrings(
1244
+ checkpoint=_CHECKPOINT_FOR_DOC,
1245
+ output_type=MaskedLMOutput,
1246
+ config_class=_CONFIG_FOR_DOC,
1247
+ expected_output="'paris'",
1248
+ expected_loss=0.88,
1249
+ )
1250
+ def forward(
1251
+ self,
1252
+ input_ids: Optional[torch.Tensor] = None,
1253
+ attention_mask: Optional[torch.Tensor] = None,
1254
+ token_type_ids: Optional[torch.Tensor] = None,
1255
+ task_type_ids: Optional[torch.Tensor] = None,
1256
+ position_ids: Optional[torch.Tensor] = None,
1257
+ head_mask: Optional[torch.Tensor] = None,
1258
+ inputs_embeds: Optional[torch.Tensor] = None,
1259
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1260
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1261
+ labels: Optional[torch.Tensor] = None,
1262
+ output_attentions: Optional[bool] = None,
1263
+ output_hidden_states: Optional[bool] = None,
1264
+ return_dict: Optional[bool] = None,
1265
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
1266
+ r"""
1267
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1268
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1269
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1270
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1271
+ """
1272
+
1273
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1274
+
1275
+ outputs = self.ernie(
1276
+ input_ids,
1277
+ attention_mask=attention_mask,
1278
+ token_type_ids=token_type_ids,
1279
+ task_type_ids=task_type_ids,
1280
+ position_ids=position_ids,
1281
+ head_mask=head_mask,
1282
+ inputs_embeds=inputs_embeds,
1283
+ encoder_hidden_states=encoder_hidden_states,
1284
+ encoder_attention_mask=encoder_attention_mask,
1285
+ output_attentions=output_attentions,
1286
+ output_hidden_states=output_hidden_states,
1287
+ return_dict=return_dict,
1288
+ )
1289
+
1290
+ sequence_output = outputs[0]
1291
+ prediction_scores = self.cls(sequence_output)
1292
+
1293
+ masked_lm_loss = None
1294
+ if labels is not None:
1295
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1296
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1297
+
1298
+ if not return_dict:
1299
+ output = (prediction_scores,) + outputs[2:]
1300
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1301
+
1302
+ return MaskedLMOutput(
1303
+ loss=masked_lm_loss,
1304
+ logits=prediction_scores,
1305
+ hidden_states=outputs.hidden_states,
1306
+ attentions=outputs.attentions,
1307
+ )
1308
+
1309
+ # Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.prepare_inputs_for_generation
1310
+ def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
1311
+ input_shape = input_ids.shape
1312
+ effective_batch_size = input_shape[0]
1313
+
1314
+ # add a dummy token
1315
+ if self.config.pad_token_id is None:
1316
+ raise ValueError("The PAD token should be defined for generation")
1317
+
1318
+ attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
1319
+ dummy_token = torch.full(
1320
+ (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
1321
+ )
1322
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
1323
+
1324
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
1325
+
1326
+
1327
+ @add_start_docstrings(
1328
+ """Ernie Model with a `next sentence prediction (classification)` head on top.""",
1329
+ ERNIE_START_DOCSTRING,
1330
+ )
1331
+ class ErnieForNextSentencePrediction(ErniePreTrainedModel):
1332
+ # Copied from transformers.models.bert.modeling_bert.BertForNextSentencePrediction.__init__ with Bert->Ernie,bert->ernie
1333
+ def __init__(self, config):
1334
+ super().__init__(config)
1335
+
1336
+ self.ernie = ErnieModel(config)
1337
+ self.cls = ErnieOnlyNSPHead(config)
1338
+
1339
+ # Initialize weights and apply final processing
1340
+ self.post_init()
1341
+
1342
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1343
+ @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
1344
+ def forward(
1345
+ self,
1346
+ input_ids: Optional[torch.Tensor] = None,
1347
+ attention_mask: Optional[torch.Tensor] = None,
1348
+ token_type_ids: Optional[torch.Tensor] = None,
1349
+ task_type_ids: Optional[torch.Tensor] = None,
1350
+ position_ids: Optional[torch.Tensor] = None,
1351
+ head_mask: Optional[torch.Tensor] = None,
1352
+ inputs_embeds: Optional[torch.Tensor] = None,
1353
+ labels: Optional[torch.Tensor] = None,
1354
+ output_attentions: Optional[bool] = None,
1355
+ output_hidden_states: Optional[bool] = None,
1356
+ return_dict: Optional[bool] = None,
1357
+ **kwargs,
1358
+ ) -> Union[Tuple[torch.Tensor], NextSentencePredictorOutput]:
1359
+ r"""
1360
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1361
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
1362
+ (see `input_ids` docstring). Indices should be in `[0, 1]`:
1363
+
1364
+ - 0 indicates sequence B is a continuation of sequence A,
1365
+ - 1 indicates sequence B is a random sequence.
1366
+
1367
+ Returns:
1368
+
1369
+ Example:
1370
+
1371
+ ```python
1372
+ >>> from transformers import AutoTokenizer, ErnieForNextSentencePrediction
1373
+ >>> import torch
1374
+
1375
+ >>> tokenizer = AutoTokenizer.from_pretrained("nghuyong/ernie-1.0-base-zh")
1376
+ >>> model = ErnieForNextSentencePrediction.from_pretrained("nghuyong/ernie-1.0-base-zh")
1377
+
1378
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1379
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
1380
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
1381
+
1382
+ >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
1383
+ >>> logits = outputs.logits
1384
+ >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
1385
+ ```
1386
+ """
1387
+
1388
+ if "next_sentence_label" in kwargs:
1389
+ warnings.warn(
1390
+ "The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
1391
+ " `labels` instead.",
1392
+ FutureWarning,
1393
+ )
1394
+ labels = kwargs.pop("next_sentence_label")
1395
+
1396
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1397
+
1398
+ outputs = self.ernie(
1399
+ input_ids,
1400
+ attention_mask=attention_mask,
1401
+ token_type_ids=token_type_ids,
1402
+ task_type_ids=task_type_ids,
1403
+ position_ids=position_ids,
1404
+ head_mask=head_mask,
1405
+ inputs_embeds=inputs_embeds,
1406
+ output_attentions=output_attentions,
1407
+ output_hidden_states=output_hidden_states,
1408
+ return_dict=return_dict,
1409
+ )
1410
+
1411
+ pooled_output = outputs[1]
1412
+
1413
+ seq_relationship_scores = self.cls(pooled_output)
1414
+
1415
+ next_sentence_loss = None
1416
+ if labels is not None:
1417
+ loss_fct = CrossEntropyLoss()
1418
+ next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
1419
+
1420
+ if not return_dict:
1421
+ output = (seq_relationship_scores,) + outputs[2:]
1422
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
1423
+
1424
+ return NextSentencePredictorOutput(
1425
+ loss=next_sentence_loss,
1426
+ logits=seq_relationship_scores,
1427
+ hidden_states=outputs.hidden_states,
1428
+ attentions=outputs.attentions,
1429
+ )
1430
+
1431
+
1432
+ @add_start_docstrings(
1433
+ """
1434
+ Ernie Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
1435
+ output) e.g. for GLUE tasks.
1436
+ """,
1437
+ ERNIE_START_DOCSTRING,
1438
+ )
1439
+ class ErnieForSequenceClassification(ErniePreTrainedModel):
1440
+ # Copied from transformers.models.bert.modeling_bert.BertForSequenceClassification.__init__ with Bert->Ernie,bert->ernie
1441
+ def __init__(self, config):
1442
+ super().__init__(config)
1443
+ self.num_labels = config.num_labels
1444
+ self.config = config
1445
+
1446
+ self.ernie = ErnieModel(config)
1447
+ classifier_dropout = (
1448
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1449
+ )
1450
+ self.dropout = nn.Dropout(classifier_dropout)
1451
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1452
+
1453
+ # Initialize weights and apply final processing
1454
+ self.post_init()
1455
+
1456
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1457
+ def forward(
1458
+ self,
1459
+ input_ids: Optional[torch.Tensor] = None,
1460
+ attention_mask: Optional[torch.Tensor] = None,
1461
+ token_type_ids: Optional[torch.Tensor] = None,
1462
+ task_type_ids: Optional[torch.Tensor] = None,
1463
+ position_ids: Optional[torch.Tensor] = None,
1464
+ head_mask: Optional[torch.Tensor] = None,
1465
+ inputs_embeds: Optional[torch.Tensor] = None,
1466
+ labels: Optional[torch.Tensor] = None,
1467
+ output_attentions: Optional[bool] = None,
1468
+ output_hidden_states: Optional[bool] = None,
1469
+ return_dict: Optional[bool] = None,
1470
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
1471
+ r"""
1472
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1473
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1474
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1475
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1476
+ """
1477
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1478
+
1479
+ outputs = self.ernie(
1480
+ input_ids,
1481
+ attention_mask=attention_mask,
1482
+ token_type_ids=token_type_ids,
1483
+ task_type_ids=task_type_ids,
1484
+ position_ids=position_ids,
1485
+ head_mask=head_mask,
1486
+ inputs_embeds=inputs_embeds,
1487
+ output_attentions=output_attentions,
1488
+ output_hidden_states=output_hidden_states,
1489
+ return_dict=return_dict,
1490
+ )
1491
+
1492
+ pooled_output = outputs[1]
1493
+
1494
+ pooled_output = self.dropout(pooled_output)
1495
+ logits = self.classifier(pooled_output)
1496
+
1497
+ loss = None
1498
+ if labels is not None:
1499
+ if self.config.problem_type is None:
1500
+ if self.num_labels == 1:
1501
+ self.config.problem_type = "regression"
1502
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1503
+ self.config.problem_type = "single_label_classification"
1504
+ else:
1505
+ self.config.problem_type = "multi_label_classification"
1506
+
1507
+ if self.config.problem_type == "regression":
1508
+ loss_fct = MSELoss()
1509
+ if self.num_labels == 1:
1510
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1511
+ else:
1512
+ loss = loss_fct(logits, labels)
1513
+ elif self.config.problem_type == "single_label_classification":
1514
+ loss_fct = CrossEntropyLoss()
1515
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1516
+ elif self.config.problem_type == "multi_label_classification":
1517
+ loss_fct = BCEWithLogitsLoss()
1518
+ loss = loss_fct(logits, labels)
1519
+ if not return_dict:
1520
+ output = (logits,) + outputs[2:]
1521
+ return ((loss,) + output) if loss is not None else output
1522
+
1523
+ return SequenceClassifierOutput(
1524
+ loss=loss,
1525
+ logits=logits,
1526
+ hidden_states=outputs.hidden_states,
1527
+ attentions=outputs.attentions,
1528
+ )
1529
+
1530
+
1531
+ @add_start_docstrings(
1532
+ """
1533
+ Ernie Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1534
+ softmax) e.g. for RocStories/SWAG tasks.
1535
+ """,
1536
+ ERNIE_START_DOCSTRING,
1537
+ )
1538
+ class ErnieForMultipleChoice(ErniePreTrainedModel):
1539
+ # Copied from transformers.models.bert.modeling_bert.BertForMultipleChoice.__init__ with Bert->Ernie,bert->ernie
1540
+ def __init__(self, config):
1541
+ super().__init__(config)
1542
+
1543
+ self.ernie = ErnieModel(config)
1544
+ classifier_dropout = (
1545
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1546
+ )
1547
+ self.dropout = nn.Dropout(classifier_dropout)
1548
+ self.classifier = nn.Linear(config.hidden_size, 1)
1549
+
1550
+ # Initialize weights and apply final processing
1551
+ self.post_init()
1552
+
1553
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
1554
+ @add_code_sample_docstrings(
1555
+ checkpoint=_CHECKPOINT_FOR_DOC,
1556
+ output_type=MultipleChoiceModelOutput,
1557
+ config_class=_CONFIG_FOR_DOC,
1558
+ )
1559
+ def forward(
1560
+ self,
1561
+ input_ids: Optional[torch.Tensor] = None,
1562
+ attention_mask: Optional[torch.Tensor] = None,
1563
+ token_type_ids: Optional[torch.Tensor] = None,
1564
+ task_type_ids: Optional[torch.Tensor] = None,
1565
+ position_ids: Optional[torch.Tensor] = None,
1566
+ head_mask: Optional[torch.Tensor] = None,
1567
+ inputs_embeds: Optional[torch.Tensor] = None,
1568
+ labels: Optional[torch.Tensor] = None,
1569
+ output_attentions: Optional[bool] = None,
1570
+ output_hidden_states: Optional[bool] = None,
1571
+ return_dict: Optional[bool] = None,
1572
+ ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
1573
+ r"""
1574
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1575
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1576
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1577
+ `input_ids` above)
1578
+ """
1579
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1580
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1581
+
1582
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1583
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1584
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1585
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
1586
+ inputs_embeds = (
1587
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1588
+ if inputs_embeds is not None
1589
+ else None
1590
+ )
1591
+
1592
+ outputs = self.ernie(
1593
+ input_ids,
1594
+ attention_mask=attention_mask,
1595
+ token_type_ids=token_type_ids,
1596
+ task_type_ids=task_type_ids,
1597
+ position_ids=position_ids,
1598
+ head_mask=head_mask,
1599
+ inputs_embeds=inputs_embeds,
1600
+ output_attentions=output_attentions,
1601
+ output_hidden_states=output_hidden_states,
1602
+ return_dict=return_dict,
1603
+ )
1604
+
1605
+ pooled_output = outputs[1]
1606
+
1607
+ pooled_output = self.dropout(pooled_output)
1608
+ logits = self.classifier(pooled_output)
1609
+ reshaped_logits = logits.view(-1, num_choices)
1610
+
1611
+ loss = None
1612
+ if labels is not None:
1613
+ loss_fct = CrossEntropyLoss()
1614
+ loss = loss_fct(reshaped_logits, labels)
1615
+
1616
+ if not return_dict:
1617
+ output = (reshaped_logits,) + outputs[2:]
1618
+ return ((loss,) + output) if loss is not None else output
1619
+
1620
+ return MultipleChoiceModelOutput(
1621
+ loss=loss,
1622
+ logits=reshaped_logits,
1623
+ hidden_states=outputs.hidden_states,
1624
+ attentions=outputs.attentions,
1625
+ )
1626
+
1627
+
1628
+ @add_start_docstrings(
1629
+ """
1630
+ Ernie Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1631
+ Named-Entity-Recognition (NER) tasks.
1632
+ """,
1633
+ ERNIE_START_DOCSTRING,
1634
+ )
1635
+ class ErnieForTokenClassification(ErniePreTrainedModel):
1636
+ # Copied from transformers.models.bert.modeling_bert.BertForTokenClassification.__init__ with Bert->Ernie,bert->ernie
1637
+ def __init__(self, config):
1638
+ super().__init__(config)
1639
+ self.num_labels = config.num_labels
1640
+
1641
+ self.ernie = ErnieModel(config, add_pooling_layer=False)
1642
+ classifier_dropout = (
1643
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1644
+ )
1645
+ self.dropout = nn.Dropout(classifier_dropout)
1646
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1647
+
1648
+ # Initialize weights and apply final processing
1649
+ self.post_init()
1650
+
1651
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1652
+ def forward(
1653
+ self,
1654
+ input_ids: Optional[torch.Tensor] = None,
1655
+ attention_mask: Optional[torch.Tensor] = None,
1656
+ token_type_ids: Optional[torch.Tensor] = None,
1657
+ task_type_ids: Optional[torch.Tensor] = None,
1658
+ position_ids: Optional[torch.Tensor] = None,
1659
+ head_mask: Optional[torch.Tensor] = None,
1660
+ inputs_embeds: Optional[torch.Tensor] = None,
1661
+ labels: Optional[torch.Tensor] = None,
1662
+ output_attentions: Optional[bool] = None,
1663
+ output_hidden_states: Optional[bool] = None,
1664
+ return_dict: Optional[bool] = None,
1665
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1666
+ r"""
1667
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1668
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1669
+ """
1670
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1671
+
1672
+ outputs = self.ernie(
1673
+ input_ids,
1674
+ attention_mask=attention_mask,
1675
+ token_type_ids=token_type_ids,
1676
+ task_type_ids=task_type_ids,
1677
+ position_ids=position_ids,
1678
+ head_mask=head_mask,
1679
+ inputs_embeds=inputs_embeds,
1680
+ output_attentions=output_attentions,
1681
+ output_hidden_states=output_hidden_states,
1682
+ return_dict=return_dict,
1683
+ )
1684
+
1685
+ sequence_output = outputs[0]
1686
+
1687
+ sequence_output = self.dropout(sequence_output)
1688
+ logits = self.classifier(sequence_output)
1689
+
1690
+ loss = None
1691
+ if labels is not None:
1692
+ loss_fct = CrossEntropyLoss()
1693
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1694
+
1695
+ if not return_dict:
1696
+ output = (logits,) + outputs[2:]
1697
+ return ((loss,) + output) if loss is not None else output
1698
+
1699
+ return TokenClassifierOutput(
1700
+ loss=loss,
1701
+ logits=logits,
1702
+ hidden_states=outputs.hidden_states,
1703
+ attentions=outputs.attentions,
1704
+ )
1705
+
1706
+
1707
+ @add_start_docstrings(
1708
+ """
1709
+ Ernie Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1710
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1711
+ """,
1712
+ ERNIE_START_DOCSTRING,
1713
+ )
1714
+ class ErnieForQuestionAnswering(ErniePreTrainedModel):
1715
+ # Copied from transformers.models.bert.modeling_bert.BertForQuestionAnswering.__init__ with Bert->Ernie,bert->ernie
1716
+ def __init__(self, config):
1717
+ super().__init__(config)
1718
+ self.num_labels = config.num_labels
1719
+
1720
+ self.ernie = ErnieModel(config, add_pooling_layer=False)
1721
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1722
+
1723
+ # Initialize weights and apply final processing
1724
+ self.post_init()
1725
+
1726
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1727
+ def forward(
1728
+ self,
1729
+ input_ids: Optional[torch.Tensor] = None,
1730
+ attention_mask: Optional[torch.Tensor] = None,
1731
+ token_type_ids: Optional[torch.Tensor] = None,
1732
+ task_type_ids: Optional[torch.Tensor] = None,
1733
+ position_ids: Optional[torch.Tensor] = None,
1734
+ head_mask: Optional[torch.Tensor] = None,
1735
+ inputs_embeds: Optional[torch.Tensor] = None,
1736
+ start_positions: Optional[torch.Tensor] = None,
1737
+ end_positions: Optional[torch.Tensor] = None,
1738
+ output_attentions: Optional[bool] = None,
1739
+ output_hidden_states: Optional[bool] = None,
1740
+ return_dict: Optional[bool] = None,
1741
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
1742
+ r"""
1743
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1744
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1745
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1746
+ are not taken into account for computing the loss.
1747
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1748
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1749
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1750
+ are not taken into account for computing the loss.
1751
+ """
1752
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1753
+
1754
+ outputs = self.ernie(
1755
+ input_ids,
1756
+ attention_mask=attention_mask,
1757
+ token_type_ids=token_type_ids,
1758
+ task_type_ids=task_type_ids,
1759
+ position_ids=position_ids,
1760
+ head_mask=head_mask,
1761
+ inputs_embeds=inputs_embeds,
1762
+ output_attentions=output_attentions,
1763
+ output_hidden_states=output_hidden_states,
1764
+ return_dict=return_dict,
1765
+ )
1766
+
1767
+ sequence_output = outputs[0]
1768
+
1769
+ logits = self.qa_outputs(sequence_output)
1770
+ start_logits, end_logits = logits.split(1, dim=-1)
1771
+ start_logits = start_logits.squeeze(-1).contiguous()
1772
+ end_logits = end_logits.squeeze(-1).contiguous()
1773
+
1774
+ total_loss = None
1775
+ if start_positions is not None and end_positions is not None:
1776
+ # If we are on multi-GPU, split add a dimension
1777
+ if len(start_positions.size()) > 1:
1778
+ start_positions = start_positions.squeeze(-1)
1779
+ if len(end_positions.size()) > 1:
1780
+ end_positions = end_positions.squeeze(-1)
1781
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1782
+ ignored_index = start_logits.size(1)
1783
+ start_positions = start_positions.clamp(0, ignored_index)
1784
+ end_positions = end_positions.clamp(0, ignored_index)
1785
+
1786
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1787
+ start_loss = loss_fct(start_logits, start_positions)
1788
+ end_loss = loss_fct(end_logits, end_positions)
1789
+ total_loss = (start_loss + end_loss) / 2
1790
+
1791
+ if not return_dict:
1792
+ output = (start_logits, end_logits) + outputs[2:]
1793
+ return ((total_loss,) + output) if total_loss is not None else output
1794
+
1795
+ return QuestionAnsweringModelOutput(
1796
+ loss=total_loss,
1797
+ start_logits=start_logits,
1798
+ end_logits=end_logits,
1799
+ hidden_states=outputs.hidden_states,
1800
+ attentions=outputs.attentions,
1801
+ )
1802
+
1803
+
1804
+ __all__ = [
1805
+ "ErnieForCausalLM",
1806
+ "ErnieForMaskedLM",
1807
+ "ErnieForMultipleChoice",
1808
+ "ErnieForNextSentencePrediction",
1809
+ "ErnieForPreTraining",
1810
+ "ErnieForQuestionAnswering",
1811
+ "ErnieForSequenceClassification",
1812
+ "ErnieForTokenClassification",
1813
+ "ErnieModel",
1814
+ "ErniePreTrainedModel",
1815
+ ]
janus/lib/python3.10/site-packages/transformers/models/falcon/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_falcon import *
22
+ from .modeling_falcon import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
janus/lib/python3.10/site-packages/transformers/models/falcon/__pycache__/configuration_falcon.cpython-310.pyc ADDED
Binary file (9.75 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/fuyu/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (591 Bytes). View file
 
janus/lib/python3.10/site-packages/transformers/models/fuyu/__pycache__/modeling_fuyu.cpython-310.pyc ADDED
Binary file (15.3 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/fuyu/__pycache__/processing_fuyu.cpython-310.pyc ADDED
Binary file (23.5 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/fuyu/configuration_fuyu.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Adept AI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Fuyu model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+ from ..auto import CONFIG_MAPPING
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class FuyuConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`FuyuForCausalLM`]. It is used to instantiate an
28
+ Fuyu model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of the
30
+ [adept/fuyu-8b](https://huggingface.co/adept/fuyu-8b).
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 262144):
38
+ Vocabulary size of the Fuyu model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`FuyuForCausalLM`]
40
+ hidden_size (`int`, *optional*, defaults to 4096):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 16384):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 36):
45
+ Number of hidden layers in the Transformer encoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 64):
47
+ Number of attention heads for each attention layer in the Transformer encoder.
48
+ hidden_act (`str` or `function`, *optional*, defaults to `"relu2"`):
49
+ The non-linear activation function (function or string) in the decoder.
50
+ max_position_embeddings (`int`, *optional*, defaults to 16384):
51
+ The maximum sequence length that this model might ever be used with.
52
+ image_size (`int`, *optional*, defaults to 300):
53
+ The input image size.
54
+ patch_size (`int`, *optional*, defaults to 30):
55
+ The input vision transformer encoding patch size.
56
+ num_channels (`int`, *optional*, defaults to 3):
57
+ The input image number of channels.
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
61
+ The epsilon used by the rms normalization layers.
62
+ use_cache (`bool`, *optional*, defaults to `True`):
63
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
64
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings
65
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
66
+ Whether to tie input and output embeddings.
67
+ rope_theta (`float`, *optional*, defaults to 25000.0):
68
+ The base period of the RoPE embeddings.
69
+ rope_scaling (`Dict`, *optional*):
70
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
71
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
72
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
73
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
74
+ these scaling strategies behave:
75
+ https://www.reddit.com/r/LocalFuyu/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
76
+ experimental feature, subject to breaking API changes in future versions.
77
+ qk_layernorm (`bool`, *optional*, defaults to `True`):
78
+ Whether or not to normalize the Queries and Keys after projecting the hidden states
79
+ hidden_dropout (`float`, *optional*, defaults to 0.0):
80
+ The dropout ratio after applying the MLP to the hidden states.
81
+ attention_dropout (`float`, *optional*, defaults to 0.0):
82
+ The dropout ratio after computing the attention scores.
83
+ partial_rotary_factor (`float`, *optional*, defaults to 0.5):
84
+ Percentage of the query and keys which will have rotary embedding.
85
+
86
+ pad_token_id (`int`, *optional*):
87
+ The id of the *padding* token.
88
+ bos_token_id (`int`, *optional*, defaults to 1):
89
+ The id of the *beginning-of-sequence* token.
90
+ eos_token_id (`Union[int, List[int]]`, *optional*, defaults to 2):
91
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
92
+ text_config (`dict`, *optional*):
93
+ Dictionary of configuration options used to initialize the `language``[`Aut`].
94
+
95
+ ```python
96
+ >>> from transformers import FuyuConfig
97
+
98
+ >>> # Initializing a Fuyu fuyu-7b style configuration
99
+ >>> configuration = FuyuConfig()
100
+ ```"""
101
+
102
+ model_type = "fuyu"
103
+ keys_to_ignore_at_inference = ["past_key_values"]
104
+
105
+ def __init__(
106
+ self,
107
+ vocab_size=262144,
108
+ hidden_size=4096,
109
+ intermediate_size=16384,
110
+ num_hidden_layers=36,
111
+ num_attention_heads=64,
112
+ hidden_act="relu2",
113
+ max_position_embeddings=16384,
114
+ image_size=300,
115
+ patch_size=30,
116
+ num_channels=3,
117
+ initializer_range=0.02,
118
+ layer_norm_eps=1e-5,
119
+ use_cache=True,
120
+ tie_word_embeddings=False,
121
+ rope_theta=25000.0,
122
+ rope_scaling=None,
123
+ qk_layernorm=True,
124
+ hidden_dropout=0.0,
125
+ attention_dropout=0.0,
126
+ partial_rotary_factor=0.5,
127
+ pad_token_id=None,
128
+ bos_token_id=1,
129
+ eos_token_id=2,
130
+ text_config=None,
131
+ **kwargs,
132
+ ):
133
+ if text_config is None:
134
+ text_config = {
135
+ "vocab_size": vocab_size,
136
+ "max_position_embeddings": max_position_embeddings,
137
+ "hidden_size": hidden_size,
138
+ "intermediate_size": intermediate_size,
139
+ "num_hidden_layers": num_hidden_layers,
140
+ "num_attention_heads": num_attention_heads,
141
+ "hidden_act": hidden_act,
142
+ "initializer_range": initializer_range,
143
+ "layer_norm_eps": layer_norm_eps,
144
+ "use_cache": use_cache,
145
+ "rope_theta": rope_theta,
146
+ "rope_scaling": rope_scaling,
147
+ "qk_layernorm": qk_layernorm,
148
+ "hidden_dropout": hidden_dropout,
149
+ "attention_dropout": attention_dropout,
150
+ "partial_rotary_factor": partial_rotary_factor,
151
+ "pad_token_id": pad_token_id,
152
+ "bos_token_id": bos_token_id,
153
+ "eos_token_id": eos_token_id,
154
+ "tie_word_embeddings": tie_word_embeddings,
155
+ }
156
+ logger.info("text_config is None. initializing the text model with default values.")
157
+ text_model_type = text_config["model_type"] if "model_type" in text_config else "persimmon"
158
+ self.text_config = CONFIG_MAPPING[text_model_type](**text_config)
159
+
160
+ self._vocab_size = vocab_size
161
+ self.max_position_embeddings = max_position_embeddings
162
+ self.image_size = image_size
163
+ self.patch_size = patch_size
164
+ self.num_channels = num_channels
165
+ self.hidden_size = hidden_size
166
+ self.intermediate_size = intermediate_size
167
+ self.num_hidden_layers = num_hidden_layers
168
+ self.num_attention_heads = num_attention_heads
169
+ self.hidden_act = hidden_act
170
+ self.initializer_range = initializer_range
171
+ self.layer_norm_eps = layer_norm_eps
172
+ self.use_cache = use_cache
173
+ self.rope_theta = rope_theta
174
+ self.rope_scaling = rope_scaling
175
+ self.qk_layernorm = qk_layernorm
176
+ self.hidden_dropout = hidden_dropout
177
+ self.attention_dropout = attention_dropout
178
+ self.partial_rotary_factor = partial_rotary_factor
179
+ self._rope_scaling_validation()
180
+
181
+ super().__init__(
182
+ pad_token_id=pad_token_id,
183
+ bos_token_id=bos_token_id,
184
+ eos_token_id=eos_token_id,
185
+ tie_word_embeddings=tie_word_embeddings,
186
+ **kwargs,
187
+ )
188
+
189
+ def _rope_scaling_validation(self):
190
+ """
191
+ Validate the `rope_scaling` configuration.
192
+ """
193
+ if self.rope_scaling is None:
194
+ return
195
+
196
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
197
+ raise ValueError(
198
+ "`rope_scaling` must be a dictionary with two fields, `type` and `factor`, " f"got {self.rope_scaling}"
199
+ )
200
+ rope_scaling_type = self.rope_scaling.get("type", None)
201
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
202
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
203
+ raise ValueError(
204
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
205
+ )
206
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
207
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
208
+
209
+
210
+ __all__ = ["FuyuConfig"]
janus/lib/python3.10/site-packages/transformers/models/longformer/__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_longformer import *
22
+ from .modeling_longformer import *
23
+ from .modeling_tf_longformer import *
24
+ from .tokenization_longformer import *
25
+ from .tokenization_longformer_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__)
janus/lib/python3.10/site-packages/transformers/models/longformer/__pycache__/modeling_longformer.cpython-310.pyc ADDED
Binary file (77.5 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/longformer/modeling_tf_longformer.py ADDED
The diff for this file is too large to render. See raw diff
 
janus/lib/python3.10/site-packages/transformers/models/longformer/tokenization_longformer.py ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The Allen Institute for AI team 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
+
33
+ @lru_cache()
34
+ # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode
35
+ def bytes_to_unicode():
36
+ """
37
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
38
+ characters the bpe code barfs on.
39
+
40
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
41
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
42
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
43
+ tables between utf-8 bytes and unicode strings.
44
+ """
45
+ bs = (
46
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
47
+ )
48
+ cs = bs[:]
49
+ n = 0
50
+ for b in range(2**8):
51
+ if b not in bs:
52
+ bs.append(b)
53
+ cs.append(2**8 + n)
54
+ n += 1
55
+ cs = [chr(n) for n in cs]
56
+ return dict(zip(bs, cs))
57
+
58
+
59
+ # Copied from transformers.models.roberta.tokenization_roberta.get_pairs
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
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer with FacebookAI/roberta-base->allenai/longformer-base-4096, RoBERTa->Longformer all-casing, RobertaTokenizer->LongformerTokenizer
75
+ class LongformerTokenizer(PreTrainedTokenizer):
76
+ """
77
+ Constructs a Longformer tokenizer, derived from the GPT-2 tokenizer, using byte-level Byte-Pair-Encoding.
78
+
79
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
80
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
81
+
82
+ ```python
83
+ >>> from transformers import LongformerTokenizer
84
+
85
+ >>> tokenizer = LongformerTokenizer.from_pretrained("allenai/longformer-base-4096")
86
+ >>> tokenizer("Hello world")["input_ids"]
87
+ [0, 31414, 232, 2]
88
+
89
+ >>> tokenizer(" Hello world")["input_ids"]
90
+ [0, 20920, 232, 2]
91
+ ```
92
+
93
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
94
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
95
+
96
+ <Tip>
97
+
98
+ When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
99
+
100
+ </Tip>
101
+
102
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
103
+ this superclass for more information regarding those methods.
104
+
105
+ Args:
106
+ vocab_file (`str`):
107
+ Path to the vocabulary file.
108
+ merges_file (`str`):
109
+ Path to the merges file.
110
+ errors (`str`, *optional*, defaults to `"replace"`):
111
+ Paradigm to follow when decoding bytes to UTF-8. See
112
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
113
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
114
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
115
+
116
+ <Tip>
117
+
118
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
119
+ sequence. The token used is the `cls_token`.
120
+
121
+ </Tip>
122
+
123
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
124
+ The end of sequence token.
125
+
126
+ <Tip>
127
+
128
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
129
+ The token used is the `sep_token`.
130
+
131
+ </Tip>
132
+
133
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
134
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
135
+ sequence classification or for a text and a question for question answering. It is also used as the last
136
+ token of a sequence built with special tokens.
137
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
138
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
139
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
140
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
141
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
142
+ token instead.
143
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
144
+ The token used for padding, for example when batching sequences of different lengths.
145
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
146
+ The token used for masking values. This is the token used when training this model with masked language
147
+ modeling. This is the token which the model will try to predict.
148
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
149
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
150
+ other word. (Longformer tokenizer detect beginning of words by the preceding space).
151
+ """
152
+
153
+ vocab_files_names = VOCAB_FILES_NAMES
154
+ model_input_names = ["input_ids", "attention_mask"]
155
+
156
+ def __init__(
157
+ self,
158
+ vocab_file,
159
+ merges_file,
160
+ errors="replace",
161
+ bos_token="<s>",
162
+ eos_token="</s>",
163
+ sep_token="</s>",
164
+ cls_token="<s>",
165
+ unk_token="<unk>",
166
+ pad_token="<pad>",
167
+ mask_token="<mask>",
168
+ add_prefix_space=False,
169
+ **kwargs,
170
+ ):
171
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
172
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
173
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
174
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
175
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
176
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
177
+
178
+ # Mask token behave like a normal word, i.e. include the space before it
179
+ mask_token = (
180
+ AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False)
181
+ if isinstance(mask_token, str)
182
+ else mask_token
183
+ )
184
+
185
+ # these special tokens are not part of the vocab.json, let's add them in the correct order
186
+
187
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
188
+ self.encoder = json.load(vocab_handle)
189
+ self.decoder = {v: k for k, v in self.encoder.items()}
190
+ self.errors = errors # how to handle errors in decoding
191
+ self.byte_encoder = bytes_to_unicode()
192
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
193
+ with open(merges_file, encoding="utf-8") as merges_handle:
194
+ bpe_merges = merges_handle.read().split("\n")[1:-1]
195
+ bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
196
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
197
+ self.cache = {}
198
+ self.add_prefix_space = add_prefix_space
199
+
200
+ # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
201
+ self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
202
+
203
+ super().__init__(
204
+ errors=errors,
205
+ bos_token=bos_token,
206
+ eos_token=eos_token,
207
+ unk_token=unk_token,
208
+ sep_token=sep_token,
209
+ cls_token=cls_token,
210
+ pad_token=pad_token,
211
+ mask_token=mask_token,
212
+ add_prefix_space=add_prefix_space,
213
+ **kwargs,
214
+ )
215
+
216
+ @property
217
+ def vocab_size(self):
218
+ return len(self.encoder)
219
+
220
+ def get_vocab(self):
221
+ vocab = dict(self.encoder).copy()
222
+ vocab.update(self.added_tokens_encoder)
223
+ return vocab
224
+
225
+ def bpe(self, token):
226
+ if token in self.cache:
227
+ return self.cache[token]
228
+ word = tuple(token)
229
+ pairs = get_pairs(word)
230
+
231
+ if not pairs:
232
+ return token
233
+
234
+ while True:
235
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
236
+ if bigram not in self.bpe_ranks:
237
+ break
238
+ first, second = bigram
239
+ new_word = []
240
+ i = 0
241
+ while i < len(word):
242
+ try:
243
+ j = word.index(first, i)
244
+ except ValueError:
245
+ new_word.extend(word[i:])
246
+ break
247
+ else:
248
+ new_word.extend(word[i:j])
249
+ i = j
250
+
251
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
252
+ new_word.append(first + second)
253
+ i += 2
254
+ else:
255
+ new_word.append(word[i])
256
+ i += 1
257
+ new_word = tuple(new_word)
258
+ word = new_word
259
+ if len(word) == 1:
260
+ break
261
+ else:
262
+ pairs = get_pairs(word)
263
+ word = " ".join(word)
264
+ self.cache[token] = word
265
+ return word
266
+
267
+ def _tokenize(self, text):
268
+ """Tokenize a string."""
269
+ bpe_tokens = []
270
+ for token in re.findall(self.pat, text):
271
+ token = "".join(
272
+ self.byte_encoder[b] for b in token.encode("utf-8")
273
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
274
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
275
+ return bpe_tokens
276
+
277
+ def _convert_token_to_id(self, token):
278
+ """Converts a token (str) in an id using the vocab."""
279
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
280
+
281
+ def _convert_id_to_token(self, index):
282
+ """Converts an index (integer) in a token (str) using the vocab."""
283
+ return self.decoder.get(index)
284
+
285
+ def convert_tokens_to_string(self, tokens):
286
+ """Converts a sequence of tokens (string) in a single string."""
287
+ text = "".join(tokens)
288
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
289
+ return text
290
+
291
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
292
+ if not os.path.isdir(save_directory):
293
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
294
+ return
295
+ vocab_file = os.path.join(
296
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
297
+ )
298
+ merge_file = os.path.join(
299
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
300
+ )
301
+
302
+ with open(vocab_file, "w", encoding="utf-8") as f:
303
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
304
+
305
+ index = 0
306
+ with open(merge_file, "w", encoding="utf-8") as writer:
307
+ writer.write("#version: 0.2\n")
308
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
309
+ if index != token_index:
310
+ logger.warning(
311
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
312
+ " Please check that the tokenizer is not corrupted!"
313
+ )
314
+ index = token_index
315
+ writer.write(" ".join(bpe_tokens) + "\n")
316
+ index += 1
317
+
318
+ return vocab_file, merge_file
319
+
320
+ def build_inputs_with_special_tokens(
321
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
322
+ ) -> List[int]:
323
+ """
324
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
325
+ adding special tokens. A Longformer sequence has the following format:
326
+
327
+ - single sequence: `<s> X </s>`
328
+ - pair of sequences: `<s> A </s></s> B </s>`
329
+
330
+ Args:
331
+ token_ids_0 (`List[int]`):
332
+ List of IDs to which the special tokens will be added.
333
+ token_ids_1 (`List[int]`, *optional*):
334
+ Optional second list of IDs for sequence pairs.
335
+
336
+ Returns:
337
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
338
+ """
339
+ if token_ids_1 is None:
340
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
341
+ cls = [self.cls_token_id]
342
+ sep = [self.sep_token_id]
343
+ return cls + token_ids_0 + sep + sep + token_ids_1 + sep
344
+
345
+ def get_special_tokens_mask(
346
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
347
+ ) -> List[int]:
348
+ """
349
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
350
+ special tokens using the tokenizer `prepare_for_model` method.
351
+
352
+ Args:
353
+ token_ids_0 (`List[int]`):
354
+ List of IDs.
355
+ token_ids_1 (`List[int]`, *optional*):
356
+ Optional second list of IDs for sequence pairs.
357
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
358
+ Whether or not the token list is already formatted with special tokens for the model.
359
+
360
+ Returns:
361
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
362
+ """
363
+ if already_has_special_tokens:
364
+ return super().get_special_tokens_mask(
365
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
366
+ )
367
+
368
+ if token_ids_1 is None:
369
+ return [1] + ([0] * len(token_ids_0)) + [1]
370
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
371
+
372
+ def create_token_type_ids_from_sequences(
373
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
374
+ ) -> List[int]:
375
+ """
376
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. Longformer does not
377
+ make use of token type ids, therefore a list of zeros is returned.
378
+
379
+ Args:
380
+ token_ids_0 (`List[int]`):
381
+ List of IDs.
382
+ token_ids_1 (`List[int]`, *optional*):
383
+ Optional second list of IDs for sequence pairs.
384
+
385
+ Returns:
386
+ `List[int]`: List of zeros.
387
+ """
388
+ sep = [self.sep_token_id]
389
+ cls = [self.cls_token_id]
390
+
391
+ if token_ids_1 is None:
392
+ return len(cls + token_ids_0 + sep) * [0]
393
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
394
+
395
+ def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
396
+ add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
397
+ if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
398
+ text = " " + text
399
+ return (text, kwargs)
400
+
401
+
402
+ __all__ = ["LongformerTokenizer"]
janus/lib/python3.10/site-packages/transformers/models/longformer/tokenization_longformer_fast.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The Allen Institute for AI team 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
+ """Fast Tokenization classes for Longformer."""
16
+
17
+ import json
18
+ from typing import List, Optional, Tuple
19
+
20
+ from tokenizers import processors
21
+
22
+ from ...tokenization_utils_base import AddedToken, BatchEncoding
23
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
24
+ from ...utils import logging
25
+ from .tokenization_longformer import LongformerTokenizer
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
31
+
32
+
33
+ # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast with FacebookAI/roberta-base->allenai/longformer-base-4096, RoBERTa->Longformer all-casing, Roberta->Longformer
34
+ class LongformerTokenizerFast(PreTrainedTokenizerFast):
35
+ """
36
+ Construct a "fast" Longformer tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2
37
+ tokenizer, using byte-level Byte-Pair-Encoding.
38
+
39
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
40
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
41
+
42
+ ```python
43
+ >>> from transformers import LongformerTokenizerFast
44
+
45
+ >>> tokenizer = LongformerTokenizerFast.from_pretrained("allenai/longformer-base-4096")
46
+ >>> tokenizer("Hello world")["input_ids"]
47
+ [0, 31414, 232, 2]
48
+
49
+ >>> tokenizer(" Hello world")["input_ids"]
50
+ [0, 20920, 232, 2]
51
+ ```
52
+
53
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
54
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
55
+
56
+ <Tip>
57
+
58
+ When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
59
+
60
+ </Tip>
61
+
62
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
63
+ refer to this superclass for more information regarding those methods.
64
+
65
+ Args:
66
+ vocab_file (`str`):
67
+ Path to the vocabulary file.
68
+ merges_file (`str`):
69
+ Path to the merges file.
70
+ errors (`str`, *optional*, defaults to `"replace"`):
71
+ Paradigm to follow when decoding bytes to UTF-8. See
72
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
73
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
74
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
75
+
76
+ <Tip>
77
+
78
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
79
+ sequence. The token used is the `cls_token`.
80
+
81
+ </Tip>
82
+
83
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
84
+ The end of sequence token.
85
+
86
+ <Tip>
87
+
88
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
89
+ The token used is the `sep_token`.
90
+
91
+ </Tip>
92
+
93
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
94
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
95
+ sequence classification or for a text and a question for question answering. It is also used as the last
96
+ token of a sequence built with special tokens.
97
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
98
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
99
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
100
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
101
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
102
+ token instead.
103
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
104
+ The token used for padding, for example when batching sequences of different lengths.
105
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
106
+ The token used for masking values. This is the token used when training this model with masked language
107
+ modeling. This is the token which the model will try to predict.
108
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
109
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
110
+ other word. (Longformer tokenizer detect beginning of words by the preceding space).
111
+ trim_offsets (`bool`, *optional*, defaults to `True`):
112
+ Whether the post processing step should trim offsets to avoid including whitespaces.
113
+ """
114
+
115
+ vocab_files_names = VOCAB_FILES_NAMES
116
+ model_input_names = ["input_ids", "attention_mask"]
117
+ slow_tokenizer_class = LongformerTokenizer
118
+
119
+ def __init__(
120
+ self,
121
+ vocab_file=None,
122
+ merges_file=None,
123
+ tokenizer_file=None,
124
+ errors="replace",
125
+ bos_token="<s>",
126
+ eos_token="</s>",
127
+ sep_token="</s>",
128
+ cls_token="<s>",
129
+ unk_token="<unk>",
130
+ pad_token="<pad>",
131
+ mask_token="<mask>",
132
+ add_prefix_space=False,
133
+ trim_offsets=True,
134
+ **kwargs,
135
+ ):
136
+ mask_token = (
137
+ AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False)
138
+ if isinstance(mask_token, str)
139
+ else mask_token
140
+ )
141
+ super().__init__(
142
+ vocab_file,
143
+ merges_file,
144
+ tokenizer_file=tokenizer_file,
145
+ errors=errors,
146
+ bos_token=bos_token,
147
+ eos_token=eos_token,
148
+ sep_token=sep_token,
149
+ cls_token=cls_token,
150
+ unk_token=unk_token,
151
+ pad_token=pad_token,
152
+ mask_token=mask_token,
153
+ add_prefix_space=add_prefix_space,
154
+ trim_offsets=trim_offsets,
155
+ **kwargs,
156
+ )
157
+
158
+ tokenizer_component = "post_processor"
159
+ tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)
160
+ if tokenizer_component_instance:
161
+ state = json.loads(tokenizer_component_instance.__getstate__())
162
+
163
+ # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
164
+ if "sep" in state:
165
+ state["sep"] = tuple(state["sep"])
166
+ if "cls" in state:
167
+ state["cls"] = tuple(state["cls"])
168
+
169
+ changes_to_apply = False
170
+
171
+ if state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
172
+ state["add_prefix_space"] = add_prefix_space
173
+ changes_to_apply = True
174
+
175
+ if state.get("trim_offsets", trim_offsets) != trim_offsets:
176
+ state["trim_offsets"] = trim_offsets
177
+ changes_to_apply = True
178
+
179
+ if changes_to_apply:
180
+ component_class = getattr(processors, state.pop("type"))
181
+ new_value = component_class(**state)
182
+ setattr(self.backend_tokenizer, tokenizer_component, new_value)
183
+
184
+ @property
185
+ def mask_token(self) -> str:
186
+ """
187
+ `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
188
+ having been set.
189
+
190
+ Longformer tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
191
+ comprise the space before the *<mask>*.
192
+ """
193
+ if self._mask_token is None:
194
+ if self.verbose:
195
+ logger.error("Using mask_token, but it is not set yet.")
196
+ return None
197
+ return str(self._mask_token)
198
+
199
+ @mask_token.setter
200
+ def mask_token(self, value):
201
+ """
202
+ Overriding the default behavior of the mask token to have it eat the space before it.
203
+
204
+ This is needed to preserve backward compatibility with all the previously used models based on Longformer.
205
+ """
206
+ # Mask token behave like a normal word, i.e. include the space before it
207
+ # So we set lstrip to True
208
+ value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
209
+ self._mask_token = value
210
+
211
+ def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
212
+ is_split_into_words = kwargs.get("is_split_into_words", False)
213
+ assert self.add_prefix_space or not is_split_into_words, (
214
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
215
+ "to use it with pretokenized inputs."
216
+ )
217
+
218
+ return super()._batch_encode_plus(*args, **kwargs)
219
+
220
+ def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
221
+ is_split_into_words = kwargs.get("is_split_into_words", False)
222
+
223
+ assert self.add_prefix_space or not is_split_into_words, (
224
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
225
+ "to use it with pretokenized inputs."
226
+ )
227
+
228
+ return super()._encode_plus(*args, **kwargs)
229
+
230
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
231
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
232
+ return tuple(files)
233
+
234
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
235
+ output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
236
+ if token_ids_1 is None:
237
+ return output
238
+
239
+ return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]
240
+
241
+ def create_token_type_ids_from_sequences(
242
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
243
+ ) -> List[int]:
244
+ """
245
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. Longformer does not
246
+ make use of token type ids, therefore a list of zeros is returned.
247
+
248
+ Args:
249
+ token_ids_0 (`List[int]`):
250
+ List of IDs.
251
+ token_ids_1 (`List[int]`, *optional*):
252
+ Optional second list of IDs for sequence pairs.
253
+
254
+ Returns:
255
+ `List[int]`: List of zeros.
256
+ """
257
+ sep = [self.sep_token_id]
258
+ cls = [self.cls_token_id]
259
+
260
+ if token_ids_1 is None:
261
+ return len(cls + token_ids_0 + sep) * [0]
262
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
263
+
264
+
265
+ __all__ = ["LongformerTokenizerFast"]
janus/lib/python3.10/site-packages/transformers/models/mixtral/__init__.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Mixtral AI and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import (
17
+ OptionalDependencyNotAvailable,
18
+ _LazyModule,
19
+ is_torch_available,
20
+ )
21
+
22
+
23
+ _import_structure = {
24
+ "configuration_mixtral": ["MixtralConfig"],
25
+ }
26
+
27
+
28
+ try:
29
+ if not is_torch_available():
30
+ raise OptionalDependencyNotAvailable()
31
+ except OptionalDependencyNotAvailable:
32
+ pass
33
+ else:
34
+ _import_structure["modeling_mixtral"] = [
35
+ "MixtralForCausalLM",
36
+ "MixtralForQuestionAnswering",
37
+ "MixtralModel",
38
+ "MixtralPreTrainedModel",
39
+ "MixtralForSequenceClassification",
40
+ "MixtralForTokenClassification",
41
+ ]
42
+
43
+
44
+ if TYPE_CHECKING:
45
+ from .configuration_mixtral import MixtralConfig
46
+
47
+ try:
48
+ if not is_torch_available():
49
+ raise OptionalDependencyNotAvailable()
50
+ except OptionalDependencyNotAvailable:
51
+ pass
52
+ else:
53
+ from .modeling_mixtral import (
54
+ MixtralForCausalLM,
55
+ MixtralForQuestionAnswering,
56
+ MixtralForSequenceClassification,
57
+ MixtralForTokenClassification,
58
+ MixtralModel,
59
+ MixtralPreTrainedModel,
60
+ )
61
+
62
+
63
+ else:
64
+ import sys
65
+
66
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
janus/lib/python3.10/site-packages/transformers/models/mixtral/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (952 Bytes). View file
 
janus/lib/python3.10/site-packages/transformers/models/mixtral/__pycache__/configuration_mixtral.cpython-310.pyc ADDED
Binary file (7.14 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/mixtral/__pycache__/modeling_mixtral.cpython-310.pyc ADDED
Binary file (43.9 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/mixtral/configuration_mixtral.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Mixtral 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
+ """Mixtral 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 MixtralConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`MixtralModel`]. It is used to instantiate an
27
+ Mixtral 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 Mixtral-7B-v0.1 or Mixtral-7B-Instruct-v0.1.
29
+
30
+ [mixtralai/Mixtral-8x7B](https://huggingface.co/mixtralai/Mixtral-8x7B)
31
+ [mixtralai/Mixtral-7B-Instruct-v0.1](https://huggingface.co/mixtralai/Mixtral-7B-Instruct-v0.1)
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 32000):
39
+ Vocabulary size of the Mixtral model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`MixtralModel`]
41
+ hidden_size (`int`, *optional*, defaults to 4096):
42
+ Dimension of the hidden representations.
43
+ intermediate_size (`int`, *optional*, defaults to 14336):
44
+ Dimension of the MLP representations.
45
+ num_hidden_layers (`int`, *optional*, defaults to 32):
46
+ Number of hidden layers in the Transformer encoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 32):
48
+ Number of attention heads for each attention layer in the Transformer encoder.
49
+ num_key_value_heads (`int`, *optional*, defaults to 8):
50
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
51
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
52
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
53
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
54
+ by meanpooling all the original heads within that group. For more details checkout [this
55
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `8`.
56
+ head_dim (`int`, *optional*, defaults to `hidden_size // num_attention_heads`):
57
+ The attention head dimension.
58
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
59
+ The non-linear activation function (function or string) in the decoder.
60
+ max_position_embeddings (`int`, *optional*, defaults to `4096*32`):
61
+ The maximum sequence length that this model might ever be used with. Mixtral's sliding window attention
62
+ allows sequence of up to 4096*32 tokens.
63
+ initializer_range (`float`, *optional*, defaults to 0.02):
64
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
65
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
66
+ The epsilon used by the rms normalization layers.
67
+ use_cache (`bool`, *optional*, defaults to `True`):
68
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
69
+ relevant if `config.is_decoder=True`.
70
+ pad_token_id (`int`, *optional*):
71
+ The id of the padding token.
72
+ bos_token_id (`int`, *optional*, defaults to 1):
73
+ The id of the "beginning-of-sequence" token.
74
+ eos_token_id (`int`, *optional*, defaults to 2):
75
+ The id of the "end-of-sequence" token.
76
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
77
+ Whether the model's input and output word embeddings should be tied.
78
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
79
+ The base period of the RoPE embeddings.
80
+ sliding_window (`int`, *optional*):
81
+ Sliding window attention window size. If not specified, will default to `4096`.
82
+ attention_dropout (`float`, *optional*, defaults to 0.0):
83
+ The dropout ratio for the attention probabilities.
84
+ num_experts_per_tok (`int`, *optional*, defaults to 2):
85
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
86
+ parameter
87
+ num_local_experts (`int`, *optional*, defaults to 8):
88
+ Number of experts per Sparse MLP layer.
89
+ output_router_logits (`bool`, *optional*, defaults to `False`):
90
+ Whether or not the router logits should be returned by the model. Enabeling this will also
91
+ allow the model to output the auxiliary loss. See [here]() for more details
92
+ router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
93
+ The aux loss factor for the total loss.
94
+ router_jitter_noise (`float`, *optional*, defaults to 0.0):
95
+ Amount of noise to add to the router.
96
+
97
+ ```python
98
+ >>> from transformers import MixtralModel, MixtralConfig
99
+
100
+ >>> # Initializing a Mixtral 7B style configuration
101
+ >>> configuration = MixtralConfig()
102
+
103
+ >>> # Initializing a model from the Mixtral 7B style configuration
104
+ >>> model = MixtralModel(configuration)
105
+
106
+ >>> # Accessing the model configuration
107
+ >>> configuration = model.config
108
+ ```"""
109
+
110
+ model_type = "mixtral"
111
+ keys_to_ignore_at_inference = ["past_key_values"]
112
+
113
+ def __init__(
114
+ self,
115
+ vocab_size=32000,
116
+ hidden_size=4096,
117
+ intermediate_size=14336,
118
+ num_hidden_layers=32,
119
+ num_attention_heads=32,
120
+ num_key_value_heads=8,
121
+ head_dim=None,
122
+ hidden_act="silu",
123
+ max_position_embeddings=4096 * 32,
124
+ initializer_range=0.02,
125
+ rms_norm_eps=1e-5,
126
+ use_cache=True,
127
+ pad_token_id=None,
128
+ bos_token_id=1,
129
+ eos_token_id=2,
130
+ tie_word_embeddings=False,
131
+ rope_theta=1e6,
132
+ sliding_window=None,
133
+ attention_dropout=0.0,
134
+ num_experts_per_tok=2,
135
+ num_local_experts=8,
136
+ output_router_logits=False,
137
+ router_aux_loss_coef=0.001,
138
+ router_jitter_noise=0.0,
139
+ **kwargs,
140
+ ):
141
+ self.vocab_size = vocab_size
142
+ self.max_position_embeddings = max_position_embeddings
143
+ self.hidden_size = hidden_size
144
+ self.intermediate_size = intermediate_size
145
+ self.num_hidden_layers = num_hidden_layers
146
+ self.num_attention_heads = num_attention_heads
147
+ self.sliding_window = sliding_window
148
+
149
+ # for backward compatibility
150
+ if num_key_value_heads is None:
151
+ num_key_value_heads = num_attention_heads
152
+
153
+ self.num_key_value_heads = num_key_value_heads
154
+ self.hidden_act = hidden_act
155
+ self.initializer_range = initializer_range
156
+ self.rms_norm_eps = rms_norm_eps
157
+ self.use_cache = use_cache
158
+ self.rope_theta = rope_theta
159
+ self.attention_dropout = attention_dropout
160
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
161
+
162
+ self.num_experts_per_tok = num_experts_per_tok
163
+ self.num_local_experts = num_local_experts
164
+ self.output_router_logits = output_router_logits
165
+ self.router_aux_loss_coef = router_aux_loss_coef
166
+ self.router_jitter_noise = router_jitter_noise
167
+ super().__init__(
168
+ pad_token_id=pad_token_id,
169
+ bos_token_id=bos_token_id,
170
+ eos_token_id=eos_token_id,
171
+ tie_word_embeddings=tie_word_embeddings,
172
+ **kwargs,
173
+ )
janus/lib/python3.10/site-packages/transformers/models/mixtral/modular_mixtral.py ADDED
@@ -0,0 +1,574 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Mistral AI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """PyTorch Mixtral model."""
21
+
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+
29
+ from ...activations import ACT2FN
30
+ from ...cache_utils import DynamicCache
31
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
32
+ from ...modeling_outputs import (
33
+ MoeCausalLMOutputWithPast,
34
+ MoeModelOutputWithPast,
35
+ )
36
+ from ...processing_utils import Unpack
37
+ from ...utils import (
38
+ LossKwargs,
39
+ logging,
40
+ )
41
+ from ..mistral.modeling_mistral import (
42
+ MistralAttention,
43
+ MistralForCausalLM,
44
+ MistralForQuestionAnswering,
45
+ MistralForSequenceClassification,
46
+ MistralForTokenClassification,
47
+ MistralModel,
48
+ MistralRMSNorm,
49
+ )
50
+ from .configuration_mixtral import MixtralConfig
51
+
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CHECKPOINT_FOR_DOC = "mistralai/Mixtral-8x7B-v0.1"
56
+ _CONFIG_FOR_DOC = "MixtralConfig"
57
+
58
+
59
+ def load_balancing_loss_func(
60
+ gate_logits: Union[torch.Tensor, Tuple[torch.Tensor], None],
61
+ num_experts: Optional[int] = None,
62
+ top_k=2,
63
+ attention_mask: Optional[torch.Tensor] = None,
64
+ ) -> Union[torch.Tensor, int]:
65
+ r"""
66
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
67
+
68
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
69
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
70
+ experts is too unbalanced.
71
+
72
+ Args:
73
+ gate_logits:
74
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
75
+ shape [batch_size X sequence_length, num_experts].
76
+ num_experts:
77
+ Number of experts
78
+ top_k:
79
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
80
+ parameter.
81
+ attention_mask (`torch.Tensor`, *optional*):
82
+ The attention_mask used in forward function
83
+ shape [batch_size X sequence_length] if not None.
84
+
85
+ Returns:
86
+ The auxiliary loss.
87
+ """
88
+ if gate_logits is None or not isinstance(gate_logits, tuple):
89
+ return 0
90
+
91
+ if isinstance(gate_logits, tuple):
92
+ compute_device = gate_logits[0].device
93
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
94
+
95
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
96
+
97
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
98
+
99
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
100
+
101
+ if attention_mask is None:
102
+ # Compute the percentage of tokens routed to each experts
103
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
104
+
105
+ # Compute the average probability of routing to these experts
106
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
107
+ else:
108
+ batch_size, sequence_length = attention_mask.shape
109
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
110
+
111
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
112
+ expert_attention_mask = (
113
+ attention_mask[None, :, :, None, None]
114
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
115
+ .reshape(-1, top_k, num_experts)
116
+ .to(compute_device)
117
+ )
118
+
119
+ # Compute the percentage of tokens routed to each experts
120
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
121
+ expert_attention_mask, dim=0
122
+ )
123
+
124
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
125
+ router_per_expert_attention_mask = (
126
+ attention_mask[None, :, :, None]
127
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
128
+ .reshape(-1, num_experts)
129
+ .to(compute_device)
130
+ )
131
+
132
+ # Compute the average probability of routing to these experts
133
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
134
+ router_per_expert_attention_mask, dim=0
135
+ )
136
+
137
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
138
+ return overall_loss * num_experts
139
+
140
+
141
+ class MixtralBlockSparseTop2MLP(nn.Module):
142
+ def __init__(self, config: MixtralConfig):
143
+ super().__init__()
144
+ self.ffn_dim = config.intermediate_size
145
+ self.hidden_dim = config.hidden_size
146
+
147
+ self.w1 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
148
+ self.w2 = nn.Linear(self.ffn_dim, self.hidden_dim, bias=False)
149
+ self.w3 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
150
+
151
+ self.act_fn = ACT2FN[config.hidden_act]
152
+
153
+ def forward(self, hidden_states):
154
+ current_hidden_states = self.act_fn(self.w1(hidden_states)) * self.w3(hidden_states)
155
+ current_hidden_states = self.w2(current_hidden_states)
156
+ return current_hidden_states
157
+
158
+
159
+ class MixtralSparseMoeBlock(nn.Module):
160
+ """
161
+ This implementation is
162
+ strictly equivalent to standard MoE with full capacity (no
163
+ dropped tokens). It's faster since it formulates MoE operations
164
+ in terms of block-sparse operations to accommodate imbalanced
165
+ assignments of tokens to experts, whereas standard MoE either
166
+ (1) drop tokens at the cost of reduced performance or (2) set
167
+ capacity factor to number of experts and thus waste computation
168
+ and memory on padding.
169
+ """
170
+
171
+ def __init__(self, config):
172
+ super().__init__()
173
+ self.hidden_dim = config.hidden_size
174
+ self.ffn_dim = config.intermediate_size
175
+ self.num_experts = config.num_local_experts
176
+ self.top_k = config.num_experts_per_tok
177
+
178
+ # gating
179
+ self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False)
180
+
181
+ self.experts = nn.ModuleList([MixtralBlockSparseTop2MLP(config) for _ in range(self.num_experts)])
182
+
183
+ # Jitter parameters
184
+ self.jitter_noise = config.router_jitter_noise
185
+
186
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
187
+ """ """
188
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
189
+ if self.training and self.jitter_noise > 0:
190
+ hidden_states *= torch.empty_like(hidden_states).uniform_(1.0 - self.jitter_noise, 1.0 + self.jitter_noise)
191
+ hidden_states = hidden_states.view(-1, hidden_dim)
192
+ # router_logits: (batch * sequence_length, n_experts)
193
+ router_logits = self.gate(hidden_states)
194
+
195
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
196
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
197
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
198
+ # we cast back to the input dtype
199
+ routing_weights = routing_weights.to(hidden_states.dtype)
200
+
201
+ final_hidden_states = torch.zeros(
202
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
203
+ )
204
+
205
+ # One hot encode the selected experts to create an expert mask
206
+ # this will be used to easily index which expert is going to be sollicitated
207
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
208
+
209
+ # Loop over all available experts in the model and perform the computation on each expert
210
+ for expert_idx in range(self.num_experts):
211
+ expert_layer = self.experts[expert_idx]
212
+ idx, top_x = torch.where(expert_mask[expert_idx])
213
+
214
+ # Index the correct hidden states and compute the expert hidden state for
215
+ # the current expert. We need to make sure to multiply the output hidden
216
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
217
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
218
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
219
+
220
+ # However `index_add_` only support torch tensors for indexing so we'll use
221
+ # the `top_x` tensor here.
222
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
223
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
224
+ return final_hidden_states, router_logits
225
+
226
+
227
+ class MixtralRMSNorm(MistralRMSNorm):
228
+ pass
229
+
230
+
231
+ class MixtralAttention(MistralAttention):
232
+ pass
233
+
234
+
235
+ class MixtralDecoderLayer(nn.Module):
236
+ def __init__(self, config: MixtralConfig, layer_idx: int):
237
+ super().__init__()
238
+ self.hidden_size = config.hidden_size
239
+
240
+ self.self_attn = MixtralAttention(config, layer_idx)
241
+
242
+ self.block_sparse_moe = MixtralSparseMoeBlock(config)
243
+ self.input_layernorm = MixtralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
244
+ self.post_attention_layernorm = MixtralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
245
+
246
+ def forward(
247
+ self,
248
+ hidden_states: torch.Tensor,
249
+ attention_mask: Optional[torch.Tensor] = None,
250
+ position_ids: Optional[torch.LongTensor] = None,
251
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
252
+ output_attentions: Optional[bool] = False,
253
+ output_router_logits: Optional[bool] = False,
254
+ use_cache: Optional[bool] = False,
255
+ cache_position: Optional[torch.LongTensor] = None,
256
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
257
+ **kwargs: Unpack[FlashAttentionKwargs],
258
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
259
+ """
260
+ Args:
261
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
262
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
263
+ `(batch, sequence_length)` where padding elements are indicated by 0.
264
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
265
+ output_attentions (`bool`, *optional*):
266
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
267
+ returned tensors for more detail.
268
+ output_router_logits (`bool`, *optional*):
269
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
270
+ should not be returned during inference.
271
+ use_cache (`bool`, *optional*):
272
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
273
+ (see `past_key_values`).
274
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
275
+ Indices depicting the position of the input sequence tokens in the sequence.
276
+ kwargs (`dict`, *optional*):
277
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
278
+ into the model
279
+ """
280
+
281
+ residual = hidden_states
282
+
283
+ hidden_states = self.input_layernorm(hidden_states)
284
+
285
+ # Self Attention
286
+ hidden_states, self_attn_weights = self.self_attn(
287
+ hidden_states=hidden_states,
288
+ position_embeddings=position_embeddings,
289
+ attention_mask=attention_mask,
290
+ position_ids=position_ids,
291
+ past_key_value=past_key_value,
292
+ output_attentions=output_attentions,
293
+ use_cache=use_cache,
294
+ cache_position=cache_position,
295
+ **kwargs,
296
+ )
297
+ hidden_states = residual + hidden_states
298
+
299
+ # Fully Connected
300
+ residual = hidden_states
301
+ hidden_states = self.post_attention_layernorm(hidden_states)
302
+ hidden_states, router_logits = self.block_sparse_moe(hidden_states)
303
+ hidden_states = residual + hidden_states
304
+
305
+ outputs = (hidden_states,)
306
+
307
+ if output_attentions:
308
+ outputs += (self_attn_weights,)
309
+
310
+ if output_router_logits:
311
+ outputs += (router_logits,)
312
+
313
+ return outputs
314
+
315
+
316
+ class MixtralModel(MistralModel):
317
+ def __init__(self, config: MixtralConfig):
318
+ super().__init__(config)
319
+ self.layers = nn.ModuleList(
320
+ [MixtralDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
321
+ )
322
+
323
+ def forward(
324
+ self,
325
+ input_ids: torch.LongTensor = None,
326
+ attention_mask: Optional[torch.Tensor] = None,
327
+ position_ids: Optional[torch.LongTensor] = None,
328
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
329
+ inputs_embeds: Optional[torch.FloatTensor] = None,
330
+ use_cache: Optional[bool] = None,
331
+ output_attentions: Optional[bool] = None,
332
+ output_hidden_states: Optional[bool] = None,
333
+ output_router_logits: Optional[bool] = None,
334
+ return_dict: Optional[bool] = None,
335
+ cache_position: Optional[torch.LongTensor] = None,
336
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
337
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
338
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
339
+ output_router_logits = (
340
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
341
+ )
342
+ output_hidden_states = (
343
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
344
+ )
345
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
346
+
347
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
348
+
349
+ if (input_ids is None) ^ (inputs_embeds is not None):
350
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
351
+
352
+ if self.gradient_checkpointing and self.training:
353
+ if use_cache:
354
+ logger.warning_once(
355
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
356
+ )
357
+ use_cache = False
358
+
359
+ if use_cache and past_key_values is None:
360
+ past_key_values = DynamicCache()
361
+
362
+ if inputs_embeds is None:
363
+ inputs_embeds = self.embed_tokens(input_ids)
364
+
365
+ if cache_position is None:
366
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
367
+ cache_position = torch.arange(
368
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
369
+ )
370
+ if position_ids is None:
371
+ position_ids = cache_position.unsqueeze(0)
372
+
373
+ causal_mask = self._update_causal_mask(
374
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
375
+ )
376
+
377
+ hidden_states = inputs_embeds
378
+
379
+ # create position embeddings to be shared across the decoder layers
380
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
381
+
382
+ # decoder layers
383
+ all_hidden_states = () if output_hidden_states else None
384
+ all_self_attns = () if output_attentions else None
385
+ all_router_logits = () if output_router_logits else None
386
+
387
+ for decoder_layer in self.layers:
388
+ if output_hidden_states:
389
+ all_hidden_states += (hidden_states,)
390
+
391
+ if self.gradient_checkpointing and self.training:
392
+ layer_outputs = self._gradient_checkpointing_func(
393
+ decoder_layer.__call__,
394
+ hidden_states,
395
+ causal_mask,
396
+ position_ids,
397
+ past_key_values,
398
+ output_attentions,
399
+ output_router_logits,
400
+ use_cache,
401
+ cache_position,
402
+ position_embeddings,
403
+ )
404
+ else:
405
+ layer_outputs = decoder_layer(
406
+ hidden_states,
407
+ attention_mask=causal_mask,
408
+ position_ids=position_ids,
409
+ past_key_value=past_key_values,
410
+ output_attentions=output_attentions,
411
+ output_router_logits=output_router_logits,
412
+ use_cache=use_cache,
413
+ cache_position=cache_position,
414
+ position_embeddings=position_embeddings,
415
+ **flash_attn_kwargs,
416
+ )
417
+
418
+ hidden_states = layer_outputs[0]
419
+
420
+ if output_attentions:
421
+ all_self_attns += (layer_outputs[1],)
422
+
423
+ if output_router_logits:
424
+ all_router_logits += (layer_outputs[-1],)
425
+
426
+ hidden_states = self.norm(hidden_states)
427
+
428
+ # add hidden states from the last decoder layer
429
+ if output_hidden_states:
430
+ all_hidden_states += (hidden_states,)
431
+
432
+ output = MoeModelOutputWithPast(
433
+ last_hidden_state=hidden_states,
434
+ past_key_values=past_key_values,
435
+ hidden_states=all_hidden_states,
436
+ attentions=all_self_attns,
437
+ router_logits=all_router_logits,
438
+ )
439
+ return output if return_dict else output.to_tuple()
440
+
441
+
442
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
443
+
444
+
445
+ class MixtralForCausalLM(MistralForCausalLM):
446
+ _tied_weights_keys = ["lm_head.weight"]
447
+
448
+ def __init__(self, config):
449
+ super().__init__(config)
450
+ self.model = MixtralModel(config)
451
+ self.router_aux_loss_coef = config.router_aux_loss_coef
452
+ self.num_experts = config.num_local_experts
453
+ self.num_experts_per_tok = config.num_experts_per_tok
454
+
455
+ def forward(
456
+ self,
457
+ input_ids: torch.LongTensor = None,
458
+ attention_mask: Optional[torch.Tensor] = None,
459
+ position_ids: Optional[torch.LongTensor] = None,
460
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
461
+ inputs_embeds: Optional[torch.FloatTensor] = None,
462
+ labels: Optional[torch.LongTensor] = None,
463
+ use_cache: Optional[bool] = None,
464
+ output_attentions: Optional[bool] = None,
465
+ output_hidden_states: Optional[bool] = None,
466
+ output_router_logits: Optional[bool] = None,
467
+ return_dict: Optional[bool] = None,
468
+ cache_position: Optional[torch.LongTensor] = None,
469
+ num_logits_to_keep: int = 0,
470
+ **kwargs: Unpack[KwargsForCausalLM],
471
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
472
+ r"""
473
+ Args:
474
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
475
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
476
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
477
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
478
+
479
+ num_logits_to_keep (`int`, *optional*):
480
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
481
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
482
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
483
+
484
+ Returns:
485
+
486
+ Example:
487
+
488
+ ```python
489
+ >>> from transformers import AutoTokenizer, MixtralForCausalLM
490
+
491
+ >>> model = MixtralForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-v0.1")
492
+ >>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-v0.1")
493
+
494
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
495
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
496
+
497
+ >>> # Generate
498
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
499
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
500
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
501
+ ```"""
502
+
503
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
504
+ output_router_logits = (
505
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
506
+ )
507
+
508
+ output_hidden_states = (
509
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
510
+ )
511
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
512
+
513
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
514
+ outputs = self.model(
515
+ input_ids=input_ids,
516
+ attention_mask=attention_mask,
517
+ position_ids=position_ids,
518
+ past_key_values=past_key_values,
519
+ inputs_embeds=inputs_embeds,
520
+ use_cache=use_cache,
521
+ output_attentions=output_attentions,
522
+ output_hidden_states=output_hidden_states,
523
+ output_router_logits=output_router_logits,
524
+ return_dict=return_dict,
525
+ cache_position=cache_position,
526
+ **kwargs,
527
+ )
528
+
529
+ hidden_states = outputs[0]
530
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
531
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
532
+
533
+ loss = None
534
+ if labels is not None:
535
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
536
+
537
+ aux_loss = None
538
+ if output_router_logits:
539
+ aux_loss = load_balancing_loss_func(
540
+ outputs.router_logits if return_dict else outputs[-1],
541
+ self.num_experts,
542
+ self.num_experts_per_tok,
543
+ attention_mask,
544
+ )
545
+ if labels is not None:
546
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
547
+
548
+ if not return_dict:
549
+ output = (logits,) + outputs[1:]
550
+ if output_router_logits:
551
+ output = (aux_loss,) + output
552
+ return (loss,) + output if loss is not None else output
553
+
554
+ return MoeCausalLMOutputWithPast(
555
+ loss=loss,
556
+ aux_loss=aux_loss,
557
+ logits=logits,
558
+ past_key_values=outputs.past_key_values,
559
+ hidden_states=outputs.hidden_states,
560
+ attentions=outputs.attentions,
561
+ router_logits=outputs.router_logits,
562
+ )
563
+
564
+
565
+ class MixtralForSequenceClassification(MistralForSequenceClassification):
566
+ pass
567
+
568
+
569
+ class MixtralForTokenClassification(MistralForTokenClassification):
570
+ pass
571
+
572
+
573
+ class MixtralForQuestionAnswering(MistralForQuestionAnswering):
574
+ pass
janus/lib/python3.10/site-packages/transformers/models/musicgen/__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_musicgen import *
22
+ from .modeling_musicgen import *
23
+ from .processing_musicgen 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__)
janus/lib/python3.10/site-packages/transformers/models/musicgen/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (574 Bytes). View file
 
janus/lib/python3.10/site-packages/transformers/models/musicgen/__pycache__/configuration_musicgen.cpython-310.pyc ADDED
Binary file (9.47 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/musicgen/__pycache__/modeling_musicgen.cpython-310.pyc ADDED
Binary file (78.2 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/musicgen/__pycache__/processing_musicgen.cpython-310.pyc ADDED
Binary file (4.5 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/musicgen/configuration_musicgen.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Meta 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
+ """MusicGen model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+ from ..auto.configuration_auto import AutoConfig
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class MusicgenDecoderConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of an [`MusicgenDecoder`]. It is used to instantiate a
28
+ MusicGen decoder according to the specified arguments, defining the model architecture. Instantiating a
29
+ configuration with the defaults will yield a similar configuration to that of the MusicGen
30
+ [facebook/musicgen-small](https://huggingface.co/facebook/musicgen-small) architecture.
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 2048):
38
+ Vocabulary size of the MusicgenDecoder model. Defines the number of different tokens that can be
39
+ represented by the `inputs_ids` passed when calling [`MusicgenDecoder`].
40
+ hidden_size (`int`, *optional*, defaults to 1024):
41
+ Dimensionality of the layers and the pooler layer.
42
+ num_hidden_layers (`int`, *optional*, defaults to 24):
43
+ Number of decoder layers.
44
+ num_attention_heads (`int`, *optional*, defaults to 16):
45
+ Number of attention heads for each attention layer in the Transformer block.
46
+ ffn_dim (`int`, *optional*, defaults to 4096):
47
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer block.
48
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
49
+ The non-linear activation function (function or string) in the decoder and pooler. If string, `"gelu"`,
50
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
51
+ dropout (`float`, *optional*, defaults to 0.1):
52
+ The dropout probability for all fully connected layers in the embeddings, text_encoder, and pooler.
53
+ attention_dropout (`float`, *optional*, defaults to 0.0):
54
+ The dropout ratio for the attention probabilities.
55
+ activation_dropout (`float`, *optional*, defaults to 0.0):
56
+ The dropout ratio for activations inside the fully connected layer.
57
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
58
+ The maximum sequence length that this model might ever be used with. Typically, set this to something large
59
+ just in case (e.g., 512 or 1024 or 2048).
60
+ initializer_factor (`float`, *optional*, defaults to 0.02):
61
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
62
+ layerdrop (`float`, *optional*, defaults to 0.0):
63
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
64
+ for more details.
65
+ scale_embedding (`bool`, *optional*, defaults to `False`):
66
+ Scale embeddings by diving by sqrt(hidden_size).
67
+ use_cache (`bool`, *optional*, defaults to `True`):
68
+ Whether the model should return the last key/values attentions (not used by all models)
69
+ num_codebooks (`int`, *optional*, defaults to 4):
70
+ The number of parallel codebooks forwarded to the model.
71
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
72
+ Whether input and output word embeddings should be tied.
73
+ audio_channels (`int`, *optional*, defaults to 1
74
+ Number of channels in the audio data. Either 1 for mono or 2 for stereo. Stereo models generate a separate
75
+ audio stream for the left/right output channels. Mono models generate a single audio stream output.
76
+ """
77
+
78
+ model_type = "musicgen_decoder"
79
+ base_config_key = "decoder_config"
80
+ keys_to_ignore_at_inference = ["past_key_values"]
81
+
82
+ def __init__(
83
+ self,
84
+ vocab_size=2048,
85
+ max_position_embeddings=2048,
86
+ num_hidden_layers=24,
87
+ ffn_dim=4096,
88
+ num_attention_heads=16,
89
+ layerdrop=0.0,
90
+ use_cache=True,
91
+ activation_function="gelu",
92
+ hidden_size=1024,
93
+ dropout=0.1,
94
+ attention_dropout=0.0,
95
+ activation_dropout=0.0,
96
+ initializer_factor=0.02,
97
+ scale_embedding=False,
98
+ num_codebooks=4,
99
+ audio_channels=1,
100
+ pad_token_id=2048,
101
+ bos_token_id=2048,
102
+ eos_token_id=None,
103
+ tie_word_embeddings=False,
104
+ **kwargs,
105
+ ):
106
+ self.vocab_size = vocab_size
107
+ self.max_position_embeddings = max_position_embeddings
108
+ self.hidden_size = hidden_size
109
+ self.ffn_dim = ffn_dim
110
+ self.num_hidden_layers = num_hidden_layers
111
+ self.num_attention_heads = num_attention_heads
112
+ self.dropout = dropout
113
+ self.attention_dropout = attention_dropout
114
+ self.activation_dropout = activation_dropout
115
+ self.activation_function = activation_function
116
+ self.initializer_factor = initializer_factor
117
+ self.layerdrop = layerdrop
118
+ self.use_cache = use_cache
119
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
120
+ self.num_codebooks = num_codebooks
121
+
122
+ if audio_channels not in [1, 2]:
123
+ raise ValueError(f"Expected 1 (mono) or 2 (stereo) audio channels, got {audio_channels} channels.")
124
+ self.audio_channels = audio_channels
125
+
126
+ super().__init__(
127
+ pad_token_id=pad_token_id,
128
+ bos_token_id=bos_token_id,
129
+ eos_token_id=eos_token_id,
130
+ tie_word_embeddings=tie_word_embeddings,
131
+ **kwargs,
132
+ )
133
+
134
+
135
+ class MusicgenConfig(PretrainedConfig):
136
+ r"""
137
+ This is the configuration class to store the configuration of a [`MusicgenModel`]. It is used to instantiate a
138
+ MusicGen model according to the specified arguments, defining the text encoder, audio encoder and MusicGen decoder
139
+ configs.
140
+
141
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
142
+ documentation from [`PretrainedConfig`] for more information.
143
+
144
+ Args:
145
+ kwargs (*optional*):
146
+ Dictionary of keyword arguments. Notably:
147
+
148
+ - **text_encoder** ([`PretrainedConfig`], *optional*) -- An instance of a configuration object that
149
+ defines the text encoder config.
150
+ - **audio_encoder** ([`PretrainedConfig`], *optional*) -- An instance of a configuration object that
151
+ defines the audio encoder config.
152
+ - **decoder** ([`PretrainedConfig`], *optional*) -- An instance of a configuration object that defines
153
+ the decoder config.
154
+
155
+ Example:
156
+
157
+ ```python
158
+ >>> from transformers import (
159
+ ... MusicgenConfig,
160
+ ... MusicgenDecoderConfig,
161
+ ... T5Config,
162
+ ... EncodecConfig,
163
+ ... MusicgenForConditionalGeneration,
164
+ ... )
165
+
166
+ >>> # Initializing text encoder, audio encoder, and decoder model configurations
167
+ >>> text_encoder_config = T5Config()
168
+ >>> audio_encoder_config = EncodecConfig()
169
+ >>> decoder_config = MusicgenDecoderConfig()
170
+
171
+ >>> configuration = MusicgenConfig.from_sub_models_config(
172
+ ... text_encoder_config, audio_encoder_config, decoder_config
173
+ ... )
174
+
175
+ >>> # Initializing a MusicgenForConditionalGeneration (with random weights) from the facebook/musicgen-small style configuration
176
+ >>> model = MusicgenForConditionalGeneration(configuration)
177
+
178
+ >>> # Accessing the model configuration
179
+ >>> configuration = model.config
180
+ >>> config_text_encoder = model.config.text_encoder
181
+ >>> config_audio_encoder = model.config.audio_encoder
182
+ >>> config_decoder = model.config.decoder
183
+
184
+ >>> # Saving the model, including its configuration
185
+ >>> model.save_pretrained("musicgen-model")
186
+
187
+ >>> # loading model and config from pretrained folder
188
+ >>> musicgen_config = MusicgenConfig.from_pretrained("musicgen-model")
189
+ >>> model = MusicgenForConditionalGeneration.from_pretrained("musicgen-model", config=musicgen_config)
190
+ ```"""
191
+
192
+ model_type = "musicgen"
193
+ sub_configs = {
194
+ "text_encoder": AutoConfig,
195
+ "audio_encoder": AutoConfig,
196
+ "decoder": MusicgenDecoderConfig,
197
+ }
198
+ is_composition = True
199
+
200
+ def __init__(self, **kwargs):
201
+ super().__init__(**kwargs)
202
+ if "text_encoder" not in kwargs or "audio_encoder" not in kwargs or "decoder" not in kwargs:
203
+ raise ValueError("Config has to be initialized with text_encoder, audio_encoder and decoder config")
204
+
205
+ text_encoder_config = kwargs.pop("text_encoder")
206
+ text_encoder_model_type = text_encoder_config.pop("model_type")
207
+
208
+ audio_encoder_config = kwargs.pop("audio_encoder")
209
+ audio_encoder_model_type = audio_encoder_config.pop("model_type")
210
+
211
+ decoder_config = kwargs.pop("decoder")
212
+
213
+ self.text_encoder = AutoConfig.for_model(text_encoder_model_type, **text_encoder_config)
214
+ self.audio_encoder = AutoConfig.for_model(audio_encoder_model_type, **audio_encoder_config)
215
+ self.decoder = MusicgenDecoderConfig(**decoder_config)
216
+ self.is_encoder_decoder = True
217
+
218
+ @classmethod
219
+ def from_sub_models_config(
220
+ cls,
221
+ text_encoder_config: PretrainedConfig,
222
+ audio_encoder_config: PretrainedConfig,
223
+ decoder_config: MusicgenDecoderConfig,
224
+ **kwargs,
225
+ ):
226
+ r"""
227
+ Instantiate a [`MusicgenConfig`] (or a derived class) from text encoder, audio encoder and decoder
228
+ configurations.
229
+
230
+ Returns:
231
+ [`MusicgenConfig`]: An instance of a configuration object
232
+ """
233
+
234
+ return cls(
235
+ text_encoder=text_encoder_config.to_dict(),
236
+ audio_encoder=audio_encoder_config.to_dict(),
237
+ decoder=decoder_config.to_dict(),
238
+ **kwargs,
239
+ )
240
+
241
+ @property
242
+ # This is a property because you might want to change the codec model on the fly
243
+ def sampling_rate(self):
244
+ return self.audio_encoder.sampling_rate
245
+
246
+
247
+ __all__ = ["MusicgenConfig", "MusicgenDecoderConfig"]
janus/lib/python3.10/site-packages/transformers/models/musicgen/modeling_musicgen.py ADDED
The diff for this file is too large to render. See raw diff
 
janus/lib/python3.10/site-packages/transformers/models/musicgen/processing_musicgen.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Text/audio processor class for MusicGen
17
+ """
18
+
19
+ from typing import List, Optional
20
+
21
+ import numpy as np
22
+
23
+ from ...processing_utils import ProcessorMixin
24
+ from ...utils import to_numpy
25
+
26
+
27
+ class MusicgenProcessor(ProcessorMixin):
28
+ r"""
29
+ Constructs a MusicGen processor which wraps an EnCodec feature extractor and a T5 tokenizer into a single processor
30
+ class.
31
+
32
+ [`MusicgenProcessor`] offers all the functionalities of [`EncodecFeatureExtractor`] and [`TTokenizer`]. See
33
+ [`~MusicgenProcessor.__call__`] and [`~MusicgenProcessor.decode`] for more information.
34
+
35
+ Args:
36
+ feature_extractor (`EncodecFeatureExtractor`):
37
+ An instance of [`EncodecFeatureExtractor`]. The feature extractor is a required input.
38
+ tokenizer (`T5Tokenizer`):
39
+ An instance of [`T5Tokenizer`]. The tokenizer is a required input.
40
+ """
41
+
42
+ feature_extractor_class = "EncodecFeatureExtractor"
43
+ tokenizer_class = ("T5Tokenizer", "T5TokenizerFast")
44
+
45
+ def __init__(self, feature_extractor, tokenizer):
46
+ super().__init__(feature_extractor, tokenizer)
47
+ self.current_processor = self.feature_extractor
48
+ self._in_target_context_manager = False
49
+
50
+ def get_decoder_prompt_ids(self, task=None, language=None, no_timestamps=True):
51
+ return self.tokenizer.get_decoder_prompt_ids(task=task, language=language, no_timestamps=no_timestamps)
52
+
53
+ def __call__(self, *args, **kwargs):
54
+ """
55
+ Forwards the `audio` argument to EncodecFeatureExtractor's [`~EncodecFeatureExtractor.__call__`] and the `text`
56
+ argument to [`~T5Tokenizer.__call__`]. Please refer to the doctsring of the above two methods for more
57
+ information.
58
+ """
59
+ # For backward compatibility
60
+ if self._in_target_context_manager:
61
+ return self.current_processor(*args, **kwargs)
62
+
63
+ audio = kwargs.pop("audio", None)
64
+ sampling_rate = kwargs.pop("sampling_rate", None)
65
+ text = kwargs.pop("text", None)
66
+ if len(args) > 0:
67
+ audio = args[0]
68
+ args = args[1:]
69
+
70
+ if audio is None and text is None:
71
+ raise ValueError("You need to specify either an `audio` or `text` input to process.")
72
+
73
+ if text is not None:
74
+ inputs = self.tokenizer(text, **kwargs)
75
+
76
+ if audio is not None:
77
+ audio_inputs = self.feature_extractor(audio, *args, sampling_rate=sampling_rate, **kwargs)
78
+
79
+ if audio is None:
80
+ return inputs
81
+
82
+ elif text is None:
83
+ return audio_inputs
84
+
85
+ else:
86
+ inputs["input_values"] = audio_inputs["input_values"]
87
+ if "padding_mask" in audio_inputs:
88
+ inputs["padding_mask"] = audio_inputs["padding_mask"]
89
+ return inputs
90
+
91
+ def batch_decode(self, *args, **kwargs):
92
+ """
93
+ This method is used to decode either batches of audio outputs from the MusicGen model, or batches of token ids
94
+ from the tokenizer. In the case of decoding token ids, this method forwards all its arguments to T5Tokenizer's
95
+ [`~PreTrainedTokenizer.batch_decode`]. Please refer to the docstring of this method for more information.
96
+ """
97
+ audio_values = kwargs.pop("audio", None)
98
+ padding_mask = kwargs.pop("padding_mask", None)
99
+
100
+ if len(args) > 0:
101
+ audio_values = args[0]
102
+ args = args[1:]
103
+
104
+ if audio_values is not None:
105
+ return self._decode_audio(audio_values, padding_mask=padding_mask)
106
+ else:
107
+ return self.tokenizer.batch_decode(*args, **kwargs)
108
+
109
+ def decode(self, *args, **kwargs):
110
+ """
111
+ This method forwards all its arguments to T5Tokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to the
112
+ docstring of this method for more information.
113
+ """
114
+ return self.tokenizer.decode(*args, **kwargs)
115
+
116
+ def _decode_audio(self, audio_values, padding_mask: Optional = None) -> List[np.ndarray]:
117
+ """
118
+ This method strips any padding from the audio values to return a list of numpy audio arrays.
119
+ """
120
+ audio_values = to_numpy(audio_values)
121
+ bsz, channels, seq_len = audio_values.shape
122
+
123
+ if padding_mask is None:
124
+ return list(audio_values)
125
+
126
+ padding_mask = to_numpy(padding_mask)
127
+
128
+ # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding**
129
+ # token (so that the generated audio values are **not** treated as padded tokens)
130
+ difference = seq_len - padding_mask.shape[-1]
131
+ padding_value = 1 - self.feature_extractor.padding_value
132
+ padding_mask = np.pad(padding_mask, ((0, 0), (0, difference)), "constant", constant_values=padding_value)
133
+
134
+ audio_values = audio_values.tolist()
135
+ for i in range(bsz):
136
+ sliced_audio = np.asarray(audio_values[i])[
137
+ padding_mask[i][None, :] != self.feature_extractor.padding_value
138
+ ]
139
+ audio_values[i] = sliced_audio.reshape(channels, -1)
140
+
141
+ return audio_values
142
+
143
+
144
+ __all__ = ["MusicgenProcessor"]
janus/lib/python3.10/site-packages/transformers/models/paligemma/__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_paligemma import *
22
+ from .modeling_paligemma import *
23
+ from .processing_paligemma 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__)
janus/lib/python3.10/site-packages/transformers/models/paligemma/__pycache__/configuration_paligemma.cpython-310.pyc ADDED
Binary file (4.76 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/paligemma/modeling_paligemma.py ADDED
@@ -0,0 +1,623 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """PyTorch PaliGemmamodel."""
16
+
17
+ from dataclasses import dataclass
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ import torch
21
+ import torch.utils.checkpoint
22
+ from torch import nn
23
+
24
+ from ...cache_utils import Cache, HybridCache, StaticCache
25
+ from ...generation import GenerationMixin
26
+ from ...modeling_utils import PreTrainedModel
27
+ from ...utils import (
28
+ ModelOutput,
29
+ add_start_docstrings,
30
+ add_start_docstrings_to_model_forward,
31
+ is_flash_attn_2_available,
32
+ logging,
33
+ replace_return_docstrings,
34
+ )
35
+ from .configuration_paligemma import PaliGemmaConfig
36
+
37
+
38
+ if is_flash_attn_2_available():
39
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
40
+
41
+ from ..auto import AutoModel, AutoModelForCausalLM
42
+
43
+
44
+ logger = logging.get_logger(__name__)
45
+
46
+ _CONFIG_FOR_DOC = "PaliGemmaConfig"
47
+
48
+
49
+ # Adapted from transformers.models.llama.modeling_llama.LlamaModel._prepare_4d_causal_attention_mask_with_cache_position
50
+ # But Paligemma has no causal mask on prefix
51
+ def _prepare_4d_causal_attention_mask_with_cache_position(
52
+ attention_mask: torch.Tensor,
53
+ sequence_length: int,
54
+ target_length: int,
55
+ dtype: torch.dtype,
56
+ device: torch.device,
57
+ min_dtype: float,
58
+ cache_position: torch.Tensor,
59
+ batch_size: int,
60
+ is_training: bool = False,
61
+ token_type_ids: torch.Tensor = None,
62
+ **kwargs,
63
+ ):
64
+ """
65
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
66
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
67
+
68
+ Args:
69
+ attention_mask (`torch.Tensor`):
70
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
71
+ sequence_length (`int`):
72
+ The sequence length being processed.
73
+ target_length (`int`):
74
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
75
+ dtype (`torch.dtype`):
76
+ The dtype to use for the 4D attention mask.
77
+ device (`torch.device`):
78
+ The device to plcae the 4D attention mask on.
79
+ min_dtype (`float`):
80
+ The minimum value representable with the dtype `dtype`.
81
+ cache_position (`torch.Tensor`):
82
+ Indices depicting the position of the input sequence tokens in the sequence.
83
+ batch_size (`torch.Tensor`):
84
+ Batch size.
85
+ is_training (`bool`):
86
+ Whether the model is in training mode or in inference. The condition is checked by presence/absence of `token_type_ids/labels`
87
+ """
88
+ if attention_mask is not None and attention_mask.dim() == 4:
89
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
90
+ causal_mask = attention_mask
91
+ else:
92
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
93
+ # Causal diagonal mask only if training, otherwise attend to the whole prefix. Training-specific attn for prefix is handled below
94
+ if sequence_length != 1:
95
+ if is_training:
96
+ causal_mask = torch.triu(causal_mask, diagonal=1)
97
+ else:
98
+ causal_mask[:, :sequence_length] = 0.0
99
+
100
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
101
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
102
+ if attention_mask is not None:
103
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
104
+ mask_length = attention_mask.shape[-1]
105
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(causal_mask.device)
106
+ padding_mask = padding_mask == 0
107
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
108
+ padding_mask, min_dtype
109
+ )
110
+ # we are training thus we need to create a full mask on the image + prefix but causal on suffix
111
+ if is_training:
112
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
113
+ token_type_ids[:, None, None, :].to(causal_mask.device) == 0, 0
114
+ )
115
+ return causal_mask
116
+
117
+
118
+ @dataclass
119
+ class PaliGemmaCausalLMOutputWithPast(ModelOutput):
120
+ """
121
+ Base class for PaliGemmacausal language model (or autoregressive) outputs.
122
+
123
+ Args:
124
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
125
+ Language modeling loss (for next-token prediction).
126
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.text_config.vocab_size)`):
127
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
128
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
129
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
130
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
131
+
132
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
133
+ `past_key_values` input) to speed up sequential decoding.
134
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
135
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
136
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
137
+
138
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
139
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
140
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
141
+ sequence_length)`.
142
+
143
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
144
+ heads.
145
+ image_hidden_states (`torch.FloatTensor`, *optional*):
146
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
147
+ image_hidden_states of the model produced by the vision encoder after projecting last hidden state.
148
+ """
149
+
150
+ loss: Optional[torch.FloatTensor] = None
151
+ logits: torch.FloatTensor = None
152
+ past_key_values: Optional[Union[List[torch.FloatTensor], Cache]] = None
153
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
154
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
155
+ image_hidden_states: Optional[torch.FloatTensor] = None
156
+
157
+
158
+ class PaliGemmaMultiModalProjector(nn.Module):
159
+ def __init__(self, config: PaliGemmaConfig):
160
+ super().__init__()
161
+ self.linear = nn.Linear(config.vision_config.hidden_size, config.vision_config.projection_dim, bias=True)
162
+
163
+ def forward(self, image_features):
164
+ hidden_states = self.linear(image_features)
165
+
166
+ return hidden_states
167
+
168
+
169
+ PALIGEMMA_START_DOCSTRING = r"""
170
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
171
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
172
+ etc.)
173
+
174
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
175
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
176
+ and behavior.
177
+
178
+ Parameters:
179
+ config ([`PaliGemmaConfig`] or [`PaliGemmaVisionConfig`]):
180
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
181
+ load the weights associated with the model, only the configuration. Check out the
182
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
183
+ """
184
+
185
+
186
+ @add_start_docstrings(
187
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
188
+ PALIGEMMA_START_DOCSTRING,
189
+ )
190
+ class PaliGemmaPreTrainedModel(PreTrainedModel):
191
+ config_class = PaliGemmaConfig
192
+ base_model_prefix = "model"
193
+ supports_gradient_checkpointing = True
194
+ _no_split_modules = ["PaliGemmaMultiModalProjector"]
195
+ _skip_keys_device_placement = "past_key_values"
196
+ _supports_cache_class = True
197
+ _supports_quantized_cache = True
198
+ _supports_static_cache = True
199
+ _supports_cache_class = True
200
+ _supports_flash_attn_2 = True
201
+ _supports_sdpa = True
202
+
203
+ def _init_weights(self, module):
204
+ # important: this ported version of PaliGemmaisn't meant for training from scratch - only
205
+ # inference and fine-tuning
206
+ std = (
207
+ self.config.initializer_range
208
+ if hasattr(self.config, "initializer_range")
209
+ else self.config.text_config.initializer_range
210
+ )
211
+
212
+ if hasattr(module, "class_embedding"):
213
+ module.class_embedding.data.normal_(mean=0.0, std=std)
214
+
215
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
216
+ module.weight.data.normal_(mean=0.0, std=std)
217
+ if module.bias is not None:
218
+ module.bias.data.zero_()
219
+ elif isinstance(module, nn.Embedding):
220
+ module.weight.data.normal_(mean=0.0, std=std)
221
+ if module.padding_idx is not None:
222
+ module.weight.data[module.padding_idx].zero_()
223
+
224
+
225
+ PALIGEMMA_INPUTS_DOCSTRING = r"""
226
+ Args:
227
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
228
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
229
+ it.
230
+
231
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
232
+ [`PreTrainedTokenizer.__call__`] for details.
233
+
234
+ [What are input IDs?](../glossary#input-ids)
235
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
236
+ The tensors corresponding to the input images. Pixel values can be obtained using
237
+ [`AutoImageProcessor`]. See [`SiglipImageProcessor.__call__`] for details ([]`PaliGemmaProcessor`] uses
238
+ [`SiglipImageProcessor`] for processing images).
239
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
240
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
241
+
242
+ - 1 for tokens that are **not masked**,
243
+ - 0 for tokens that are **masked**.
244
+
245
+ [What are attention masks?](../glossary#attention-mask)
246
+
247
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
248
+ [`PreTrainedTokenizer.__call__`] for details.
249
+
250
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
251
+ `past_key_values`).
252
+
253
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
254
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
255
+ information on the default strategy.
256
+
257
+ - 1 indicates the head is **not masked**,
258
+ - 0 indicates the head is **masked**.
259
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
260
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
261
+ config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
262
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
263
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
264
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
265
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
266
+
267
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
268
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
269
+
270
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
271
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
272
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
273
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
274
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
275
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
276
+ model's internal embedding lookup matrix.
277
+ use_cache (`bool`, *optional*):
278
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
279
+ `past_key_values`).
280
+ output_attentions (`bool`, *optional*):
281
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
282
+ tensors for more detail.
283
+ output_hidden_states (`bool`, *optional*):
284
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
285
+ more detail.
286
+ return_dict (`bool`, *optional*):
287
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
288
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
289
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
290
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
291
+ the complete sequence length.
292
+ """
293
+
294
+
295
+ @add_start_docstrings(
296
+ """The PALIGEMMA model which consists of a vision backbone and a language model.""",
297
+ PALIGEMMA_START_DOCSTRING,
298
+ )
299
+ class PaliGemmaForConditionalGeneration(PaliGemmaPreTrainedModel, GenerationMixin):
300
+ def __init__(self, config: PaliGemmaConfig):
301
+ super().__init__(config)
302
+ self.vision_tower = AutoModel.from_config(config=config.vision_config)
303
+ self.multi_modal_projector = PaliGemmaMultiModalProjector(config)
304
+ self.vocab_size = config.text_config.vocab_size
305
+
306
+ language_model = AutoModelForCausalLM.from_config(config=config.text_config)
307
+
308
+ if language_model._tied_weights_keys is not None:
309
+ self._tied_weights_keys = [f"language_model.{k}" for k in language_model._tied_weights_keys]
310
+ self.language_model = language_model
311
+
312
+ self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
313
+ self.post_init()
314
+
315
+ # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.get_input_embeddings with Llava->PaliGemma
316
+ def get_input_embeddings(self):
317
+ return self.language_model.get_input_embeddings()
318
+
319
+ # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.set_input_embeddings with Llava->PaliGemma
320
+ def set_input_embeddings(self, value):
321
+ self.language_model.set_input_embeddings(value)
322
+
323
+ # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.get_output_embeddings with Llava->PaliGemma
324
+ def get_output_embeddings(self):
325
+ return self.language_model.get_output_embeddings()
326
+
327
+ # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.set_output_embeddings with Llava->PaliGemma
328
+ def set_output_embeddings(self, new_embeddings):
329
+ self.language_model.set_output_embeddings(new_embeddings)
330
+
331
+ # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.set_decoder with Llava->PaliGemma
332
+ def set_decoder(self, decoder):
333
+ self.language_model.set_decoder(decoder)
334
+
335
+ # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.get_decoder with Llava->PaliGemma
336
+ def get_decoder(self):
337
+ return self.language_model.get_decoder()
338
+
339
+ # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.tie_weights with Llava->PaliGemma
340
+ def tie_weights(self):
341
+ return self.language_model.tie_weights()
342
+
343
+ def _update_causal_mask(
344
+ self,
345
+ attention_mask,
346
+ token_type_ids,
347
+ past_key_values,
348
+ cache_position,
349
+ input_ids=None,
350
+ inputs_embeds=None,
351
+ is_training: bool = False,
352
+ ):
353
+ if self.config.text_config._attn_implementation == "flash_attention_2":
354
+ if attention_mask is not None and 0.0 in attention_mask:
355
+ return attention_mask
356
+ return None
357
+
358
+ using_static_cache = isinstance(past_key_values, StaticCache)
359
+ min_dtype = torch.finfo(self.dtype).min
360
+ inputs_lead_dim = input_ids.shape[0] if input_ids is not None else inputs_embeds.shape[0]
361
+ sequence_length = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
362
+ if using_static_cache:
363
+ target_length = past_key_values.get_max_cache_shape()
364
+ elif isinstance(past_key_values, HybridCache):
365
+ target_length = past_key_values.get_max_cache_shape()
366
+ else:
367
+ target_length = (
368
+ attention_mask.shape[-1]
369
+ if isinstance(attention_mask, torch.Tensor)
370
+ else cache_position[0] + sequence_length + 1
371
+ )
372
+
373
+ if attention_mask is not None and attention_mask.dim() == 4:
374
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
375
+ return attention_mask
376
+
377
+ causal_mask = torch.full(
378
+ (sequence_length, target_length), fill_value=min_dtype, dtype=self.dtype, device=cache_position.device
379
+ )
380
+ # Causal diagonal mask only if training, otherwise attend to the whole prefix. Training-specific attn for prefix is handled below
381
+ if sequence_length != 1:
382
+ if is_training:
383
+ causal_mask = torch.triu(causal_mask, diagonal=1)
384
+ else:
385
+ causal_mask[:, :sequence_length] = 0.0
386
+
387
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
388
+ causal_mask = causal_mask[None, None, :, :].expand(inputs_lead_dim, 1, -1, -1)
389
+ if attention_mask is not None:
390
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
391
+ mask_length = attention_mask.shape[-1]
392
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(causal_mask.device)
393
+ padding_mask = padding_mask == 0
394
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
395
+ padding_mask, min_dtype
396
+ )
397
+ # we are training thus we need to create a full mask on the image + prefix but causal on suffix
398
+ if is_training:
399
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
400
+ token_type_ids[:, None, None, :].to(causal_mask.device) == 0, 0
401
+ )
402
+ return causal_mask
403
+
404
+ def get_image_features(self, pixel_values: torch.FloatTensor):
405
+ """
406
+ Obtains image last hidden states from the vision tower and apply multimodal projection.
407
+
408
+ Args:
409
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
410
+ The tensors corresponding to the input images.
411
+ Returns:
412
+ image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
413
+ """
414
+ image_outputs = self.vision_tower(pixel_values)
415
+ selected_image_feature = image_outputs.last_hidden_state
416
+ image_features = self.multi_modal_projector(selected_image_feature)
417
+ image_features = image_features / (self.config.text_config.hidden_size**0.5)
418
+ return image_features
419
+
420
+ @add_start_docstrings_to_model_forward(PALIGEMMA_INPUTS_DOCSTRING)
421
+ @replace_return_docstrings(output_type=PaliGemmaCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
422
+ def forward(
423
+ self,
424
+ input_ids: torch.LongTensor = None,
425
+ pixel_values: torch.FloatTensor = None,
426
+ attention_mask: Optional[torch.Tensor] = None,
427
+ position_ids: Optional[torch.LongTensor] = None,
428
+ past_key_values: Optional[Union[List[torch.FloatTensor], Cache]] = None,
429
+ token_type_ids: Optional[torch.LongTensor] = None,
430
+ cache_position: Optional[torch.LongTensor] = None,
431
+ inputs_embeds: Optional[torch.FloatTensor] = None,
432
+ labels: Optional[torch.LongTensor] = None,
433
+ use_cache: Optional[bool] = None,
434
+ output_attentions: Optional[bool] = None,
435
+ output_hidden_states: Optional[bool] = None,
436
+ return_dict: Optional[bool] = None,
437
+ num_logits_to_keep: int = 0,
438
+ ) -> Union[Tuple, PaliGemmaCausalLMOutputWithPast]:
439
+ r"""
440
+ Args:
441
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
442
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
443
+ config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
444
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
445
+
446
+ num_logits_to_keep (`int`, *optional*):
447
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
448
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
449
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
450
+
451
+ Returns:
452
+
453
+ Example:
454
+
455
+ ```python
456
+ >>> from PIL import Image
457
+ >>> import requests
458
+ >>> from transformers import AutoProcessor, PaliGemmaForConditionalGeneration
459
+
460
+ >>> model = PaliGemmaForConditionalGeneration.from_pretrained("google/PaliGemma-test-224px-hf")
461
+ >>> processor = AutoProcessor.from_pretrained("google/PaliGemma-test-224px-hf")
462
+
463
+ >>> prompt = "answer en Where is the cow standing?"
464
+ >>> url = "https://huggingface.co/gv-hf/PaliGemma-test-224px-hf/resolve/main/cow_beach_1.png"
465
+ >>> image = Image.open(requests.get(url, stream=True).raw)
466
+
467
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
468
+
469
+ >>> # Generate
470
+ >>> generate_ids = model.generate(**inputs, max_length=30)
471
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
472
+ "answer en Where is the cow standing?\nbeach"
473
+ ```"""
474
+
475
+ if (input_ids is None) ^ (inputs_embeds is not None):
476
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
477
+
478
+ if pixel_values is not None and inputs_embeds is not None:
479
+ raise ValueError(
480
+ "You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
481
+ )
482
+
483
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
484
+ output_hidden_states = (
485
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
486
+ )
487
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
488
+
489
+ is_training = token_type_ids is not None and labels is not None
490
+
491
+ if inputs_embeds is None:
492
+ inputs_embeds = self.get_input_embeddings()(input_ids)
493
+
494
+ if cache_position is None:
495
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
496
+ cache_position = torch.arange(
497
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
498
+ )
499
+
500
+ if position_ids is None:
501
+ position_ids = cache_position.unsqueeze(0) + 1 # Paligemma positions are 1-indexed
502
+
503
+ # Merge text and images
504
+ if pixel_values is not None:
505
+ image_features = self.get_image_features(pixel_values)
506
+
507
+ special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
508
+ special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
509
+ if inputs_embeds[special_image_mask].numel() != image_features.numel():
510
+ image_tokens_in_text = torch.sum(input_ids == self.config.image_token_index)
511
+ raise ValueError(
512
+ f"Number of images does not match number of special image tokens in the input text. "
513
+ f"Got {image_tokens_in_text} image tokens in the text but {image_features.shape[0] * image_features.shape[1]} "
514
+ "tokens from image embeddings."
515
+ )
516
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
517
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
518
+
519
+ # mask out pad-token-ids in labels for BC
520
+ if labels is not None and self.pad_token_id in labels:
521
+ logger.warning_once(
522
+ "`labels` contains `pad_token_id` which will be masked with `config.ignore_index`. "
523
+ "You have to mask out `pad_token_id` when preparing `labels`, this behavior will be removed in v.4.46.",
524
+ )
525
+ labels = torch.where(input_ids == self.pad_token_id, self.config.ignore_index, labels)
526
+
527
+ causal_mask = self._update_causal_mask(
528
+ attention_mask, token_type_ids, past_key_values, cache_position, input_ids, inputs_embeds, is_training
529
+ )
530
+ outputs = self.language_model(
531
+ attention_mask=causal_mask,
532
+ position_ids=position_ids,
533
+ past_key_values=past_key_values,
534
+ inputs_embeds=inputs_embeds,
535
+ use_cache=use_cache,
536
+ output_attentions=output_attentions,
537
+ output_hidden_states=output_hidden_states,
538
+ return_dict=return_dict,
539
+ cache_position=cache_position,
540
+ num_logits_to_keep=num_logits_to_keep,
541
+ )
542
+
543
+ logits = outputs.logits
544
+ loss = None
545
+ if labels is not None:
546
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
547
+ logits = logits.float()
548
+ shift_logits = logits[..., :-1, :]
549
+ shift_labels = labels[..., 1:]
550
+ if attention_mask is not None:
551
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
552
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
553
+ shift_attention_mask = attention_mask[:, -shift_logits.shape[1] :].to(logits.device)
554
+ shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
555
+ shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
556
+ else:
557
+ shift_logits = shift_logits.contiguous()
558
+ shift_labels = shift_labels.contiguous()
559
+ # Flatten the tokens
560
+ loss_fct = nn.CrossEntropyLoss()
561
+
562
+ flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
563
+ flat_labels = shift_labels.view(-1).to(shift_logits.device)
564
+ loss = loss_fct(flat_logits, flat_labels)
565
+ if not return_dict:
566
+ output = (logits,) + outputs[1:]
567
+ return (loss,) + output if loss is not None else output
568
+
569
+ return PaliGemmaCausalLMOutputWithPast(
570
+ loss=loss,
571
+ logits=logits,
572
+ past_key_values=outputs.past_key_values,
573
+ hidden_states=outputs.hidden_states,
574
+ attentions=outputs.attentions,
575
+ image_hidden_states=image_features if pixel_values is not None else None,
576
+ )
577
+
578
+ def prepare_inputs_for_generation(
579
+ self,
580
+ input_ids,
581
+ past_key_values=None,
582
+ inputs_embeds=None,
583
+ cache_position=None,
584
+ position_ids=None,
585
+ pixel_values=None,
586
+ attention_mask=None,
587
+ token_type_ids=None,
588
+ use_cache=True,
589
+ num_logits_to_keep=None,
590
+ labels=None,
591
+ **kwargs,
592
+ ):
593
+ # Overwritten -- custom `position_ids` and `pixel_values` handling
594
+ model_inputs = self.language_model.prepare_inputs_for_generation(
595
+ input_ids,
596
+ past_key_values=past_key_values,
597
+ inputs_embeds=inputs_embeds,
598
+ attention_mask=attention_mask,
599
+ position_ids=position_ids,
600
+ cache_position=cache_position,
601
+ use_cache=use_cache,
602
+ num_logits_to_keep=num_logits_to_keep,
603
+ token_type_ids=token_type_ids,
604
+ **kwargs,
605
+ )
606
+
607
+ # position_ids in Paligemma are 1-indexed
608
+ if model_inputs.get("position_ids") is not None:
609
+ model_inputs["position_ids"] += 1
610
+ # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
611
+ # Otherwise we need pixel values to be passed to model. NOTE: use_cache=False needs pixel_values always
612
+ if cache_position[0] == 0:
613
+ model_inputs["pixel_values"] = pixel_values
614
+ is_training = token_type_ids is not None and labels is not None
615
+ if cache_position[0] == 0 and isinstance(past_key_values, HybridCache):
616
+ causal_mask = self._update_causal_mask(
617
+ attention_mask, token_type_ids, past_key_values, cache_position, input_ids, inputs_embeds, is_training
618
+ )
619
+ model_inputs["attention_mask"] = causal_mask
620
+ return model_inputs
621
+
622
+
623
+ __all__ = ["PaliGemmaForConditionalGeneration", "PaliGemmaPreTrainedModel"]