ZTWHHH commited on
Commit
f4fb264
·
verified ·
1 Parent(s): 56f7f18

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. .gitattributes +1 -0
  2. vlmpy310/lib/python3.10/site-packages/transformers/models/bamba/__pycache__/__init__.cpython-310.pyc +0 -0
  3. vlmpy310/lib/python3.10/site-packages/transformers/models/bamba/__pycache__/convert_mamba_ssm_checkpoint.cpython-310.pyc +0 -0
  4. vlmpy310/lib/python3.10/site-packages/transformers/models/bamba/modeling_bamba.py +1611 -0
  5. vlmpy310/lib/python3.10/site-packages/transformers/models/clap/__init__.py +29 -0
  6. vlmpy310/lib/python3.10/site-packages/transformers/models/clap/__pycache__/__init__.cpython-310.pyc +0 -0
  7. vlmpy310/lib/python3.10/site-packages/transformers/models/clap/__pycache__/configuration_clap.cpython-310.pyc +0 -0
  8. vlmpy310/lib/python3.10/site-packages/transformers/models/clap/__pycache__/convert_clap_original_pytorch_to_hf.cpython-310.pyc +0 -0
  9. vlmpy310/lib/python3.10/site-packages/transformers/models/clap/__pycache__/feature_extraction_clap.cpython-310.pyc +0 -0
  10. vlmpy310/lib/python3.10/site-packages/transformers/models/clap/__pycache__/modeling_clap.cpython-310.pyc +0 -0
  11. vlmpy310/lib/python3.10/site-packages/transformers/models/clap/__pycache__/processing_clap.cpython-310.pyc +0 -0
  12. vlmpy310/lib/python3.10/site-packages/transformers/models/clap/configuration_clap.py +394 -0
  13. vlmpy310/lib/python3.10/site-packages/transformers/models/clap/convert_clap_original_pytorch_to_hf.py +133 -0
  14. vlmpy310/lib/python3.10/site-packages/transformers/models/clap/feature_extraction_clap.py +365 -0
  15. vlmpy310/lib/python3.10/site-packages/transformers/models/clap/modeling_clap.py +0 -0
  16. vlmpy310/lib/python3.10/site-packages/transformers/models/clap/processing_clap.py +120 -0
  17. vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/__init__.py +31 -0
  18. vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/__init__.cpython-310.pyc +0 -0
  19. vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/configuration_distilbert.cpython-310.pyc +0 -0
  20. vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/modeling_distilbert.cpython-310.pyc +0 -0
  21. vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/modeling_flax_distilbert.cpython-310.pyc +0 -0
  22. vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/modeling_tf_distilbert.cpython-310.pyc +0 -0
  23. vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/tokenization_distilbert.cpython-310.pyc +0 -0
  24. vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/tokenization_distilbert_fast.cpython-310.pyc +0 -0
  25. vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/configuration_distilbert.py +141 -0
  26. vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/modeling_distilbert.py +1378 -0
  27. vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/modeling_flax_distilbert.py +906 -0
  28. vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/modeling_tf_distilbert.py +1147 -0
  29. vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/tokenization_distilbert.py +522 -0
  30. vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/tokenization_distilbert_fast.py +179 -0
  31. vlmpy310/lib/python3.10/site-packages/transformers/models/levit/__init__.py +29 -0
  32. vlmpy310/lib/python3.10/site-packages/transformers/models/levit/configuration_levit.py +144 -0
  33. vlmpy310/lib/python3.10/site-packages/transformers/models/levit/convert_levit_timm_to_pytorch.py +180 -0
  34. vlmpy310/lib/python3.10/site-packages/transformers/models/levit/feature_extraction_levit.py +36 -0
  35. vlmpy310/lib/python3.10/site-packages/transformers/models/levit/image_processing_levit.py +309 -0
  36. vlmpy310/lib/python3.10/site-packages/transformers/models/levit/modeling_levit.py +743 -0
  37. vlmpy310/lib/python3.10/site-packages/transformers/models/olmoe/__pycache__/modeling_olmoe.cpython-310.pyc +0 -0
  38. vlmpy310/lib/python3.10/site-packages/transformers/models/olmoe/configuration_olmoe.py +182 -0
  39. vlmpy310/lib/python3.10/site-packages/transformers/models/rag/__init__.py +30 -0
  40. vlmpy310/lib/python3.10/site-packages/transformers/models/rag/configuration_rag.py +186 -0
  41. vlmpy310/lib/python3.10/site-packages/transformers/models/rag/modeling_rag.py +1644 -0
  42. vlmpy310/lib/python3.10/site-packages/transformers/models/rag/tokenization_rag.py +124 -0
  43. vlmpy310/lib/python3.10/site-packages/transformers/models/sam/__init__.py +30 -0
  44. vlmpy310/lib/python3.10/site-packages/transformers/models/sam/__pycache__/__init__.cpython-310.pyc +0 -0
  45. vlmpy310/lib/python3.10/site-packages/transformers/models/sam/__pycache__/convert_sam_to_hf.cpython-310.pyc +0 -0
  46. vlmpy310/lib/python3.10/site-packages/transformers/models/sam/__pycache__/image_processing_sam.cpython-310.pyc +0 -0
  47. vlmpy310/lib/python3.10/site-packages/transformers/models/sam/__pycache__/modeling_sam.cpython-310.pyc +0 -0
  48. vlmpy310/lib/python3.10/site-packages/transformers/models/sam/__pycache__/modeling_tf_sam.cpython-310.pyc +0 -0
  49. vlmpy310/lib/python3.10/site-packages/transformers/models/sam/configuration_sam.py +319 -0
  50. vlmpy310/lib/python3.10/site-packages/transformers/models/sam/image_processing_sam.py +1478 -0
.gitattributes CHANGED
@@ -1161,3 +1161,4 @@ llava_next/lib/python3.10/site-packages/torchvision/image.so filter=lfs diff=lfs
1161
  vlmpy310/lib/python3.10/site-packages/tokenizers/tokenizers.abi3.so filter=lfs diff=lfs merge=lfs -text
1162
  vlmpy310/lib/python3.10/site-packages/av.libs/libavformat-071c54bd.so.61.7.100 filter=lfs diff=lfs merge=lfs -text
1163
  vlmpy310/lib/python3.10/site-packages/transformers/models/oneformer/__pycache__/modeling_oneformer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
1161
  vlmpy310/lib/python3.10/site-packages/tokenizers/tokenizers.abi3.so filter=lfs diff=lfs merge=lfs -text
1162
  vlmpy310/lib/python3.10/site-packages/av.libs/libavformat-071c54bd.so.61.7.100 filter=lfs diff=lfs merge=lfs -text
1163
  vlmpy310/lib/python3.10/site-packages/transformers/models/oneformer/__pycache__/modeling_oneformer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1164
+ vlmpy310/lib/python3.10/site-packages/transformers/models/seamless_m4t/__pycache__/modeling_seamless_m4t.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
vlmpy310/lib/python3.10/site-packages/transformers/models/bamba/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (565 Bytes). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/bamba/__pycache__/convert_mamba_ssm_checkpoint.cpython-310.pyc ADDED
Binary file (6.64 kB). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/bamba/modeling_bamba.py ADDED
@@ -0,0 +1,1611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/bamba/modular_bamba.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_bamba.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2024 IBM and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
11
+ # and OPT implementations in this library. It has been modified from its
12
+ # original forms to accommodate minor architectural differences compared
13
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
14
+ #
15
+ # Licensed under the Apache License, Version 2.0 (the "License");
16
+ # you may not use this file except in compliance with the License.
17
+ # You may obtain a copy of the License at
18
+ #
19
+ # http://www.apache.org/licenses/LICENSE-2.0
20
+ #
21
+ # Unless required by applicable law or agreed to in writing, software
22
+ # distributed under the License is distributed on an "AS IS" BASIS,
23
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
+ # See the License for the specific language governing permissions and
25
+ # limitations under the License.
26
+
27
+ from typing import Callable, Optional, Tuple, Union
28
+
29
+ import torch
30
+ from torch import nn
31
+
32
+ import transformers.models.jamba.modeling_jamba as modeling_jamba
33
+ from transformers.activations import ACT2FN
34
+
35
+ from ...cache_utils import Cache # we need __iter__ and __len__ of pkv
36
+ from ...generation import GenerationMixin
37
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
38
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
39
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
40
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS
41
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
42
+ from ...processing_utils import Unpack
43
+ from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
44
+ from ...utils.import_utils import (
45
+ is_causal_conv1d_available,
46
+ is_mamba_2_ssm_available,
47
+ )
48
+ from .configuration_bamba import BambaConfig
49
+
50
+
51
+ if is_mamba_2_ssm_available():
52
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
53
+ from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
54
+ else:
55
+ selective_state_update = None
56
+
57
+ if is_causal_conv1d_available():
58
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
59
+ else:
60
+ causal_conv1d_update, causal_conv1d_fn = None, None
61
+
62
+
63
+ logger = logging.get_logger(__name__)
64
+ _CONFIG_FOR_DOC = "BambaConfig"
65
+
66
+
67
+ # Adapted from transformers.models.jamba.modeling_jamba.HybridMambaAttentionDynamicCache for the v2 mixer
68
+ class HybridMambaAttentionDynamicCache(modeling_jamba.HybridMambaAttentionDynamicCache):
69
+ """
70
+ A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
71
+ (which has a constant shape regardless of seq_len).
72
+
73
+ This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
74
+ and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
75
+ For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
76
+ while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
77
+ For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
78
+ while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
79
+ and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
80
+ """
81
+
82
+ def __init__(self, config: BambaConfig, batch_size, dtype=torch.float16, device=None):
83
+ super().__init__(config, batch_size, dtype, device)
84
+ self.layers_block_type = config.layers_block_type
85
+ self.has_previous_state = False # only used by mamba
86
+ conv_kernel_size = config.mamba_d_conv
87
+ ssm_state_size = config.mamba_d_state
88
+
89
+ self.conv_states = []
90
+ self.ssm_states = []
91
+ self.transformer_layers = []
92
+ for i in range(config.num_hidden_layers):
93
+ if self.layers_block_type[i] == "mamba":
94
+ self.conv_states += [
95
+ torch.zeros(
96
+ batch_size,
97
+ (config.mamba_expand * config.hidden_size + 2 * config.mamba_n_groups * ssm_state_size),
98
+ conv_kernel_size,
99
+ device=device,
100
+ dtype=dtype,
101
+ )
102
+ ]
103
+ self.ssm_states += [
104
+ torch.zeros(
105
+ batch_size,
106
+ config.mamba_n_heads,
107
+ config.mamba_d_head,
108
+ ssm_state_size,
109
+ device=device,
110
+ dtype=dtype,
111
+ )
112
+ ]
113
+ else:
114
+ self.conv_states += [torch.tensor([[]] * batch_size, device=device)]
115
+ self.ssm_states += [torch.tensor([[]] * batch_size, device=device)]
116
+ self.transformer_layers.append(i)
117
+
118
+ self.key_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
119
+ self.value_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
120
+
121
+
122
+ class BambaRotaryEmbedding(nn.Module):
123
+ def __init__(self, config: BambaConfig, device=None):
124
+ super().__init__()
125
+ # BC: "rope_type" was originally "type"
126
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
127
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
128
+ else:
129
+ self.rope_type = "default"
130
+ self.max_seq_len_cached = config.max_position_embeddings
131
+ self.original_max_seq_len = config.max_position_embeddings
132
+
133
+ self.config = config
134
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
135
+
136
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
137
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
138
+ self.original_inv_freq = self.inv_freq
139
+
140
+ def _dynamic_frequency_update(self, position_ids, device):
141
+ """
142
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
143
+ 1 - growing beyond the cached sequence length (allow scaling)
144
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
145
+ """
146
+ seq_len = torch.max(position_ids) + 1
147
+ if seq_len > self.max_seq_len_cached: # growth
148
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
149
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
150
+ self.max_seq_len_cached = seq_len
151
+
152
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
153
+ # This .to() is needed if the model has been moved to a device after being initialized (because
154
+ # the buffer is automatically moved, but not the original copy)
155
+ self.original_inv_freq = self.original_inv_freq.to(device)
156
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
157
+ self.max_seq_len_cached = self.original_max_seq_len
158
+
159
+ @torch.no_grad()
160
+ def forward(self, x, position_ids):
161
+ if "dynamic" in self.rope_type:
162
+ self._dynamic_frequency_update(position_ids, device=x.device)
163
+
164
+ # Core RoPE block
165
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
166
+ position_ids_expanded = position_ids[:, None, :].float()
167
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
168
+ device_type = x.device.type
169
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
170
+ with torch.autocast(device_type=device_type, enabled=False):
171
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
172
+ emb = torch.cat((freqs, freqs), dim=-1)
173
+ cos = emb.cos()
174
+ sin = emb.sin()
175
+
176
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
177
+ cos = cos * self.attention_scaling
178
+ sin = sin * self.attention_scaling
179
+
180
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
181
+
182
+
183
+ def rotate_half(x):
184
+ """Rotates half the hidden dims of the input."""
185
+ x1 = x[..., : x.shape[-1] // 2]
186
+ x2 = x[..., x.shape[-1] // 2 :]
187
+ return torch.cat((-x2, x1), dim=-1)
188
+
189
+
190
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
191
+ """
192
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
193
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
194
+ """
195
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
196
+ if n_rep == 1:
197
+ return hidden_states
198
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
199
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
200
+
201
+
202
+ def eager_attention_forward(
203
+ module: nn.Module,
204
+ query: torch.Tensor,
205
+ key: torch.Tensor,
206
+ value: torch.Tensor,
207
+ attention_mask: Optional[torch.Tensor],
208
+ scaling: float,
209
+ dropout: float = 0.0,
210
+ **kwargs,
211
+ ):
212
+ key_states = repeat_kv(key, module.num_key_value_groups)
213
+ value_states = repeat_kv(value, module.num_key_value_groups)
214
+
215
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
216
+ if attention_mask is not None:
217
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
218
+ attn_weights = attn_weights + causal_mask
219
+
220
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
221
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
222
+ attn_output = torch.matmul(attn_weights, value_states)
223
+ attn_output = attn_output.transpose(1, 2).contiguous()
224
+
225
+ return attn_output, attn_weights
226
+
227
+
228
+ # Adapted from transformers.models.glm.modular_glm.apply_rotary_pos_emb
229
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
230
+ """Applies Rotary Position Embedding to the query and key tensors.
231
+
232
+ Removes the interleaving of cos and sin from GLM
233
+
234
+ Args:
235
+ q (`torch.Tensor`): The query tensor.
236
+ k (`torch.Tensor`): The key tensor.
237
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
238
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
239
+ position_ids (`torch.Tensor`, *optional*):
240
+ Deprecated and unused.
241
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
242
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
243
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
244
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
245
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
246
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
247
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
248
+ Returns:
249
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
250
+ """
251
+ cos = cos.unsqueeze(unsqueeze_dim)
252
+ sin = sin.unsqueeze(unsqueeze_dim)
253
+
254
+ # Keep half or full tensor for later concatenation
255
+ rotary_dim = cos.shape[-1]
256
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
257
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
258
+
259
+ # Apply rotary embeddings on the first half or full tensor
260
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
261
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
262
+
263
+ # Concatenate back to full shape
264
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
265
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
266
+ return q_embed, k_embed
267
+
268
+
269
+ class BambaAttention(nn.Module):
270
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
271
+
272
+ def __init__(self, config: BambaConfig, layer_idx: int):
273
+ super().__init__()
274
+ self.config = config
275
+ self.layer_idx = layer_idx
276
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
277
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
278
+ self.scaling = self.head_dim**-0.5
279
+ self.attention_dropout = config.attention_dropout
280
+ self.is_causal = True
281
+
282
+ self.q_proj = nn.Linear(
283
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
284
+ )
285
+ self.k_proj = nn.Linear(
286
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
287
+ )
288
+ self.v_proj = nn.Linear(
289
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
290
+ )
291
+ self.o_proj = nn.Linear(
292
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
293
+ )
294
+
295
+ def forward(
296
+ self,
297
+ hidden_states: torch.Tensor,
298
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
299
+ attention_mask: Optional[torch.Tensor],
300
+ past_key_value: Optional[Cache] = None,
301
+ cache_position: Optional[torch.LongTensor] = None,
302
+ **kwargs: Unpack[FlashAttentionKwargs],
303
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
304
+ input_shape = hidden_states.shape[:-1]
305
+ hidden_shape = (*input_shape, -1, self.head_dim)
306
+
307
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
308
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
309
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
310
+
311
+ cos, sin = position_embeddings
312
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
313
+
314
+ if past_key_value is not None:
315
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
316
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
317
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
318
+
319
+ attention_interface: Callable = eager_attention_forward
320
+ if self.config._attn_implementation != "eager":
321
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
322
+ logger.warning_once(
323
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
324
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
325
+ )
326
+ else:
327
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
328
+
329
+ attn_output, attn_weights = attention_interface(
330
+ self,
331
+ query_states,
332
+ key_states,
333
+ value_states,
334
+ attention_mask,
335
+ dropout=0.0 if not self.training else self.attention_dropout,
336
+ scaling=self.scaling,
337
+ **kwargs,
338
+ )
339
+
340
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
341
+ attn_output = self.o_proj(attn_output)
342
+ return attn_output, attn_weights
343
+
344
+
345
+ class BambaRMSNormGated(torch.nn.Module):
346
+ def __init__(self, hidden_size, eps=1e-6):
347
+ super().__init__()
348
+ self.weight = nn.Parameter(torch.ones(hidden_size))
349
+ self.variance_epsilon = eps
350
+
351
+ def forward(self, hidden_states, gate=None):
352
+ input_dtype = hidden_states.dtype
353
+ hidden_states = hidden_states.to(torch.float32)
354
+
355
+ if gate is not None:
356
+ hidden_states = hidden_states * nn.functional.silu(gate.to(torch.float32))
357
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
358
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
359
+
360
+ return self.weight * hidden_states.to(input_dtype)
361
+
362
+
363
+ # Helper methods for segment sum computation
364
+
365
+
366
+ def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
367
+ """
368
+ Padding x tensor with `pad_size` on the seq_len dim (dim=1)
369
+
370
+ Assumes that we only have tensors of either size 4 or 3
371
+ """
372
+ pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(input_tensor.shape) == 4 else (0, 0, 0, pad_size, 0, 0)
373
+
374
+ return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
375
+
376
+
377
+ def reshape_into_chunks(input_tensor, pad_size, chunk_size):
378
+ """
379
+ Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
380
+ simultaneously splitting it into chunk sequences.
381
+
382
+ Assumes that we only have tensors of either size 4 or 3
383
+ """
384
+ # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
385
+ input_tensor = pad_tensor_by_size(input_tensor, pad_size)
386
+
387
+ if len(input_tensor.shape) == 3:
388
+ # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
389
+ return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
390
+ else:
391
+ # [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] -> [bsz, -1, chunk_size, num_heads, head_dim or state_size]
392
+ return input_tensor.reshape(
393
+ input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
394
+ )
395
+
396
+
397
+ def segment_sum(input_tensor):
398
+ """
399
+ More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
400
+ """
401
+ chunk_size = input_tensor.size(-1)
402
+ # 1. expand input tensor to have an additional dimension and repeat along that dimension
403
+ # [..., chunk_size] -> [..., chunk_size, chunk_size]
404
+ input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
405
+ # 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
406
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
407
+ input_tensor = input_tensor.masked_fill(~mask, 0)
408
+ # 3. compute actual cumsum
409
+ tensor_segsum = torch.cumsum(input_tensor, dim=-2)
410
+
411
+ # 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
412
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
413
+ tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
414
+ return tensor_segsum
415
+
416
+
417
+ is_fast_path_available = all((selective_state_update, causal_conv1d_fn, causal_conv1d_update))
418
+
419
+
420
+ def apply_mask_to_padding_states(hidden_states, attention_mask):
421
+ """
422
+ Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
423
+ """
424
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
425
+ dtype = hidden_states.dtype
426
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
427
+
428
+ return hidden_states
429
+
430
+
431
+ # Adapted from transformers.models.mamba2.modeling_mamba2.Mamba2Mixer
432
+ class BambaMixer(nn.Module):
433
+ """
434
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
435
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
436
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
437
+ and is why Mamba is called **selective** state spaces)
438
+
439
+ The are a few differences between this and Mamba2Mixer:
440
+ - The variable use_precomputed_states is slightly different due to the HybridCache structure
441
+ - There's a few non-obvious bugs fixed with batching in the slow path that exist in main
442
+ - Some extra variables that our layer doesn't need have been removed
443
+ - We ported most of the refactors in https://github.com/huggingface/transformers/pull/35154, which is (as of Dec 18, 2024) unmerged
444
+ """
445
+
446
+ def __init__(self, config: BambaConfig, layer_idx: int):
447
+ super().__init__()
448
+ self.num_heads = config.mamba_n_heads
449
+ self.hidden_size = config.hidden_size
450
+ self.ssm_state_size = config.mamba_d_state
451
+ self.conv_kernel_size = config.mamba_d_conv
452
+ self.intermediate_size = int(config.mamba_expand * self.hidden_size)
453
+ self.layer_idx = layer_idx
454
+ self.use_conv_bias = config.mamba_conv_bias
455
+ self.activation = config.hidden_act
456
+ self.act = ACT2FN[config.hidden_act]
457
+ self.use_bias = config.mamba_proj_bias
458
+
459
+ self.layer_norm_epsilon = config.rms_norm_eps
460
+
461
+ self.n_groups = config.mamba_n_groups
462
+ self.head_dim = config.mamba_d_head
463
+ self.chunk_size = config.mamba_chunk_size
464
+
465
+ # FIXME:
466
+ self.time_step_limit = (0.0, float("inf"))
467
+ self.time_step_min = 0.001
468
+ self.time_step_max = 0.1
469
+
470
+ self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
471
+ self.conv1d = nn.Conv1d(
472
+ in_channels=self.conv_dim,
473
+ out_channels=self.conv_dim,
474
+ bias=config.mamba_conv_bias,
475
+ kernel_size=self.conv_kernel_size,
476
+ groups=self.conv_dim,
477
+ padding=self.conv_kernel_size - 1,
478
+ )
479
+
480
+ # projection of the input hidden states
481
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
482
+ self.in_proj = nn.Linear(
483
+ self.hidden_size,
484
+ projection_size,
485
+ bias=self.use_bias,
486
+ )
487
+ # selective projection used to make dt, B and C input dependant
488
+
489
+ # time step projection (discretization)
490
+ # instantiate once and copy inv_dt in init_weights of PretrainedModel
491
+ self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
492
+
493
+ # S4D real initialization. These are not discretized!
494
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
495
+ A = torch.arange(1, self.num_heads + 1)
496
+ self.A_log = nn.Parameter(torch.log(A))
497
+ self.A_log._no_weight_decay = True
498
+ self.norm = BambaRMSNormGated(self.intermediate_size, eps=self.layer_norm_epsilon)
499
+ self.D = nn.Parameter(torch.ones(self.num_heads))
500
+ self.D._no_weight_decay = True
501
+
502
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=self.use_bias)
503
+
504
+ if not is_fast_path_available:
505
+ logger.warning_once(
506
+ "The fast path is not available because on of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
507
+ " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
508
+ " https://github.com/Dao-AILab/causal-conv1d"
509
+ )
510
+ else:
511
+ logger.warning_once("The fast path for Bamba will be used when running the model on a GPU")
512
+
513
+ def cuda_kernels_forward(
514
+ self,
515
+ hidden_states: torch.Tensor,
516
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
517
+ cache_position: Optional[torch.LongTensor] = None,
518
+ attention_mask: Optional[torch.Tensor] = None,
519
+ ):
520
+ # 1. Gated MLP's linear projection
521
+ hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
522
+ projected_states = self.in_proj(hidden_states)
523
+
524
+ # Set up dimensions for reshapes later
525
+ batch_size, seq_len, _ = hidden_states.shape
526
+ groups_time_state_size = self.n_groups * self.ssm_state_size
527
+
528
+ use_precomputed_states = (
529
+ cache_params is not None
530
+ and cache_params.has_previous_state
531
+ and seq_len == 1
532
+ and cache_params.conv_states[self.layer_idx].shape[0]
533
+ == cache_params.ssm_states[self.layer_idx].shape[0]
534
+ == batch_size
535
+ and cache_position is not None
536
+ and cache_position[0] > 0
537
+ )
538
+
539
+ # getting projected states from cache if it exists
540
+ if use_precomputed_states:
541
+ gate, hidden_states_B_C, dt = projected_states.squeeze(1).split(
542
+ [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
543
+ )
544
+
545
+ # 2. Convolution sequence transformation
546
+ hidden_states_B_C = causal_conv1d_update(
547
+ hidden_states_B_C,
548
+ cache_params.conv_states[self.layer_idx],
549
+ self.conv1d.weight.squeeze(1),
550
+ self.conv1d.bias,
551
+ self.activation,
552
+ )
553
+
554
+ hidden_states, B, C = torch.split(
555
+ hidden_states_B_C,
556
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
557
+ dim=-1,
558
+ )
559
+
560
+ # 3. SSM transformation
561
+ A = -torch.exp(self.A_log.float()) # (nheads,)
562
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
563
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
564
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
565
+ D = self.D[:, None, ...].expand(-1, self.head_dim)
566
+ B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
567
+ C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
568
+ hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
569
+ hidden_states = selective_state_update(
570
+ cache_params.ssm_states[self.layer_idx],
571
+ hidden_states_reshaped,
572
+ dt,
573
+ A,
574
+ B,
575
+ C,
576
+ D,
577
+ z=None,
578
+ dt_bias=dt_bias,
579
+ dt_softplus=True,
580
+ )
581
+ hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
582
+ hidden_states = self.norm(hidden_states, gate)
583
+
584
+ # 4. Final linear projection
585
+ out = self.out_proj(hidden_states)[:, None, ...]
586
+ # Fused calculations or step by step if no initialized cache is found
587
+ else:
588
+ A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
589
+ dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit}
590
+
591
+ # 2-4. Fused kernel for conv1d, SSM, and the final projection
592
+ if self.training and cache_params is None:
593
+ out = mamba_split_conv1d_scan_combined(
594
+ projected_states,
595
+ self.conv1d.weight.squeeze(1),
596
+ self.conv1d.bias,
597
+ self.dt_bias,
598
+ A,
599
+ D=self.D,
600
+ chunk_size=self.chunk_size,
601
+ seq_idx=None, # was seq_idx
602
+ activation=self.activation,
603
+ rmsnorm_weight=self.norm.weight,
604
+ rmsnorm_eps=self.norm.variance_epsilon,
605
+ outproj_weight=self.out_proj.weight,
606
+ outproj_bias=self.out_proj.bias,
607
+ headdim=self.head_dim,
608
+ ngroups=self.n_groups,
609
+ norm_before_gate=False,
610
+ return_final_states=False,
611
+ **dt_limit_kwargs,
612
+ )
613
+
614
+ else:
615
+ gate, hidden_states_B_C, dt = projected_states.split(
616
+ [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
617
+ )
618
+
619
+ # 2. Convolution sequence transformation
620
+ # Init cache
621
+ if cache_params is not None:
622
+ # storing the states
623
+ # If we just take xBC[:, :, -self.d_conv :], it will error if seqlen < self.d_conv
624
+ # Instead F.pad will pad with zeros if seqlen < self.d_conv, and truncate otherwise.
625
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
626
+ conv_states = nn.functional.pad(
627
+ hidden_states_B_C_transposed,
628
+ (self.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0),
629
+ )
630
+ cache_params.conv_states[self.layer_idx].copy_(conv_states)
631
+
632
+ if self.activation not in ["silu", "swish"]:
633
+ hidden_states_B_C = self.act(
634
+ self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2)
635
+ )
636
+ else:
637
+ hidden_states_B_C = causal_conv1d_fn(
638
+ x=hidden_states_B_C.transpose(1, 2),
639
+ weight=self.conv1d.weight.squeeze(1),
640
+ bias=self.conv1d.bias,
641
+ activation=self.activation,
642
+ ).transpose(1, 2)
643
+
644
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
645
+ hidden_states, B, C = torch.split(
646
+ hidden_states_B_C,
647
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
648
+ dim=-1,
649
+ )
650
+
651
+ # 3. SSM transformation
652
+ scan_output, ssm_state = mamba_chunk_scan_combined(
653
+ hidden_states.view(batch_size, seq_len, -1, self.head_dim),
654
+ dt,
655
+ A,
656
+ B.view(batch_size, seq_len, self.n_groups, -1),
657
+ C.view(batch_size, seq_len, self.n_groups, -1),
658
+ chunk_size=self.chunk_size,
659
+ D=self.D,
660
+ z=None,
661
+ seq_idx=None,
662
+ return_final_states=True,
663
+ dt_bias=self.dt_bias,
664
+ dt_softplus=True,
665
+ **dt_limit_kwargs,
666
+ )
667
+
668
+ # Init cache
669
+ if ssm_state is not None and cache_params is not None:
670
+ cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
671
+
672
+ scan_output = scan_output.view(batch_size, seq_len, -1)
673
+ # Multiply "gate" branch and apply extra normalization layer
674
+ scan_output = self.norm(scan_output, gate)
675
+
676
+ # 4. Final linear projection
677
+ out = self.out_proj(scan_output)
678
+ return out
679
+
680
+ # fmt: off
681
+ def torch_forward(
682
+ self,
683
+ input_states,
684
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
685
+ cache_position: Optional[torch.LongTensor] = None,
686
+ attention_mask: Optional[torch.Tensor] = None,
687
+ ):
688
+ batch_size, seq_len, _ = input_states.shape
689
+ dtype = input_states.dtype
690
+
691
+ # 1. Gated MLP's linear projection
692
+ input_states = apply_mask_to_padding_states(input_states, attention_mask)
693
+ projected_states = self.in_proj(input_states)
694
+ gate, hidden_states_B_C, dt = projected_states.split(
695
+ [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
696
+ )
697
+
698
+ use_precomputed_states = (
699
+ cache_params is not None
700
+ and cache_params.has_previous_state
701
+ and seq_len == 1
702
+ and cache_params.conv_states[self.layer_idx].shape[0]
703
+ == cache_params.ssm_states[self.layer_idx].shape[0]
704
+ == batch_size
705
+ and cache_position is not None
706
+ and cache_position[0] > 0
707
+ )
708
+
709
+ # 2. Convolution sequence transformation
710
+ if use_precomputed_states:
711
+ cache_params.conv_states[self.layer_idx] = cache_params.conv_states[self.layer_idx].roll(shifts=-1, dims=-1)
712
+ cache_params.conv_states[self.layer_idx][:, :, -1] = hidden_states_B_C[:, 0, :].to(cache_params.conv_states[self.layer_idx].device)
713
+
714
+ # We need to guarantee that anything regarding the cache is on the same device
715
+ conv_states = cache_params.conv_states[self.layer_idx].to(device=self.conv1d.weight.device)
716
+
717
+ hidden_states_B_C = torch.sum(
718
+ conv_states * self.conv1d.weight.squeeze(1), dim=-1
719
+ )
720
+ if self.use_conv_bias:
721
+ hidden_states_B_C = hidden_states_B_C + self.conv1d.bias
722
+ hidden_states_B_C = self.act(hidden_states_B_C)
723
+ else:
724
+ # Init cache
725
+ if cache_params is not None:
726
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
727
+ conv_states = nn.functional.pad(
728
+ hidden_states_B_C_transposed, (self.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0)
729
+ )
730
+ cache_params.conv_states[self.layer_idx].copy_(conv_states)
731
+
732
+ hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2))
733
+
734
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
735
+ hidden_states, B, C = torch.split(
736
+ hidden_states_B_C,
737
+ [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size],
738
+ dim=-1
739
+ )
740
+
741
+ # 3. SSM transformation
742
+ A = -torch.exp(self.A_log.float()) # [num_heads]
743
+ if use_precomputed_states:
744
+ # We need to guarantee that anything regarding the cache is on the same device
745
+ cache_device = cache_params.ssm_states[self.layer_idx].device
746
+
747
+ # Note: there is no need to pad parameter matrices here, as there is just one new token
748
+ # for batched generation
749
+ dt = dt[:, 0, :][:, None, ...]
750
+ dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
751
+ # [num_heads] -> [num_heads, head_dim]
752
+ dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
753
+
754
+ dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
755
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
756
+ A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
757
+ # [bsz, num_heads, head_dim, state_size]
758
+ dA = (torch.exp(dt[..., None] * A)).to(device=cache_device)
759
+
760
+ # Discretize B
761
+ # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
762
+ # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
763
+ B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
764
+ B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
765
+ B = B.reshape(batch_size, -1, B.shape[-1])
766
+ # [bsz, num_heads, head_dim, state_size]
767
+ dB = dt[..., None] * B[..., None, :]
768
+
769
+ # Discretize x into dB
770
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
771
+ hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
772
+ dBx = (dB * hidden_states[..., None]).to(device=cache_device)
773
+
774
+ # State calculation
775
+ cache_params.ssm_states[self.layer_idx].copy_(
776
+ cache_params.ssm_states[self.layer_idx] * dA + dBx
777
+ )
778
+
779
+ # Subsequent output
780
+ # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
781
+ C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
782
+ C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
783
+ C = C.reshape(batch_size, -1, C.shape[-1])
784
+ # [bsz, num_heads, head_dim]
785
+
786
+ ssm_states = cache_params.ssm_states[self.layer_idx].to(device=C.device, dtype=C.dtype) # Shape: [b, h, d, n]
787
+ # Reshape ssm_states to merge the first two dimensions
788
+ ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
789
+ C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
790
+ y = torch.bmm(ssm_states_reshaped, C_reshaped)
791
+ y = y.view(batch_size, self.num_heads, self.head_dim)
792
+
793
+ # D skip connection
794
+ # [num_heads] -> [num_heads, head_dim]
795
+ D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
796
+ y = (y + hidden_states * D).to(y.dtype)
797
+
798
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
799
+ y = y.reshape(batch_size, -1)[:, None, ...]
800
+ else:
801
+ # begin ssd naive implementation without einsums
802
+ dt = nn.functional.softplus(dt + self.dt_bias)
803
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
804
+ hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
805
+ B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
806
+ C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
807
+ B = B.repeat(1, 1, self.num_heads // self.n_groups, 1)
808
+ C = C.repeat(1, 1, self.num_heads // self.n_groups, 1)
809
+ pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
810
+
811
+ D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
812
+
813
+ # Discretize x and A
814
+ hidden_states = hidden_states * dt[..., None]
815
+ A = A.to(hidden_states.dtype) * dt
816
+
817
+ # Rearrange into blocks/chunks
818
+ hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
819
+
820
+ # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
821
+ A = A.permute(0, 3, 1, 2)
822
+ A_cumsum = torch.cumsum(A, dim=-1)
823
+
824
+ # 1. Compute the output for each intra-chunk (diagonal blocks)
825
+ # This is the analog of a causal mask
826
+ L = torch.exp(segment_sum(A))
827
+
828
+ # Contraction of C and B to get G (attention-weights like)
829
+ G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :] # shape: (b, c, l, s, h, n)
830
+ G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
831
+
832
+ # Compute M, equivalent to applying attention mask to weights
833
+ M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
834
+ M = M_intermediate.sum(dim=-1)
835
+
836
+ # Compute Y_diag (apply to values)
837
+ Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3)
838
+
839
+ # 2. Compute the state for each intra-chunk
840
+ # (right term of low-rank factorization of off-diagonal blocks; B terms)
841
+ decay_states = torch.exp((A_cumsum[:, :, :, -1:] - A_cumsum))
842
+ B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None]
843
+ states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2)
844
+
845
+ # 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries
846
+ # (middle term of factorization of off-diag blocks; A terms)
847
+ if use_precomputed_states:
848
+ previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...].to(device=states.device)
849
+ else:
850
+ previous_states = torch.zeros_like(states[:, :1])
851
+ states = torch.cat([previous_states, states], dim=1)
852
+ decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
853
+ decay_chunk = decay_chunk.transpose(1, 3)
854
+ new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1)
855
+ states, ssm_state = new_states[:, :-1], new_states[:, -1]
856
+
857
+ # 4. Compute state -> output conversion per chunk
858
+ # (left term of low-rank factorization of off-diagonal blocks; C terms)
859
+ state_decay_out = torch.exp(A_cumsum)
860
+ C_times_states = (C[..., None, :] * states[:, :, None, ...])
861
+ state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
862
+ Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
863
+
864
+ # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
865
+ y = Y_diag + Y_off
866
+ # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
867
+ y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
868
+
869
+ y = y + D_residual
870
+ # Cutting off padded chunks
871
+ if pad_size > 0:
872
+ y = y[:, :seq_len, :, :]
873
+ y = y.reshape(batch_size, seq_len, -1)
874
+
875
+ # Init cache
876
+ if ssm_state is not None and cache_params is not None:
877
+ cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
878
+
879
+ scan_output = self.norm(y, gate)
880
+
881
+ # end ssd naive
882
+
883
+ # 4. Final linear projection
884
+ contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
885
+ return contextualized_states
886
+ # fmt: on
887
+
888
+ def forward(
889
+ self,
890
+ hidden_states,
891
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
892
+ cache_position: Optional[torch.LongTensor] = None,
893
+ attention_mask: Optional[torch.Tensor] = None,
894
+ ):
895
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type:
896
+ return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask)
897
+ dtype = hidden_states.dtype
898
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
899
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
900
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
901
+
902
+ return self.torch_forward(hidden_states, cache_params, cache_position, attention_mask)
903
+
904
+
905
+ class BambaMLP(nn.Module):
906
+ def __init__(self, config):
907
+ super().__init__()
908
+ self.config = config
909
+ self.hidden_size = config.hidden_size
910
+ self.intermediate_size = config.intermediate_size
911
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
912
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
913
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
914
+ self.act_fn = ACT2FN[config.hidden_act]
915
+
916
+ def forward(self, x):
917
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
918
+ return down_proj
919
+
920
+
921
+ class BambaRMSNorm(nn.Module):
922
+ def __init__(self, hidden_size, eps=1e-6):
923
+ """
924
+ BambaRMSNorm is equivalent to T5LayerNorm
925
+ """
926
+ super().__init__()
927
+ self.weight = nn.Parameter(torch.ones(hidden_size))
928
+ self.variance_epsilon = eps
929
+
930
+ def forward(self, hidden_states):
931
+ input_dtype = hidden_states.dtype
932
+ hidden_states = hidden_states.to(torch.float32)
933
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
934
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
935
+ return self.weight * hidden_states.to(input_dtype)
936
+
937
+ def extra_repr(self):
938
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
939
+
940
+
941
+ class BambaDecoderLayer(nn.Module):
942
+ def __init__(self, config: BambaConfig, layer_idx: int, layer_type: str = "mamba"):
943
+ super().__init__()
944
+
945
+ num_experts = 1
946
+ ffn_layer_class = BambaMLP if num_experts == 1 else None
947
+ self.feed_forward = ffn_layer_class(config)
948
+ self.input_layernorm = BambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
949
+ self.pre_ff_layernorm = BambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
950
+
951
+ self.layer_type = layer_type
952
+ if layer_type == "mamba":
953
+ self.mamba = BambaMixer(config=config, layer_idx=layer_idx)
954
+ elif layer_type == "attention":
955
+ self.self_attn = BambaAttention(config, layer_idx)
956
+ else:
957
+ raise ValueError("Invalid layer_type")
958
+
959
+ def forward(
960
+ self,
961
+ hidden_states: torch.Tensor,
962
+ attention_mask: Optional[torch.Tensor] = None,
963
+ position_ids: Optional[torch.LongTensor] = None,
964
+ past_key_value: Optional[HybridMambaAttentionDynamicCache] = None,
965
+ output_attentions: Optional[bool] = False,
966
+ use_cache: Optional[bool] = False,
967
+ cache_position: Optional[torch.LongTensor] = None,
968
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
969
+ **kwargs,
970
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
971
+ """
972
+ Args:
973
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
974
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
975
+ `(batch, sequence_length)` where padding elements are indicated by 0.
976
+ past_key_value (`HybridMambaAttentionDynamicCache`, *optional*): cached past key and value projection states
977
+ output_attentions (`bool`, *optional*):
978
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
979
+ returned tensors for more detail.
980
+ use_cache (`bool`, *optional*):
981
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
982
+ (see `past_key_values`).
983
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
984
+ Indices depicting the position of the input sequence tokens in the sequence.
985
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
986
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
987
+ with `head_dim` being the embedding dimension of each attention head.
988
+ kwargs (`dict`, *optional*):
989
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
990
+ into the model
991
+ """
992
+
993
+ residual = hidden_states
994
+
995
+ hidden_states = self.input_layernorm(hidden_states)
996
+
997
+ # this is a hybrid decoder layer
998
+ if self.layer_type == "mamba":
999
+ hidden_states = self.mamba(
1000
+ hidden_states=hidden_states,
1001
+ cache_params=past_key_value,
1002
+ cache_position=cache_position,
1003
+ attention_mask=attention_mask,
1004
+ )
1005
+ self_attn_weights = None
1006
+ elif self.layer_type == "attention":
1007
+ hidden_states, self_attn_weights = self.self_attn(
1008
+ hidden_states=hidden_states,
1009
+ attention_mask=attention_mask,
1010
+ position_ids=position_ids,
1011
+ past_key_value=past_key_value,
1012
+ output_attentions=output_attentions,
1013
+ use_cache=use_cache,
1014
+ cache_position=cache_position,
1015
+ position_embeddings=position_embeddings,
1016
+ **kwargs,
1017
+ )
1018
+
1019
+ # residual connection after attention
1020
+ hidden_states = residual + hidden_states
1021
+
1022
+ # feed-forward
1023
+ residual = hidden_states
1024
+ hidden_states = self.pre_ff_layernorm(hidden_states)
1025
+ hidden_states = self.feed_forward(hidden_states)
1026
+ hidden_states = residual + hidden_states
1027
+
1028
+ outputs = (hidden_states,)
1029
+
1030
+ if output_attentions:
1031
+ outputs += (self_attn_weights,)
1032
+
1033
+ return outputs
1034
+
1035
+
1036
+ BAMBA_START_DOCSTRING = r"""
1037
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1038
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1039
+ etc.)
1040
+
1041
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1042
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1043
+ and behavior.
1044
+
1045
+ Parameters:
1046
+ config ([`BambaConfig`]):
1047
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1048
+ load the weights associated with the model, only the configuration. Check out the
1049
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1050
+ """
1051
+
1052
+
1053
+ @add_start_docstrings(
1054
+ "The bare BambaModel outputting raw hidden-states without any specific head on top.",
1055
+ BAMBA_START_DOCSTRING,
1056
+ )
1057
+ class BambaPreTrainedModel(PreTrainedModel):
1058
+ config_class = BambaConfig
1059
+ base_model_prefix = "model"
1060
+ supports_gradient_checkpointing = True
1061
+ _no_split_modules = ["BambaDecoderLayer"]
1062
+ _skip_keys_device_placement = "past_key_values"
1063
+ _supports_flash_attn_2 = True
1064
+ _supports_sdpa = True
1065
+ _supports_cache_class = True # Note: only supports HybridMambaAttentionDynamicCache
1066
+ _is_stateful = True
1067
+
1068
+ def _init_weights(self, module):
1069
+ std = self.config.initializer_range
1070
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
1071
+ module.weight.data.normal_(mean=0.0, std=std)
1072
+ if module.bias is not None:
1073
+ module.bias.data.zero_()
1074
+ elif isinstance(module, nn.Embedding):
1075
+ module.weight.data.normal_(mean=0.0, std=std)
1076
+ if module.padding_idx is not None:
1077
+ module.weight.data[module.padding_idx].zero_()
1078
+
1079
+
1080
+ BAMBA_INPUTS_DOCSTRING = r"""
1081
+ Args:
1082
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1083
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1084
+ it.
1085
+
1086
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1087
+ [`PreTrainedTokenizer.__call__`] for details.
1088
+
1089
+ [What are input IDs?](../glossary#input-ids)
1090
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1091
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1092
+
1093
+ - 1 for tokens that are **not masked**,
1094
+ - 0 for tokens that are **masked**.
1095
+
1096
+ [What are attention masks?](../glossary#attention-mask)
1097
+
1098
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1099
+ [`PreTrainedTokenizer.__call__`] for details.
1100
+
1101
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1102
+ `past_key_values`).
1103
+
1104
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1105
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1106
+ information on the default strategy.
1107
+
1108
+ - 1 indicates the head is **not masked**,
1109
+ - 0 indicates the head is **masked**.
1110
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1111
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1112
+ config.n_positions - 1]`.
1113
+
1114
+ [What are position IDs?](../glossary#position-ids)
1115
+ past_key_values (`HybridMambaAttentionDynamicCache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1116
+ A HybridMambaAttentionDynamicCache object containing pre-computed hidden-states (keys and values in the
1117
+ self-attention blocks and convolution and ssm states in the mamba blocks) that can be used (see
1118
+ `past_key_values` input) to speed up sequential decoding.
1119
+ Key and value cache tensors have shape `(batch_size, num_heads, seq_len, head_dim)`.
1120
+ Convolution and ssm states tensors have shape `(batch_size, d_inner, d_conv)` and
1121
+ `(batch_size, d_inner, d_state)` respectively.
1122
+ See the `HybridMambaAttentionDynamicCache` class for more details.
1123
+
1124
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that
1125
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1126
+ `input_ids` of shape `(batch_size, sequence_length)`.
1127
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1128
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1129
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1130
+ model's internal embedding lookup matrix.
1131
+ use_cache (`bool`, *optional*):
1132
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1133
+ `past_key_values`).
1134
+ output_attentions (`bool`, *optional*):
1135
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1136
+ tensors for more detail.
1137
+ output_hidden_states (`bool`, *optional*):
1138
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1139
+ more detail.
1140
+ output_router_logits (`bool`, *optional*):
1141
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
1142
+ should not be returned during inference.
1143
+ return_dict (`bool`, *optional*):
1144
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1145
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1146
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
1147
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
1148
+ the complete sequence length.
1149
+ """
1150
+
1151
+
1152
+ @add_start_docstrings(
1153
+ "The bare Bamba Model outputting raw hidden-states without any specific head on top.",
1154
+ BAMBA_START_DOCSTRING,
1155
+ )
1156
+ # Adapted from transformers.models.jamba.modeling_jamba.JambaModel
1157
+ class BambaModel(BambaPreTrainedModel):
1158
+ """
1159
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`BambaDecoderLayer`]
1160
+
1161
+ Args:
1162
+ config: BambaConfig
1163
+ """
1164
+
1165
+ def __init__(self, config: BambaConfig):
1166
+ super().__init__(config)
1167
+ self.padding_idx = config.pad_token_id
1168
+ self.vocab_size = config.vocab_size
1169
+
1170
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1171
+ decoder_layers = []
1172
+ for i in range(config.num_hidden_layers):
1173
+ decoder_layers.append(BambaDecoderLayer(config, layer_idx=i, layer_type=config.layers_block_type[i]))
1174
+ self.layers = nn.ModuleList(decoder_layers)
1175
+
1176
+ self._attn_implementation = config._attn_implementation
1177
+ self.final_layernorm = BambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1178
+ self.rotary_emb = BambaRotaryEmbedding(config=config)
1179
+
1180
+ self.gradient_checkpointing = False
1181
+ # Initialize weights and apply final processing
1182
+ self.post_init()
1183
+
1184
+ def get_input_embeddings(self):
1185
+ return self.embed_tokens
1186
+
1187
+ def set_input_embeddings(self, value):
1188
+ self.embed_tokens = value
1189
+
1190
+ @add_start_docstrings_to_model_forward(BAMBA_INPUTS_DOCSTRING)
1191
+ def forward(
1192
+ self,
1193
+ input_ids: torch.LongTensor = None,
1194
+ attention_mask: Optional[torch.Tensor] = None,
1195
+ position_ids: Optional[torch.LongTensor] = None,
1196
+ past_key_values: Optional[HybridMambaAttentionDynamicCache] = None,
1197
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1198
+ use_cache: Optional[bool] = None,
1199
+ output_attentions: Optional[bool] = None,
1200
+ output_hidden_states: Optional[bool] = None,
1201
+ return_dict: Optional[bool] = None,
1202
+ cache_position: Optional[torch.LongTensor] = None,
1203
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1204
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1205
+ output_hidden_states = (
1206
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1207
+ )
1208
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1209
+
1210
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1211
+
1212
+ if (input_ids is None) ^ (inputs_embeds is not None):
1213
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1214
+
1215
+ if self.gradient_checkpointing and self.training and use_cache:
1216
+ logger.warning_once(
1217
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1218
+ )
1219
+ use_cache = False
1220
+
1221
+ if inputs_embeds is None:
1222
+ inputs_embeds = self.embed_tokens(input_ids)
1223
+ hidden_states = inputs_embeds
1224
+
1225
+ if use_cache and past_key_values is None:
1226
+ logger.warning_once(
1227
+ "Bamba requires an initialized `HybridMambaAttentionDynamicCache` to return a cache. None was "
1228
+ "provided, so no cache will be returned."
1229
+ )
1230
+
1231
+ if cache_position is None:
1232
+ cache_position = torch.arange(hidden_states.shape[1], device=hidden_states.device)
1233
+ if position_ids is None:
1234
+ position_ids = cache_position.unsqueeze(0)
1235
+
1236
+ causal_mask = self._update_causal_mask(
1237
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1238
+ )
1239
+ mamba_mask = self._update_mamba_mask(attention_mask, cache_position)
1240
+
1241
+ # create position embeddings to be shared across the decoder layers
1242
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1243
+
1244
+ all_hidden_states = () if output_hidden_states else None
1245
+ all_self_attns = () if output_attentions else None
1246
+
1247
+ for decoder_layer in self.layers:
1248
+ # Depending on the layer type we opt for 2D base attention mask (Mamba) or 4D causal mask (Attention)
1249
+ layer_mask = mamba_mask if decoder_layer.layer_type == "mamba" else causal_mask
1250
+
1251
+ if output_hidden_states:
1252
+ all_hidden_states += (hidden_states,)
1253
+
1254
+ if self.gradient_checkpointing and self.training:
1255
+ layer_outputs = self._gradient_checkpointing_func(
1256
+ decoder_layer.__call__,
1257
+ hidden_states,
1258
+ layer_mask,
1259
+ position_ids,
1260
+ past_key_values,
1261
+ output_attentions,
1262
+ use_cache,
1263
+ cache_position,
1264
+ position_embeddings,
1265
+ )
1266
+ else:
1267
+ layer_outputs = decoder_layer(
1268
+ hidden_states,
1269
+ attention_mask=layer_mask,
1270
+ position_ids=position_ids,
1271
+ past_key_value=past_key_values,
1272
+ output_attentions=output_attentions,
1273
+ use_cache=use_cache,
1274
+ cache_position=cache_position,
1275
+ position_embeddings=position_embeddings,
1276
+ )
1277
+
1278
+ hidden_states = layer_outputs[0]
1279
+
1280
+ if output_attentions:
1281
+ if layer_outputs[1] is not None:
1282
+ # append attentions only of attention layers. Mamba layers return `None` as the attention weights
1283
+ all_self_attns += (layer_outputs[1],)
1284
+
1285
+ hidden_states = self.final_layernorm(hidden_states)
1286
+
1287
+ # add hidden states from the last decoder layer
1288
+ if output_hidden_states:
1289
+ all_hidden_states += (hidden_states,)
1290
+
1291
+ if past_key_values and not past_key_values.has_previous_state:
1292
+ past_key_values.has_previous_state = True
1293
+
1294
+ next_cache = None if not use_cache else past_key_values
1295
+
1296
+ if not return_dict:
1297
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1298
+ return BaseModelOutputWithPast(
1299
+ last_hidden_state=hidden_states,
1300
+ past_key_values=next_cache,
1301
+ hidden_states=all_hidden_states,
1302
+ attentions=all_self_attns,
1303
+ )
1304
+
1305
+ def _update_causal_mask(
1306
+ self,
1307
+ attention_mask: torch.Tensor,
1308
+ input_tensor: torch.Tensor,
1309
+ cache_position: torch.Tensor,
1310
+ past_key_values: HybridMambaAttentionDynamicCache,
1311
+ output_attentions: bool,
1312
+ ):
1313
+ if self.config._attn_implementation == "flash_attention_2":
1314
+ if attention_mask is not None and 0.0 in attention_mask:
1315
+ return attention_mask
1316
+ return None
1317
+
1318
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1319
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1320
+ # to infer the attention mask.
1321
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1322
+
1323
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1324
+ if self.config._attn_implementation == "sdpa" and not output_attentions:
1325
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1326
+ attention_mask,
1327
+ inputs_embeds=input_tensor,
1328
+ past_key_values_length=past_seen_tokens,
1329
+ is_training=self.training,
1330
+ ):
1331
+ return None
1332
+
1333
+ dtype, device = input_tensor.dtype, input_tensor.device
1334
+ sequence_length = input_tensor.shape[1]
1335
+ target_length = (
1336
+ attention_mask.shape[-1]
1337
+ if isinstance(attention_mask, torch.Tensor)
1338
+ else past_seen_tokens + sequence_length + 1
1339
+ )
1340
+
1341
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1342
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1343
+ attention_mask,
1344
+ sequence_length=sequence_length,
1345
+ target_length=target_length,
1346
+ dtype=dtype,
1347
+ device=device,
1348
+ cache_position=cache_position,
1349
+ batch_size=input_tensor.shape[0],
1350
+ )
1351
+
1352
+ if (
1353
+ self.config._attn_implementation == "sdpa"
1354
+ and attention_mask is not None
1355
+ and attention_mask.device.type == "cuda"
1356
+ and not output_attentions
1357
+ ):
1358
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1359
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1360
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1361
+ min_dtype = torch.finfo(dtype).min
1362
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1363
+
1364
+ return causal_mask
1365
+
1366
+ @staticmethod
1367
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1368
+ attention_mask: torch.Tensor,
1369
+ sequence_length: int,
1370
+ target_length: int,
1371
+ dtype: torch.dtype,
1372
+ device: torch.device,
1373
+ cache_position: torch.Tensor,
1374
+ batch_size: int,
1375
+ **kwargs,
1376
+ ):
1377
+ """
1378
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1379
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1380
+
1381
+ Args:
1382
+ attention_mask (`torch.Tensor`):
1383
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
1384
+ `(batch_size, 1, query_length, key_value_length)`.
1385
+ sequence_length (`int`):
1386
+ The sequence length being processed.
1387
+ target_length (`int`):
1388
+ The target length: when generating with static cache, the mask should be as long as the static cache,
1389
+ to account for the 0 padding, the part of the cache that is not filled yet.
1390
+ dtype (`torch.dtype`):
1391
+ The dtype to use for the 4D attention mask.
1392
+ device (`torch.device`):
1393
+ The device to plcae the 4D attention mask on.
1394
+ cache_position (`torch.Tensor`):
1395
+ Indices depicting the position of the input sequence tokens in the sequence.
1396
+ batch_size (`torch.Tensor`):
1397
+ Batch size.
1398
+ """
1399
+ if attention_mask is not None and attention_mask.dim() == 4:
1400
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1401
+ causal_mask = attention_mask
1402
+ else:
1403
+ min_dtype = torch.finfo(dtype).min
1404
+ causal_mask = torch.full(
1405
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1406
+ )
1407
+ if sequence_length != 1:
1408
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1409
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1410
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1411
+ if attention_mask is not None:
1412
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1413
+ mask_length = attention_mask.shape[-1]
1414
+ padding_attention_mask = (attention_mask[:, None, None, :] == attention_mask[:, None, :, None])[
1415
+ :, :, -sequence_length:, :
1416
+ ].to(dtype)
1417
+ padding_mask = causal_mask[:, :, :, :mask_length] + padding_attention_mask
1418
+ padding_mask = padding_mask == 0
1419
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1420
+ padding_mask, min_dtype
1421
+ )
1422
+
1423
+ return causal_mask
1424
+
1425
+ def _update_mamba_mask(self, attention_mask, cache_position):
1426
+ """
1427
+ No need for zeroing states when
1428
+ 1. Cached forward
1429
+ 2. Attending to all inputs
1430
+ """
1431
+ mamba_mask = attention_mask
1432
+ if cache_position[0] > 0 or (attention_mask is not None and torch.all(attention_mask == 1)):
1433
+ mamba_mask = None
1434
+ return mamba_mask
1435
+
1436
+
1437
+ class BambaForCausalLM(BambaPreTrainedModel, GenerationMixin):
1438
+ _tied_weights_keys = ["lm_head.weight"]
1439
+ _tp_plan = {"lm_head": "colwise_rep"}
1440
+
1441
+ def __init__(self, config):
1442
+ super().__init__(config)
1443
+ self.model = BambaModel(config)
1444
+ self.vocab_size = config.vocab_size
1445
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1446
+
1447
+ # Initialize weights and apply final processing
1448
+ self.post_init()
1449
+
1450
+ def get_input_embeddings(self):
1451
+ return self.model.embed_tokens
1452
+
1453
+ def set_input_embeddings(self, value):
1454
+ self.model.embed_tokens = value
1455
+
1456
+ def get_output_embeddings(self):
1457
+ return self.lm_head
1458
+
1459
+ def set_output_embeddings(self, new_embeddings):
1460
+ self.lm_head = new_embeddings
1461
+
1462
+ def set_decoder(self, decoder):
1463
+ self.model = decoder
1464
+
1465
+ def get_decoder(self):
1466
+ return self.model
1467
+
1468
+ @add_start_docstrings_to_model_forward(BAMBA_INPUTS_DOCSTRING)
1469
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1470
+ def forward(
1471
+ self,
1472
+ input_ids: torch.LongTensor = None,
1473
+ attention_mask: Optional[torch.Tensor] = None,
1474
+ position_ids: Optional[torch.LongTensor] = None,
1475
+ past_key_values: Optional[HybridMambaAttentionDynamicCache] = None,
1476
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1477
+ labels: Optional[torch.LongTensor] = None,
1478
+ use_cache: Optional[bool] = None,
1479
+ output_attentions: Optional[bool] = None,
1480
+ output_hidden_states: Optional[bool] = None,
1481
+ return_dict: Optional[bool] = None,
1482
+ cache_position: Optional[torch.LongTensor] = None,
1483
+ num_logits_to_keep: int = 0,
1484
+ **kwargs,
1485
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1486
+ r"""
1487
+ Args:
1488
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1489
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1490
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1491
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1492
+
1493
+ num_logits_to_keep (`int` or `None`, *optional*):
1494
+ Calculate logits for the last `num_logits_to_keep` tokens. If `None`, calculate logits for all
1495
+ `input_ids`. Only last token logits are needed for generation, and calculating them only for that token
1496
+ can save memory, which becomes pretty significant for long sequences.
1497
+
1498
+ Returns:
1499
+
1500
+ Example:
1501
+
1502
+ ```python
1503
+ >>> from transformers import AutoTokenizer, BambaForCausalLM
1504
+
1505
+ >>> model = BambaForCausalLM.from_pretrained("...")
1506
+ >>> tokenizer = AutoTokenizer.from_pretrained("...")
1507
+
1508
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1509
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1510
+
1511
+ >>> # Generate
1512
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1513
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1514
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1515
+ ```"""
1516
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1517
+ output_hidden_states = (
1518
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1519
+ )
1520
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1521
+
1522
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1523
+ outputs = self.model(
1524
+ input_ids=input_ids,
1525
+ attention_mask=attention_mask,
1526
+ position_ids=position_ids,
1527
+ past_key_values=past_key_values,
1528
+ inputs_embeds=inputs_embeds,
1529
+ use_cache=use_cache,
1530
+ output_attentions=output_attentions,
1531
+ output_hidden_states=output_hidden_states,
1532
+ return_dict=return_dict,
1533
+ cache_position=cache_position,
1534
+ **kwargs,
1535
+ )
1536
+
1537
+ hidden_states = outputs[0]
1538
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1539
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1540
+
1541
+ loss = None
1542
+ if labels is not None:
1543
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
1544
+
1545
+ if not return_dict:
1546
+ output = (logits,) + outputs[1:]
1547
+ return (loss,) + output if loss is not None else output
1548
+
1549
+ return CausalLMOutputWithPast(
1550
+ loss=loss,
1551
+ logits=logits,
1552
+ past_key_values=outputs.past_key_values,
1553
+ hidden_states=outputs.hidden_states,
1554
+ attentions=outputs.attentions,
1555
+ )
1556
+
1557
+ def prepare_inputs_for_generation(
1558
+ self,
1559
+ input_ids,
1560
+ past_key_values=None,
1561
+ attention_mask=None,
1562
+ inputs_embeds=None,
1563
+ cache_position=None,
1564
+ position_ids=None,
1565
+ use_cache=True,
1566
+ **kwargs,
1567
+ ):
1568
+ # Overwitten -- has a unique cache type, `HybridMambaAttentionDynamicCache`
1569
+
1570
+ empty_past_kv = past_key_values is None
1571
+
1572
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1573
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1574
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1575
+ if not empty_past_kv:
1576
+ if inputs_embeds is not None: # Exception 1
1577
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1578
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1579
+ input_ids = input_ids[:, cache_position]
1580
+ else:
1581
+ past_key_values = HybridMambaAttentionDynamicCache(
1582
+ self.config, input_ids.shape[0], self.dtype, device=self.device
1583
+ )
1584
+
1585
+ if attention_mask is not None and position_ids is None:
1586
+ # create position_ids on the fly for batch generation
1587
+ position_ids = attention_mask.long().cumsum(-1) - 1
1588
+ position_ids.masked_fill_(attention_mask == 0, 1)
1589
+ if not empty_past_kv:
1590
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1591
+
1592
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1593
+ if inputs_embeds is not None and empty_past_kv:
1594
+ model_inputs = {"inputs_embeds": inputs_embeds}
1595
+ else:
1596
+ model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
1597
+
1598
+ model_inputs.update(
1599
+ {
1600
+ "position_ids": position_ids,
1601
+ "past_key_values": past_key_values,
1602
+ "use_cache": use_cache,
1603
+ "attention_mask": attention_mask,
1604
+ "num_logits_to_keep": self.config.num_logits_to_keep,
1605
+ "cache_position": cache_position,
1606
+ }
1607
+ )
1608
+ return model_inputs
1609
+
1610
+
1611
+ __all__ = ["BambaModel", "BambaForCausalLM", "BambaPreTrainedModel"]
vlmpy310/lib/python3.10/site-packages/transformers/models/clap/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_clap import *
22
+ from .feature_extraction_clap import *
23
+ from .modeling_clap import *
24
+ from .processing_clap import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
vlmpy310/lib/python3.10/site-packages/transformers/models/clap/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (596 Bytes). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/clap/__pycache__/configuration_clap.cpython-310.pyc ADDED
Binary file (16.3 kB). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/clap/__pycache__/convert_clap_original_pytorch_to_hf.cpython-310.pyc ADDED
Binary file (3.33 kB). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/clap/__pycache__/feature_extraction_clap.cpython-310.pyc ADDED
Binary file (14.5 kB). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/clap/__pycache__/modeling_clap.cpython-310.pyc ADDED
Binary file (67.1 kB). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/clap/__pycache__/processing_clap.cpython-310.pyc ADDED
Binary file (5.25 kB). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/clap/configuration_clap.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """CLAP 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 ClapTextConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`ClapTextModel`]. It is used to instantiate a CLAP
27
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
28
+ defaults will yield a similar configuration to that of the CLAP
29
+ [calp-hsat-fused](https://huggingface.co/laion/clap-hsat-fused) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 30522):
37
+ Vocabulary size of the CLAP model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`ClapTextModel`].
39
+ hidden_size (`int`, *optional*, defaults to 768):
40
+ Dimensionality of the encoder layers and the pooler layer.
41
+ num_hidden_layers (`int`, *optional*, defaults to 12):
42
+ Number of hidden layers in the Transformer encoder.
43
+ num_attention_heads (`int`, *optional*, defaults to 12):
44
+ Number of attention heads for each attention layer in the Transformer encoder.
45
+ intermediate_size (`int`, *optional*, defaults to 3072):
46
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
47
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"relu"`):
48
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"relu"`,
49
+ `"relu"`, `"silu"` and `"relu_new"` are supported.
50
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
51
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
52
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
53
+ The dropout ratio for the attention probabilities.
54
+ max_position_embeddings (`int`, *optional*, defaults to 512):
55
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
56
+ just in case (e.g., 512 or 1024 or 2048).
57
+ type_vocab_size (`int`, *optional*, defaults to 2):
58
+ The vocabulary size of the `token_type_ids` passed when calling [`ClapTextModel`].
59
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
60
+ The epsilon used by the layer normalization layers.
61
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
62
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
63
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
64
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
65
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
66
+ with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
67
+ is_decoder (`bool`, *optional*, defaults to `False`):
68
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
69
+ use_cache (`bool`, *optional*, defaults to `True`):
70
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
71
+ relevant if `config.is_decoder=True`.
72
+ projection_hidden_act (`str`, *optional*, defaults to `"relu"`):
73
+ The non-linear activation function (function or string) in the projection layer. If string, `"gelu"`,
74
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
75
+ projection_dim (`int`, *optional*, defaults to 512)
76
+ Dimension of the projection head of the `ClapTextModelWithProjection`.
77
+
78
+ Examples:
79
+
80
+ ```python
81
+ >>> from transformers import ClapTextConfig, ClapTextModel
82
+
83
+ >>> # Initializing a CLAP text configuration
84
+ >>> configuration = ClapTextConfig()
85
+
86
+ >>> # Initializing a model (with random weights) from the configuration
87
+ >>> model = ClapTextModel(configuration)
88
+
89
+ >>> # Accessing the model configuration
90
+ >>> configuration = model.config
91
+ ```"""
92
+
93
+ model_type = "clap_text_model"
94
+ base_config_key = "text_config"
95
+
96
+ def __init__(
97
+ self,
98
+ vocab_size=50265,
99
+ hidden_size=768,
100
+ num_hidden_layers=12,
101
+ num_attention_heads=12,
102
+ intermediate_size=3072,
103
+ hidden_act="gelu",
104
+ hidden_dropout_prob=0.1,
105
+ attention_probs_dropout_prob=0.1,
106
+ max_position_embeddings=514,
107
+ type_vocab_size=1,
108
+ initializer_factor=1.0,
109
+ layer_norm_eps=1e-12,
110
+ projection_dim=512,
111
+ pad_token_id=1,
112
+ bos_token_id=0,
113
+ eos_token_id=2,
114
+ position_embedding_type="absolute",
115
+ use_cache=True,
116
+ projection_hidden_act="relu",
117
+ **kwargs,
118
+ ):
119
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
120
+
121
+ self.vocab_size = vocab_size
122
+ self.hidden_size = hidden_size
123
+ self.num_hidden_layers = num_hidden_layers
124
+ self.num_attention_heads = num_attention_heads
125
+ self.hidden_act = hidden_act
126
+ self.intermediate_size = intermediate_size
127
+ self.hidden_dropout_prob = hidden_dropout_prob
128
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
129
+ self.max_position_embeddings = max_position_embeddings
130
+ self.type_vocab_size = type_vocab_size
131
+ self.initializer_factor = initializer_factor
132
+ self.layer_norm_eps = layer_norm_eps
133
+ self.position_embedding_type = position_embedding_type
134
+ self.use_cache = use_cache
135
+ self.projection_hidden_act = projection_hidden_act
136
+ self.projection_dim = projection_dim
137
+
138
+
139
+ class ClapAudioConfig(PretrainedConfig):
140
+ r"""
141
+ This is the configuration class to store the configuration of a [`ClapAudioModel`]. It is used to instantiate a
142
+ CLAP audio encoder according to the specified arguments, defining the model architecture. Instantiating a
143
+ configuration with the defaults will yield a similar configuration to that of the audio encoder of the CLAP
144
+ [laion/clap-htsat-fused](https://huggingface.co/laion/clap-htsat-fused) architecture.
145
+
146
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
147
+ documentation from [`PretrainedConfig`] for more information.
148
+
149
+ Args:
150
+ window_size (`int`, *optional*, defaults to 8):
151
+ Image size of the spectrogram
152
+ num_mel_bins (`int`, *optional*, defaults to 64):
153
+ Number of mel features used per frames. Should correspond to the value used in the `ClapProcessor` class.
154
+ spec_size (`int`, *optional*, defaults to 256):
155
+ Desired input size of the spectrogram that the model supports. It can be different from the output of the
156
+ `ClapFeatureExtractor`, in which case the input features will be resized. Corresponds to the `image_size`
157
+ of the audio models.
158
+ hidden_act (`str`, *optional*, defaults to `"gelu"`):
159
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
160
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
161
+ patch_size (`int`, *optional*, defaults to 4):
162
+ Patch size for the audio spectrogram
163
+ patch_stride (`list`, *optional*, defaults to `[4, 4]`):
164
+ Patch stride for the audio spectrogram
165
+ num_classes (`int`, *optional*, defaults to 527):
166
+ Number of classes used for the head training
167
+ hidden_size (`int`, *optional*, defaults to 768):
168
+ Hidden size of the output of the audio encoder. Correspond to the dimension of the penultimate layer's
169
+ output,which is sent to the projection MLP layer.
170
+ projection_dim (`int`, *optional*, defaults to 512):
171
+ Hidden size of the projection layer.
172
+ depths (`list`, *optional*, defaults to `[2, 2, 6, 2]`):
173
+ Depths used for the Swin Layers of the audio model
174
+ num_attention_heads (`list`, *optional*, defaults to `[4, 8, 16, 32]`):
175
+ Number of attention heads used for the Swin Layers of the audio model
176
+ enable_fusion (`bool`, *optional*, defaults to `False`):
177
+ Whether or not to enable patch fusion. This is the main contribution of the authors, and should give the
178
+ best results.
179
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
180
+ The dropout probability for all fully connected layers in the encoder.
181
+ fusion_type (`[type]`, *optional*):
182
+ Fusion type used for the patch fusion.
183
+ patch_embed_input_channels (`int`, *optional*, defaults to 1):
184
+ Number of channels used for the input spectrogram
185
+ flatten_patch_embeds (`bool`, *optional*, defaults to `True`):
186
+ Whether or not to flatten the patch embeddings
187
+ patch_embeds_hidden_size (`int`, *optional*, defaults to 96):
188
+ Hidden size of the patch embeddings. It is used as the number of output channels.
189
+ enable_patch_layer_norm (`bool`, *optional*, defaults to `True`):
190
+ Whether or not to enable layer normalization for the patch embeddings
191
+ drop_path_rate (`float`, *optional*, defaults to 0.0):
192
+ Drop path rate for the patch fusion
193
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
194
+ The dropout ratio for the attention probabilities.
195
+ qkv_bias (`bool`, *optional*, defaults to `True`):
196
+ Whether or not to add a bias to the query, key, value projections.
197
+ mlp_ratio (`float`, *optional*, defaults to 4.0):
198
+ Ratio of the mlp hidden dim to embedding dim.
199
+ aff_block_r (`int`, *optional*, defaults to 4):
200
+ downsize_ratio used in the AudioFF block
201
+ num_hidden_layers (`int`, *optional*, defaults to 4):
202
+ Number of hidden layers in the Transformer encoder.
203
+ projection_hidden_act (`str`, *optional*, defaults to `"relu"`):
204
+ The non-linear activation function (function or string) in the projection layer. If string, `"gelu"`,
205
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
206
+ layer_norm_eps (`[type]`, *optional*, defaults to 1e-05):
207
+ The epsilon used by the layer normalization layers.
208
+ initializer_factor (`float`, *optional*, defaults to 1.0):
209
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
210
+ testing).
211
+
212
+ Example:
213
+
214
+ ```python
215
+ >>> from transformers import ClapAudioConfig, ClapAudioModel
216
+
217
+ >>> # Initializing a ClapAudioConfig with laion/clap-htsat-fused style configuration
218
+ >>> configuration = ClapAudioConfig()
219
+
220
+ >>> # Initializing a ClapAudioModel (with random weights) from the laion/clap-htsat-fused style configuration
221
+ >>> model = ClapAudioModel(configuration)
222
+
223
+ >>> # Accessing the model configuration
224
+ >>> configuration = model.config
225
+ ```"""
226
+
227
+ model_type = "clap_audio_model"
228
+ base_config_key = "audio_config"
229
+
230
+ def __init__(
231
+ self,
232
+ window_size=8,
233
+ num_mel_bins=64,
234
+ spec_size=256,
235
+ hidden_act="gelu",
236
+ patch_size=4,
237
+ patch_stride=[4, 4],
238
+ num_classes=527,
239
+ hidden_size=768,
240
+ projection_dim=512,
241
+ depths=[2, 2, 6, 2],
242
+ num_attention_heads=[4, 8, 16, 32],
243
+ enable_fusion=False,
244
+ hidden_dropout_prob=0.1,
245
+ fusion_type=None,
246
+ patch_embed_input_channels=1,
247
+ flatten_patch_embeds=True,
248
+ patch_embeds_hidden_size=96,
249
+ enable_patch_layer_norm=True,
250
+ drop_path_rate=0.0,
251
+ attention_probs_dropout_prob=0.0,
252
+ qkv_bias=True,
253
+ mlp_ratio=4.0,
254
+ aff_block_r=4,
255
+ num_hidden_layers=4,
256
+ projection_hidden_act="relu",
257
+ layer_norm_eps=1e-5,
258
+ initializer_factor=1.0,
259
+ **kwargs,
260
+ ):
261
+ super().__init__(**kwargs)
262
+ self.window_size = window_size
263
+ self.num_mel_bins = num_mel_bins
264
+ self.spec_size = spec_size
265
+ self.patch_size = patch_size
266
+ self.patch_stride = patch_stride
267
+ self.num_classes = num_classes
268
+ self.hidden_size = hidden_size
269
+ self.depths = depths
270
+ self.num_hidden_layers = num_hidden_layers
271
+ self.num_attention_heads = num_attention_heads
272
+ self.window_size = window_size
273
+ self.enable_fusion = enable_fusion
274
+ self.fusion_type = fusion_type
275
+ self.hidden_act = hidden_act
276
+ self.hidden_dropout_prob = hidden_dropout_prob
277
+ self.projection_dim = projection_dim
278
+ self.flatten_patch_embeds = flatten_patch_embeds
279
+ self.patch_embeds_hidden_size = patch_embeds_hidden_size
280
+ self.enable_patch_layer_norm = enable_patch_layer_norm
281
+ self.drop_path_rate = drop_path_rate
282
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
283
+ self.qkv_bias = qkv_bias
284
+ self.mlp_ratio = mlp_ratio
285
+ self.patch_embed_input_channels = patch_embed_input_channels
286
+ self.aff_block_r = aff_block_r
287
+ self.layer_norm_eps = layer_norm_eps
288
+ self.initializer_factor = initializer_factor
289
+ self.projection_hidden_act = projection_hidden_act
290
+
291
+
292
+ class ClapConfig(PretrainedConfig):
293
+ r"""
294
+ [`ClapConfig`] is the configuration class to store the configuration of a [`ClapModel`]. It is used to instantiate
295
+ a CLAP model according to the specified arguments, defining the text model and audio model configs. Instantiating a
296
+ configuration with the defaults will yield a similar configuration to that of the CLAP
297
+ [laion/clap-htsat-fused](https://huggingface.co/laion/clap-htsat-fused) architecture.
298
+
299
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
300
+ documentation from [`PretrainedConfig`] for more information.
301
+
302
+ Args:
303
+ text_config (`dict`, *optional*):
304
+ Dictionary of configuration options used to initialize [`ClapTextConfig`].
305
+ audio_config (`dict`, *optional*):
306
+ Dictionary of configuration options used to initialize [`ClapAudioConfig`].
307
+ logit_scale_init_value (`float`, *optional*, defaults to 14.29):
308
+ The initial value of the *logit_scale* parameter. Default is used as per the original CLAP implementation.
309
+ projection_dim (`int`, *optional*, defaults to 512):
310
+ Dimensionality of text and audio projection layers.
311
+ projection_hidden_act (`str`, *optional*, defaults to `"relu"`):
312
+ Activation function for the projection layers.
313
+ initializer_factor (`float`, *optional*, defaults to 1.0):
314
+ Factor to scale the initialization of the model weights.
315
+ kwargs (*optional*):
316
+ Dictionary of keyword arguments.
317
+
318
+ Example:
319
+
320
+ ```python
321
+ >>> from transformers import ClapConfig, ClapModel
322
+
323
+ >>> # Initializing a ClapConfig with laion-ai/base style configuration
324
+ >>> configuration = ClapConfig()
325
+
326
+ >>> # Initializing a ClapModel (with random weights) from the laion-ai/base style configuration
327
+ >>> model = ClapModel(configuration)
328
+
329
+ >>> # Accessing the model configuration
330
+ >>> configuration = model.config
331
+
332
+ >>> # We can also initialize a ClapConfig from a ClapTextConfig and a ClapAudioConfig
333
+ >>> from transformers import ClapTextConfig, ClapAudioConfig
334
+
335
+ >>> # Initializing a ClapText and ClapAudioConfig configuration
336
+ >>> config_text = ClapTextConfig()
337
+ >>> config_audio = ClapAudioConfig()
338
+
339
+ >>> config = ClapConfig.from_text_audio_configs(config_text, config_audio)
340
+ ```"""
341
+
342
+ model_type = "clap"
343
+ sub_configs = {"text_config": ClapTextConfig, "audio_config": ClapAudioConfig}
344
+
345
+ def __init__(
346
+ self,
347
+ text_config=None,
348
+ audio_config=None,
349
+ logit_scale_init_value=(1 / 0.07),
350
+ projection_dim=512,
351
+ projection_hidden_act="relu",
352
+ initializer_factor=1.0,
353
+ **kwargs,
354
+ ):
355
+ super().__init__(**kwargs)
356
+
357
+ if text_config is None:
358
+ text_config = {}
359
+ logger.info("text_config is None. Initializing the ClapTextConfig with default values.")
360
+
361
+ if audio_config is None:
362
+ audio_config = {}
363
+ logger.info("audio_config is None. initializing the ClapAudioConfig with default values.")
364
+
365
+ self.text_config = ClapTextConfig(**text_config)
366
+ self.audio_config = ClapAudioConfig(**audio_config)
367
+ self.text_config.projection_dim = projection_dim
368
+ self.audio_config.projection_dim = projection_dim
369
+
370
+ self.text_config.projection_hidden_act = projection_hidden_act
371
+ self.audio_config.projection_hidden_act = projection_hidden_act
372
+
373
+ self.projection_dim = projection_dim
374
+ self.projection_hidden_act = projection_hidden_act
375
+ self.hidden_size = self.text_config.hidden_size
376
+
377
+ self.logit_scale_init_value = logit_scale_init_value
378
+ self.initializer_factor = initializer_factor
379
+ self.num_hidden_layers = self.text_config.num_hidden_layers + len(self.audio_config.depths)
380
+
381
+ @classmethod
382
+ def from_text_audio_configs(cls, text_config: ClapTextConfig, audio_config: ClapAudioConfig, **kwargs):
383
+ r"""
384
+ Instantiate a [`ClapConfig`] (or a derived class) from clap text model configuration and clap audio model
385
+ configuration.
386
+
387
+ Returns:
388
+ [`ClapConfig`]: An instance of a configuration object
389
+ """
390
+
391
+ return cls(text_config=text_config.to_dict(), audio_config=audio_config.to_dict(), **kwargs)
392
+
393
+
394
+ __all__ = ["ClapAudioConfig", "ClapConfig", "ClapTextConfig"]
vlmpy310/lib/python3.10/site-packages/transformers/models/clap/convert_clap_original_pytorch_to_hf.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import argparse
17
+ import re
18
+
19
+ from laion_clap import CLAP_Module
20
+
21
+ from transformers import AutoFeatureExtractor, ClapConfig, ClapModel
22
+
23
+
24
+ KEYS_TO_MODIFY_MAPPING = {
25
+ "text_branch": "text_model",
26
+ "audio_branch": "audio_model.audio_encoder",
27
+ "attn": "attention.self",
28
+ "self.proj": "output.dense",
29
+ "attention.self_mask": "attn_mask",
30
+ "mlp.fc1": "intermediate.dense",
31
+ "mlp.fc2": "output.dense",
32
+ "norm1": "layernorm_before",
33
+ "norm2": "layernorm_after",
34
+ "bn0": "batch_norm",
35
+ }
36
+
37
+ processor = AutoFeatureExtractor.from_pretrained("laion/clap-htsat-unfused", truncation="rand_trunc")
38
+
39
+
40
+ def init_clap(checkpoint_path, model_type, enable_fusion=False):
41
+ model = CLAP_Module(
42
+ amodel=model_type,
43
+ enable_fusion=enable_fusion,
44
+ )
45
+ model.load_ckpt(checkpoint_path)
46
+ return model
47
+
48
+
49
+ def get_config_from_original(clap_model):
50
+ audio_config = {
51
+ "patch_embeds_hidden_size": clap_model.model.audio_branch.embed_dim,
52
+ "depths": clap_model.model.audio_branch.depths,
53
+ "hidden_size": clap_model.model.audio_projection[0].in_features,
54
+ }
55
+
56
+ text_config = {"hidden_size": clap_model.model.text_branch.pooler.dense.in_features}
57
+
58
+ return ClapConfig(audio_config=audio_config, text_config=text_config)
59
+
60
+
61
+ def rename_state_dict(state_dict):
62
+ model_state_dict = {}
63
+
64
+ sequential_layers_pattern = r".*sequential.(\d+).*"
65
+ text_projection_pattern = r".*_projection.(\d+).*"
66
+
67
+ for key, value in state_dict.items():
68
+ # check if any key needs to be modified
69
+ for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
70
+ if key_to_modify in key:
71
+ key = key.replace(key_to_modify, new_key)
72
+
73
+ if re.match(sequential_layers_pattern, key):
74
+ # replace sequential layers with list
75
+ sequential_layer = re.match(sequential_layers_pattern, key).group(1)
76
+
77
+ key = key.replace(f"sequential.{sequential_layer}.", f"layers.{int(sequential_layer)//3}.linear.")
78
+ elif re.match(text_projection_pattern, key):
79
+ projecton_layer = int(re.match(text_projection_pattern, key).group(1))
80
+
81
+ # Because in CLAP they use `nn.Sequential`...
82
+ transformers_projection_layer = 1 if projecton_layer == 0 else 2
83
+
84
+ key = key.replace(f"_projection.{projecton_layer}.", f"_projection.linear{transformers_projection_layer}.")
85
+
86
+ if "audio" and "qkv" in key:
87
+ # split qkv into query key and value
88
+ mixed_qkv = value
89
+ qkv_dim = mixed_qkv.size(0) // 3
90
+
91
+ query_layer = mixed_qkv[:qkv_dim]
92
+ key_layer = mixed_qkv[qkv_dim : qkv_dim * 2]
93
+ value_layer = mixed_qkv[qkv_dim * 2 :]
94
+
95
+ model_state_dict[key.replace("qkv", "query")] = query_layer
96
+ model_state_dict[key.replace("qkv", "key")] = key_layer
97
+ model_state_dict[key.replace("qkv", "value")] = value_layer
98
+ else:
99
+ model_state_dict[key] = value
100
+
101
+ return model_state_dict
102
+
103
+
104
+ def convert_clap_checkpoint(checkpoint_path, pytorch_dump_folder_path, config_path, model_type, enable_fusion=False):
105
+ clap_model = init_clap(checkpoint_path, model_type, enable_fusion=enable_fusion)
106
+
107
+ clap_model.eval()
108
+ state_dict = clap_model.model.state_dict()
109
+ state_dict = rename_state_dict(state_dict)
110
+
111
+ transformers_config = get_config_from_original(clap_model)
112
+ transformers_config.audio_config.enable_fusion = enable_fusion
113
+ model = ClapModel(transformers_config)
114
+
115
+ # ignore the spectrogram embedding layer
116
+ model.load_state_dict(state_dict, strict=False)
117
+
118
+ model.save_pretrained(pytorch_dump_folder_path)
119
+ transformers_config.save_pretrained(pytorch_dump_folder_path)
120
+
121
+
122
+ if __name__ == "__main__":
123
+ parser = argparse.ArgumentParser()
124
+ parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
125
+ parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint")
126
+ parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
127
+ parser.add_argument("--enable_fusion", action="store_true", help="Whether to enable fusion or not")
128
+ parser.add_argument("--model_type", default="HTSAT-tiny", type=str, help="Whether to enable fusion or not")
129
+ args = parser.parse_args()
130
+
131
+ convert_clap_checkpoint(
132
+ args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.model_type, args.enable_fusion
133
+ )
vlmpy310/lib/python3.10/site-packages/transformers/models/clap/feature_extraction_clap.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Feature extractor class for CLAP."""
16
+
17
+ import copy
18
+ from typing import Any, Dict, List, Optional, Union
19
+
20
+ import numpy as np
21
+ import torch
22
+
23
+ from ...audio_utils import mel_filter_bank, spectrogram, window_function
24
+ from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
25
+ from ...feature_extraction_utils import BatchFeature
26
+ from ...utils import TensorType, logging
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+
32
+ class ClapFeatureExtractor(SequenceFeatureExtractor):
33
+ r"""
34
+ Constructs a CLAP feature extractor.
35
+
36
+ This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
37
+ most of the main methods. Users should refer to this superclass for more information regarding those methods.
38
+
39
+ This class extracts mel-filter bank features from raw speech using a custom numpy implementation of the *Short Time
40
+ Fourier Transform* (STFT) which should match pytorch's `torch.stft` equivalent.
41
+
42
+ Args:
43
+ feature_size (`int`, *optional*, defaults to 64):
44
+ The feature dimension of the extracted Mel spectrograms. This corresponds to the number of mel filters
45
+ (`n_mels`).
46
+ sampling_rate (`int`, *optional*, defaults to 48000):
47
+ The sampling rate at which the audio files should be digitalized expressed in hertz (Hz). This only serves
48
+ to warn users if the audio fed to the feature extractor does not have the same sampling rate.
49
+ hop_length (`int`,*optional*, defaults to 480):
50
+ Length of the overlaping windows for the STFT used to obtain the Mel Spectrogram. The audio will be split
51
+ in smaller `frames` with a step of `hop_length` between each frame.
52
+ max_length_s (`int`, *optional*, defaults to 10):
53
+ The maximum input length of the model in seconds. This is used to pad the audio.
54
+ fft_window_size (`int`, *optional*, defaults to 1024):
55
+ Size of the window (in samples) on which the Fourier transform is applied. This controls the frequency
56
+ resolution of the spectrogram. 400 means that the fourrier transform is computed on windows of 400 samples.
57
+ padding_value (`float`, *optional*, defaults to 0.0):
58
+ Padding value used to pad the audio. Should correspond to silences.
59
+ return_attention_mask (`bool`, *optional*, defaults to `False`):
60
+ Whether or not the model should return the attention masks coresponding to the input.
61
+ frequency_min (`float`, *optional*, defaults to 0):
62
+ The lowest frequency of interest. The STFT will not be computed for values below this.
63
+ frequency_max (`float`, *optional*, defaults to 14000):
64
+ The highest frequency of interest. The STFT will not be computed for values above this.
65
+ top_db (`float`, *optional*):
66
+ The highest decibel value used to convert the mel spectrogram to the log scale. For more details see the
67
+ `audio_utils.power_to_db` function
68
+ truncation (`str`, *optional*, defaults to `"fusion"`):
69
+ Truncation pattern for long audio inputs. Two patterns are available:
70
+ - `fusion` will use `_random_mel_fusion`, which stacks 3 random crops from the mel spectrogram and a
71
+ downsampled version of the entire mel spectrogram.
72
+ If `config.fusion` is set to True, shorter audios also need to to return 4 mels, which will just be a copy
73
+ of the original mel obtained from the padded audio.
74
+ - `rand_trunc` will select a random crop of the mel spectrogram.
75
+ padding (`str`, *optional*, defaults to `"repeatpad"`):
76
+ Padding pattern for shorter audio inputs. Three patterns were originally implemented:
77
+ - `repeatpad`: the audio is repeated, and then padded to fit the `max_length`.
78
+ - `repeat`: the audio is repeated and then cut to fit the `max_length`
79
+ - `pad`: the audio is padded.
80
+ """
81
+
82
+ model_input_names = ["input_features", "is_longer"]
83
+
84
+ def __init__(
85
+ self,
86
+ feature_size=64,
87
+ sampling_rate=48_000,
88
+ hop_length=480,
89
+ max_length_s=10,
90
+ fft_window_size=1024,
91
+ padding_value=0.0,
92
+ return_attention_mask=False, # pad inputs to max length with silence token (zero) and no attention mask
93
+ frequency_min: float = 0,
94
+ frequency_max: float = 14_000,
95
+ top_db: int = None,
96
+ truncation: str = "fusion",
97
+ padding: str = "repeatpad",
98
+ **kwargs,
99
+ ):
100
+ super().__init__(
101
+ feature_size=feature_size,
102
+ sampling_rate=sampling_rate,
103
+ padding_value=padding_value,
104
+ return_attention_mask=return_attention_mask,
105
+ **kwargs,
106
+ )
107
+ self.top_db = top_db
108
+ self.truncation = truncation
109
+ self.padding = padding
110
+ self.fft_window_size = fft_window_size
111
+ self.nb_frequency_bins = (fft_window_size >> 1) + 1
112
+ self.hop_length = hop_length
113
+ self.max_length_s = max_length_s
114
+ self.nb_max_samples = max_length_s * sampling_rate
115
+ self.sampling_rate = sampling_rate
116
+ self.frequency_min = frequency_min
117
+ self.frequency_max = frequency_max
118
+ self.mel_filters = mel_filter_bank(
119
+ num_frequency_bins=self.nb_frequency_bins,
120
+ num_mel_filters=feature_size,
121
+ min_frequency=frequency_min,
122
+ max_frequency=frequency_max,
123
+ sampling_rate=sampling_rate,
124
+ norm=None,
125
+ mel_scale="htk",
126
+ )
127
+ self.mel_filters_slaney = mel_filter_bank(
128
+ num_frequency_bins=self.nb_frequency_bins,
129
+ num_mel_filters=feature_size,
130
+ min_frequency=frequency_min,
131
+ max_frequency=frequency_max,
132
+ sampling_rate=sampling_rate,
133
+ norm="slaney",
134
+ mel_scale="slaney",
135
+ )
136
+
137
+ def to_dict(self) -> Dict[str, Any]:
138
+ """
139
+ Serializes this instance to a Python dictionary.
140
+
141
+ Returns:
142
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance, excpet for the
143
+ mel filter banks, which do not need to be saved or printed as they are too long.
144
+ """
145
+ output = copy.deepcopy(self.__dict__)
146
+ output["feature_extractor_type"] = self.__class__.__name__
147
+ if "mel_filters" in output:
148
+ del output["mel_filters"]
149
+ if "mel_filters_slaney" in output:
150
+ del output["mel_filters_slaney"]
151
+ return output
152
+
153
+ def _np_extract_fbank_features(self, waveform: np.array, mel_filters: Optional[np.array] = None) -> np.ndarray:
154
+ """
155
+ Compute the log-mel spectrogram of the provided `waveform` using the Hann window. In CLAP, two different filter
156
+ banks are used depending on the truncation pattern:
157
+ - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from
158
+ calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation`
159
+ is set to `"fusion"`.
160
+ - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used
161
+ `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original
162
+ implementation when the truncation mode is not `"fusion"`.
163
+ """
164
+ log_mel_spectrogram = spectrogram(
165
+ waveform,
166
+ window_function(self.fft_window_size, "hann"),
167
+ frame_length=self.fft_window_size,
168
+ hop_length=self.hop_length,
169
+ power=2.0,
170
+ mel_filters=mel_filters,
171
+ log_mel="dB",
172
+ )
173
+ return log_mel_spectrogram.T
174
+
175
+ def _random_mel_fusion(self, mel, total_frames, chunk_frames):
176
+ ranges = np.array_split(list(range(0, total_frames - chunk_frames + 1)), 3)
177
+ if len(ranges[1]) == 0:
178
+ # if the audio is too short, we just use the first chunk
179
+ ranges[1] = [0]
180
+ if len(ranges[2]) == 0:
181
+ # if the audio is too short, we just use the first chunk
182
+ ranges[2] = [0]
183
+ # randomly choose index for each part
184
+ idx_front = np.random.choice(ranges[0])
185
+ idx_middle = np.random.choice(ranges[1])
186
+ idx_back = np.random.choice(ranges[2])
187
+
188
+ mel_chunk_front = mel[idx_front : idx_front + chunk_frames, :]
189
+ mel_chunk_middle = mel[idx_middle : idx_middle + chunk_frames, :]
190
+ mel_chunk_back = mel[idx_back : idx_back + chunk_frames, :]
191
+
192
+ mel = torch.tensor(mel[None, None, :])
193
+ mel_shrink = torch.nn.functional.interpolate(
194
+ mel, size=[chunk_frames, 64], mode="bilinear", align_corners=False
195
+ )
196
+ mel_shrink = mel_shrink[0][0].numpy()
197
+ mel_fusion = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back], axis=0)
198
+ return mel_fusion
199
+
200
+ def _get_input_mel(self, waveform: np.array, max_length, truncation, padding) -> np.array:
201
+ """
202
+ Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments.
203
+ Four different path are possible:
204
+ - `truncation="fusion"` and the length of the waveform is greater than the max length: the mel spectrogram
205
+ will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram
206
+ are then stacked together. They will later be used for `feature_fusion`.
207
+ - `truncation="rand_trunc"` and the length of the waveform is smaller than the max length: the audio is
208
+ padded based on `padding`.
209
+ - `truncation="fusion"` and the length of the waveform is smaller than the max length: the audio is padded
210
+ based on `padding`, and is repeated `4` times.
211
+ - `truncation="rand_trunc"` and the length of the waveform is greater than the max length: the mel
212
+ spectrogram will be computed on a random crop of the waveform.
213
+
214
+ """
215
+ if waveform.shape[0] > max_length:
216
+ if truncation == "rand_trunc":
217
+ longer = True
218
+ # random crop to max_length (for compatibility) -> this should be handled by self.pad
219
+ overflow = len(waveform) - max_length
220
+ idx = np.random.randint(0, overflow + 1)
221
+ waveform = waveform[idx : idx + max_length]
222
+ input_mel = self._np_extract_fbank_features(waveform, self.mel_filters_slaney)[None, :]
223
+ elif truncation == "fusion":
224
+ mel = self._np_extract_fbank_features(waveform, self.mel_filters)
225
+ chunk_frames = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed
226
+ total_frames = mel.shape[0]
227
+ if chunk_frames == total_frames:
228
+ # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length.
229
+ # In this case, we just use the whole audio.
230
+ input_mel = np.stack([mel, mel, mel, mel], axis=0)
231
+ longer = False
232
+ else:
233
+ input_mel = self._random_mel_fusion(mel, total_frames, chunk_frames)
234
+ longer = True
235
+ else:
236
+ raise NotImplementedError(f"data_truncating {truncation} not implemented")
237
+
238
+ else:
239
+ longer = False
240
+ # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding
241
+ if waveform.shape[0] < max_length:
242
+ if padding == "repeat":
243
+ n_repeat = int(max_length / len(waveform))
244
+ waveform = np.tile(waveform, n_repeat + 1)[:max_length]
245
+ if padding == "repeatpad":
246
+ n_repeat = int(max_length / len(waveform))
247
+ waveform = np.tile(waveform, n_repeat)
248
+ waveform = np.pad(waveform, (0, max_length - waveform.shape[0]), mode="constant", constant_values=0)
249
+
250
+ if truncation == "fusion":
251
+ input_mel = self._np_extract_fbank_features(waveform, self.mel_filters)
252
+ input_mel = np.stack([input_mel, input_mel, input_mel, input_mel], axis=0)
253
+ else:
254
+ input_mel = self._np_extract_fbank_features(waveform, self.mel_filters_slaney)[None, :]
255
+
256
+ return input_mel, longer
257
+
258
+ def __call__(
259
+ self,
260
+ raw_speech: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]],
261
+ truncation: str = None,
262
+ padding: Optional[str] = None,
263
+ max_length: Optional[int] = None,
264
+ sampling_rate: Optional[int] = None,
265
+ return_tensors: Optional[Union[str, TensorType]] = None,
266
+ **kwargs,
267
+ ) -> BatchFeature:
268
+ """
269
+ Main method to featurize and prepare for the model one or several sequence(s).
270
+
271
+ Args:
272
+ raw_speech (`np.ndarray`, `List[float]`, `List[np.ndarray]`, `List[List[float]]`):
273
+ The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
274
+ values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
275
+ stereo, i.e. single float per timestep.
276
+ truncation (`str`, *optional*):
277
+ Truncation pattern for long audio inputs. Two patterns are available:
278
+ - `fusion` will use `_random_mel_fusion`, which stacks 3 random crops from the mel spectrogram and
279
+ a downsampled version of the entire mel spectrogram.
280
+ If `config.fusion` is set to True, shorter audios also need to to return 4 mels, which will just be a
281
+ copy of the original mel obtained from the padded audio.
282
+ - `rand_trunc` will select a random crop of the mel spectrogram.
283
+ padding (`str`, *optional*):
284
+ Padding pattern for shorter audio inputs. Three patterns were originally implemented:
285
+ - `repeatpad`: the audio is repeated, and then padded to fit the `max_length`.
286
+ - `repeat`: the audio is repeated and then cut to fit the `max_length`
287
+ - `pad`: the audio is padded.
288
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
289
+ If set, will return tensors instead of list of python integers. Acceptable values are:
290
+
291
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
292
+ - `'pt'`: Return PyTorch `torch.np.array` objects.
293
+ - `'np'`: Return Numpy `np.ndarray` objects.
294
+ sampling_rate (`int`, *optional*):
295
+ The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
296
+ `sampling_rate` at the forward call to prevent silent errors and allow automatic speech recognition
297
+ pipeline.
298
+ """
299
+ truncation = truncation if truncation is not None else self.truncation
300
+ padding = padding if padding else self.padding
301
+
302
+ if sampling_rate is not None:
303
+ if sampling_rate != self.sampling_rate:
304
+ raise ValueError(
305
+ f"The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"
306
+ f" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"
307
+ f" was sampled with {self.sampling_rate} and not {sampling_rate}."
308
+ )
309
+ else:
310
+ logger.warning(
311
+ "It is strongly recommended to pass the `sampling_rate` argument to this function. "
312
+ "Failing to do so can result in silent errors that might be hard to debug."
313
+ )
314
+
315
+ is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
316
+ if is_batched_numpy and len(raw_speech.shape) > 2:
317
+ raise ValueError(f"Only mono-channel audio is supported for input to {self}")
318
+ is_batched = is_batched_numpy or (
319
+ isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list)))
320
+ )
321
+
322
+ if is_batched:
323
+ raw_speech = [np.asarray(speech, dtype=np.float64) for speech in raw_speech]
324
+ elif not is_batched and not isinstance(raw_speech, np.ndarray):
325
+ raw_speech = np.asarray(raw_speech, dtype=np.float64)
326
+ elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
327
+ raw_speech = raw_speech.astype(np.float64)
328
+
329
+ # always return batch
330
+ if not is_batched:
331
+ raw_speech = [np.asarray(raw_speech)]
332
+
333
+ # convert to mel spectrogram, truncate and pad if needed.
334
+ padded_inputs = [
335
+ self._get_input_mel(waveform, max_length if max_length else self.nb_max_samples, truncation, padding)
336
+ for waveform in raw_speech
337
+ ]
338
+
339
+ input_mel = []
340
+ is_longer = []
341
+ for mel, longer in padded_inputs:
342
+ input_mel.append(mel)
343
+ is_longer.append(longer)
344
+
345
+ if truncation == "fusion" and sum(is_longer) == 0:
346
+ # if no audio is longer than 10s, then randomly select one audio to be longer
347
+ rand_idx = np.random.randint(0, len(input_mel))
348
+ is_longer[rand_idx] = True
349
+
350
+ if isinstance(input_mel[0], List):
351
+ input_mel = [np.asarray(feature, dtype=np.float64) for feature in input_mel]
352
+
353
+ # is_longer is a list of bool
354
+ is_longer = [[longer] for longer in is_longer]
355
+
356
+ input_features = {"input_features": input_mel, "is_longer": is_longer}
357
+ input_features = BatchFeature(input_features)
358
+
359
+ if return_tensors is not None:
360
+ input_features = input_features.convert_to_tensors(return_tensors)
361
+
362
+ return input_features
363
+
364
+
365
+ __all__ = ["ClapFeatureExtractor"]
vlmpy310/lib/python3.10/site-packages/transformers/models/clap/modeling_clap.py ADDED
The diff for this file is too large to render. See raw diff
 
vlmpy310/lib/python3.10/site-packages/transformers/models/clap/processing_clap.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Audio/Text processor class for CLAP
17
+ """
18
+
19
+ from ...processing_utils import ProcessorMixin
20
+ from ...tokenization_utils_base import BatchEncoding
21
+
22
+
23
+ class ClapProcessor(ProcessorMixin):
24
+ r"""
25
+ Constructs a CLAP processor which wraps a CLAP feature extractor and a RoBerta tokenizer into a single processor.
26
+
27
+ [`ClapProcessor`] offers all the functionalities of [`ClapFeatureExtractor`] and [`RobertaTokenizerFast`]. See the
28
+ [`~ClapProcessor.__call__`] and [`~ClapProcessor.decode`] for more information.
29
+
30
+ Args:
31
+ feature_extractor ([`ClapFeatureExtractor`]):
32
+ The audio processor is a required input.
33
+ tokenizer ([`RobertaTokenizerFast`]):
34
+ The tokenizer is a required input.
35
+ """
36
+
37
+ feature_extractor_class = "ClapFeatureExtractor"
38
+ tokenizer_class = ("RobertaTokenizer", "RobertaTokenizerFast")
39
+
40
+ def __init__(self, feature_extractor, tokenizer):
41
+ super().__init__(feature_extractor, tokenizer)
42
+
43
+ def __call__(self, text=None, audios=None, return_tensors=None, **kwargs):
44
+ """
45
+ Main method to prepare for the model one or several sequences(s) and audio(s). This method forwards the `text`
46
+ and `kwargs` arguments to RobertaTokenizerFast's [`~RobertaTokenizerFast.__call__`] if `text` is not `None` to
47
+ encode the text. To prepare the audio(s), this method forwards the `audios` and `kwrags` arguments to
48
+ ClapFeatureExtractor's [`~ClapFeatureExtractor.__call__`] if `audios` is not `None`. Please refer to the
49
+ doctsring of the above two methods for more information.
50
+
51
+ Args:
52
+ text (`str`, `List[str]`, `List[List[str]]`):
53
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
54
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
55
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
56
+ audios (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
57
+ The audio or batch of audios to be prepared. Each audio can be NumPy array or PyTorch tensor. In case
58
+ of a NumPy array/PyTorch tensor, each audio should be of shape (C, T), where C is a number of channels,
59
+ and T the sample length of the audio.
60
+
61
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
62
+ If set, will return tensors of a particular framework. Acceptable values are:
63
+
64
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
65
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
66
+ - `'np'`: Return NumPy `np.ndarray` objects.
67
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
68
+
69
+ Returns:
70
+ [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
71
+
72
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
73
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
74
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
75
+ `None`).
76
+ - **audio_features** -- Audio features to be fed to a model. Returned when `audios` is not `None`.
77
+ """
78
+ sampling_rate = kwargs.pop("sampling_rate", None)
79
+
80
+ if text is None and audios is None:
81
+ raise ValueError("You have to specify either text or audios. Both cannot be none.")
82
+
83
+ if text is not None:
84
+ encoding = self.tokenizer(text, return_tensors=return_tensors, **kwargs)
85
+
86
+ if audios is not None:
87
+ audio_features = self.feature_extractor(
88
+ audios, sampling_rate=sampling_rate, return_tensors=return_tensors, **kwargs
89
+ )
90
+
91
+ if text is not None and audios is not None:
92
+ encoding.update(audio_features)
93
+ return encoding
94
+ elif text is not None:
95
+ return encoding
96
+ else:
97
+ return BatchEncoding(data=dict(**audio_features), tensor_type=return_tensors)
98
+
99
+ def batch_decode(self, *args, **kwargs):
100
+ """
101
+ This method forwards all its arguments to RobertaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
102
+ refer to the docstring of this method for more information.
103
+ """
104
+ return self.tokenizer.batch_decode(*args, **kwargs)
105
+
106
+ def decode(self, *args, **kwargs):
107
+ """
108
+ This method forwards all its arguments to RobertaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer
109
+ to the docstring of this method for more information.
110
+ """
111
+ return self.tokenizer.decode(*args, **kwargs)
112
+
113
+ @property
114
+ def model_input_names(self):
115
+ tokenizer_input_names = self.tokenizer.model_input_names
116
+ feature_extractor_input_names = self.feature_extractor.model_input_names
117
+ return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names))
118
+
119
+
120
+ __all__ = ["ClapProcessor"]
vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/__init__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_distilbert import *
22
+ from .modeling_distilbert import *
23
+ from .modeling_flax_distilbert import *
24
+ from .modeling_tf_distilbert import *
25
+ from .tokenization_distilbert import *
26
+ from .tokenization_distilbert_fast import *
27
+ else:
28
+ import sys
29
+
30
+ _file = globals()["__file__"]
31
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (697 Bytes). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/configuration_distilbert.cpython-310.pyc ADDED
Binary file (5.49 kB). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/modeling_distilbert.cpython-310.pyc ADDED
Binary file (40.5 kB). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/modeling_flax_distilbert.cpython-310.pyc ADDED
Binary file (23 kB). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/modeling_tf_distilbert.cpython-310.pyc ADDED
Binary file (35.7 kB). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/tokenization_distilbert.cpython-310.pyc ADDED
Binary file (17.4 kB). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/tokenization_distilbert_fast.cpython-310.pyc ADDED
Binary file (6.88 kB). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/configuration_distilbert.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
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
+ """DistilBERT model configuration"""
16
+
17
+ from collections import OrderedDict
18
+ from typing import Mapping
19
+
20
+ from ...configuration_utils import PretrainedConfig
21
+ from ...onnx import OnnxConfig
22
+ from ...utils import logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ class DistilBertConfig(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`DistilBertModel`] or a [`TFDistilBertModel`]. It
31
+ is used to instantiate a DistilBERT model according to the specified arguments, defining the model architecture.
32
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the DistilBERT
33
+ [distilbert-base-uncased](https://huggingface.co/distilbert-base-uncased) architecture.
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 30522):
40
+ Vocabulary size of the DistilBERT model. Defines the number of different tokens that can be represented by
41
+ the `inputs_ids` passed when calling [`DistilBertModel`] or [`TFDistilBertModel`].
42
+ max_position_embeddings (`int`, *optional*, defaults to 512):
43
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
44
+ just in case (e.g., 512 or 1024 or 2048).
45
+ sinusoidal_pos_embds (`boolean`, *optional*, defaults to `False`):
46
+ Whether to use sinusoidal positional embeddings.
47
+ n_layers (`int`, *optional*, defaults to 6):
48
+ Number of hidden layers in the Transformer encoder.
49
+ n_heads (`int`, *optional*, defaults to 12):
50
+ Number of attention heads for each attention layer in the Transformer encoder.
51
+ dim (`int`, *optional*, defaults to 768):
52
+ Dimensionality of the encoder layers and the pooler layer.
53
+ hidden_dim (`int`, *optional*, defaults to 3072):
54
+ The size of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
55
+ dropout (`float`, *optional*, defaults to 0.1):
56
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
57
+ attention_dropout (`float`, *optional*, defaults to 0.1):
58
+ The dropout ratio for the attention probabilities.
59
+ activation (`str` or `Callable`, *optional*, defaults to `"gelu"`):
60
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
61
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ qa_dropout (`float`, *optional*, defaults to 0.1):
65
+ The dropout probabilities used in the question answering model [`DistilBertForQuestionAnswering`].
66
+ seq_classif_dropout (`float`, *optional*, defaults to 0.2):
67
+ The dropout probabilities used in the sequence classification and the multiple choice model
68
+ [`DistilBertForSequenceClassification`].
69
+
70
+ Examples:
71
+
72
+ ```python
73
+ >>> from transformers import DistilBertConfig, DistilBertModel
74
+
75
+ >>> # Initializing a DistilBERT configuration
76
+ >>> configuration = DistilBertConfig()
77
+
78
+ >>> # Initializing a model (with random weights) from the configuration
79
+ >>> model = DistilBertModel(configuration)
80
+
81
+ >>> # Accessing the model configuration
82
+ >>> configuration = model.config
83
+ ```"""
84
+
85
+ model_type = "distilbert"
86
+ attribute_map = {
87
+ "hidden_size": "dim",
88
+ "num_attention_heads": "n_heads",
89
+ "num_hidden_layers": "n_layers",
90
+ }
91
+
92
+ def __init__(
93
+ self,
94
+ vocab_size=30522,
95
+ max_position_embeddings=512,
96
+ sinusoidal_pos_embds=False,
97
+ n_layers=6,
98
+ n_heads=12,
99
+ dim=768,
100
+ hidden_dim=4 * 768,
101
+ dropout=0.1,
102
+ attention_dropout=0.1,
103
+ activation="gelu",
104
+ initializer_range=0.02,
105
+ qa_dropout=0.1,
106
+ seq_classif_dropout=0.2,
107
+ pad_token_id=0,
108
+ **kwargs,
109
+ ):
110
+ self.vocab_size = vocab_size
111
+ self.max_position_embeddings = max_position_embeddings
112
+ self.sinusoidal_pos_embds = sinusoidal_pos_embds
113
+ self.n_layers = n_layers
114
+ self.n_heads = n_heads
115
+ self.dim = dim
116
+ self.hidden_dim = hidden_dim
117
+ self.dropout = dropout
118
+ self.attention_dropout = attention_dropout
119
+ self.activation = activation
120
+ self.initializer_range = initializer_range
121
+ self.qa_dropout = qa_dropout
122
+ self.seq_classif_dropout = seq_classif_dropout
123
+ super().__init__(**kwargs, pad_token_id=pad_token_id)
124
+
125
+
126
+ class DistilBertOnnxConfig(OnnxConfig):
127
+ @property
128
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
129
+ if self.task == "multiple-choice":
130
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
131
+ else:
132
+ dynamic_axis = {0: "batch", 1: "sequence"}
133
+ return OrderedDict(
134
+ [
135
+ ("input_ids", dynamic_axis),
136
+ ("attention_mask", dynamic_axis),
137
+ ]
138
+ )
139
+
140
+
141
+ __all__ = ["DistilBertConfig", "DistilBertOnnxConfig"]
vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/modeling_distilbert.py ADDED
@@ -0,0 +1,1378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
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
+ """
17
+ PyTorch DistilBERT model adapted in part from Facebook, Inc XLM model (https://github.com/facebookresearch/XLM) and in
18
+ part from HuggingFace PyTorch version of Google AI Bert model (https://github.com/google-research/bert)
19
+ """
20
+
21
+ import math
22
+ from typing import Dict, List, Optional, Set, Tuple, Union
23
+
24
+ import numpy as np
25
+ import torch
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from ...activations import get_activation
30
+ from ...configuration_utils import PretrainedConfig
31
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
32
+ from ...modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa
33
+ from ...modeling_outputs import (
34
+ BaseModelOutput,
35
+ MaskedLMOutput,
36
+ MultipleChoiceModelOutput,
37
+ QuestionAnsweringModelOutput,
38
+ SequenceClassifierOutput,
39
+ TokenClassifierOutput,
40
+ )
41
+ from ...modeling_utils import PreTrainedModel
42
+ from ...pytorch_utils import (
43
+ apply_chunking_to_forward,
44
+ find_pruneable_heads_and_indices,
45
+ is_torch_greater_or_equal_than_2_2,
46
+ prune_linear_layer,
47
+ )
48
+ from ...utils import (
49
+ add_code_sample_docstrings,
50
+ add_start_docstrings,
51
+ add_start_docstrings_to_model_forward,
52
+ is_flash_attn_2_available,
53
+ is_flash_attn_greater_or_equal_2_10,
54
+ logging,
55
+ replace_return_docstrings,
56
+ )
57
+ from .configuration_distilbert import DistilBertConfig
58
+
59
+
60
+ if is_flash_attn_2_available():
61
+ from ...modeling_flash_attention_utils import _flash_attention_forward
62
+
63
+
64
+ logger = logging.get_logger(__name__)
65
+ _CHECKPOINT_FOR_DOC = "distilbert-base-uncased"
66
+ _CONFIG_FOR_DOC = "DistilBertConfig"
67
+
68
+
69
+ # UTILS AND BUILDING BLOCKS OF THE ARCHITECTURE #
70
+
71
+
72
+ def create_sinusoidal_embeddings(n_pos: int, dim: int, out: torch.Tensor):
73
+ if is_deepspeed_zero3_enabled():
74
+ import deepspeed
75
+
76
+ with deepspeed.zero.GatheredParameters(out, modifier_rank=0):
77
+ if torch.distributed.get_rank() == 0:
78
+ _create_sinusoidal_embeddings(n_pos=n_pos, dim=dim, out=out)
79
+ else:
80
+ _create_sinusoidal_embeddings(n_pos=n_pos, dim=dim, out=out)
81
+
82
+
83
+ def _create_sinusoidal_embeddings(n_pos: int, dim: int, out: torch.Tensor):
84
+ position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)])
85
+ out.requires_grad = False
86
+ out[:, 0::2] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
87
+ out[:, 1::2] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
88
+ out.detach_()
89
+
90
+
91
+ class Embeddings(nn.Module):
92
+ def __init__(self, config: PretrainedConfig):
93
+ super().__init__()
94
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.dim, padding_idx=config.pad_token_id)
95
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.dim)
96
+
97
+ self.LayerNorm = nn.LayerNorm(config.dim, eps=1e-12)
98
+ self.dropout = nn.Dropout(config.dropout)
99
+ self.register_buffer(
100
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
101
+ )
102
+
103
+ def forward(self, input_ids: torch.Tensor, input_embeds: Optional[torch.Tensor] = None) -> torch.Tensor:
104
+ """
105
+ Parameters:
106
+ input_ids (torch.Tensor):
107
+ torch.tensor(bs, max_seq_length) The token ids to embed.
108
+ input_embeds (*optional*, torch.Tensor):
109
+ The pre-computed word embeddings. Can only be passed if the input ids are `None`.
110
+
111
+
112
+ Returns: torch.tensor(bs, max_seq_length, dim) The embedded tokens (plus position embeddings, no token_type
113
+ embeddings)
114
+ """
115
+ if input_ids is not None:
116
+ input_embeds = self.word_embeddings(input_ids) # (bs, max_seq_length, dim)
117
+
118
+ seq_length = input_embeds.size(1)
119
+
120
+ # Setting the position-ids to the registered buffer in constructor, it helps
121
+ # when tracing the model without passing position-ids, solves
122
+ # isues similar to issue #5664
123
+ if hasattr(self, "position_ids"):
124
+ position_ids = self.position_ids[:, :seq_length]
125
+ else:
126
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device) # (max_seq_length)
127
+ position_ids = position_ids.unsqueeze(0).expand_as(input_ids) # (bs, max_seq_length)
128
+
129
+ position_embeddings = self.position_embeddings(position_ids) # (bs, max_seq_length, dim)
130
+
131
+ embeddings = input_embeds + position_embeddings # (bs, max_seq_length, dim)
132
+ embeddings = self.LayerNorm(embeddings) # (bs, max_seq_length, dim)
133
+ embeddings = self.dropout(embeddings) # (bs, max_seq_length, dim)
134
+ return embeddings
135
+
136
+
137
+ class MultiHeadSelfAttention(nn.Module):
138
+ def __init__(self, config: PretrainedConfig):
139
+ super().__init__()
140
+ self.config = config
141
+
142
+ self.n_heads = config.n_heads
143
+ self.dim = config.dim
144
+ self.dropout = nn.Dropout(p=config.attention_dropout)
145
+ self.is_causal = False
146
+
147
+ # Have an even number of multi heads that divide the dimensions
148
+ if self.dim % self.n_heads != 0:
149
+ # Raise value errors for even multi-head attention nodes
150
+ raise ValueError(f"self.n_heads: {self.n_heads} must divide self.dim: {self.dim} evenly")
151
+
152
+ self.q_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
153
+ self.k_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
154
+ self.v_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
155
+ self.out_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
156
+
157
+ self.pruned_heads: Set[int] = set()
158
+ self.attention_head_size = self.dim // self.n_heads
159
+
160
+ def prune_heads(self, heads: List[int]):
161
+ if len(heads) == 0:
162
+ return
163
+ heads, index = find_pruneable_heads_and_indices(
164
+ heads, self.n_heads, self.attention_head_size, self.pruned_heads
165
+ )
166
+ # Prune linear layers
167
+ self.q_lin = prune_linear_layer(self.q_lin, index)
168
+ self.k_lin = prune_linear_layer(self.k_lin, index)
169
+ self.v_lin = prune_linear_layer(self.v_lin, index)
170
+ self.out_lin = prune_linear_layer(self.out_lin, index, dim=1)
171
+ # Update hyper params
172
+ self.n_heads = self.n_heads - len(heads)
173
+ self.dim = self.attention_head_size * self.n_heads
174
+ self.pruned_heads = self.pruned_heads.union(heads)
175
+
176
+ def forward(
177
+ self,
178
+ query: torch.Tensor,
179
+ key: torch.Tensor,
180
+ value: torch.Tensor,
181
+ mask: torch.Tensor,
182
+ head_mask: Optional[torch.Tensor] = None,
183
+ output_attentions: bool = False,
184
+ ) -> Tuple[torch.Tensor, ...]:
185
+ """
186
+ Parameters:
187
+ query: torch.tensor(bs, seq_length, dim)
188
+ key: torch.tensor(bs, seq_length, dim)
189
+ value: torch.tensor(bs, seq_length, dim)
190
+ mask: torch.tensor(bs, seq_length)
191
+
192
+ Returns:
193
+ weights: torch.tensor(bs, n_heads, seq_length, seq_length) Attention weights context: torch.tensor(bs,
194
+ seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
195
+ """
196
+ bs, q_length, dim = query.size()
197
+ k_length = key.size(1)
198
+ # assert dim == self.dim, f'Dimensions do not match: {dim} input vs {self.dim} configured'
199
+ # assert key.size() == value.size()
200
+
201
+ dim_per_head = self.dim // self.n_heads
202
+
203
+ mask_reshp = (bs, 1, 1, k_length)
204
+
205
+ def shape(x: torch.Tensor) -> torch.Tensor:
206
+ """separate heads"""
207
+ return x.view(bs, -1, self.n_heads, dim_per_head).transpose(1, 2)
208
+
209
+ def unshape(x: torch.Tensor) -> torch.Tensor:
210
+ """group heads"""
211
+ return x.transpose(1, 2).contiguous().view(bs, -1, self.n_heads * dim_per_head)
212
+
213
+ q = shape(self.q_lin(query)) # (bs, n_heads, q_length, dim_per_head)
214
+ k = shape(self.k_lin(key)) # (bs, n_heads, k_length, dim_per_head)
215
+ v = shape(self.v_lin(value)) # (bs, n_heads, k_length, dim_per_head)
216
+
217
+ q = q / math.sqrt(dim_per_head) # (bs, n_heads, q_length, dim_per_head)
218
+ scores = torch.matmul(q, k.transpose(2, 3)) # (bs, n_heads, q_length, k_length)
219
+ mask = (mask == 0).view(mask_reshp).expand_as(scores) # (bs, n_heads, q_length, k_length)
220
+ scores = scores.masked_fill(
221
+ mask, torch.tensor(torch.finfo(scores.dtype).min)
222
+ ) # (bs, n_heads, q_length, k_length)
223
+
224
+ weights = nn.functional.softmax(scores, dim=-1) # (bs, n_heads, q_length, k_length)
225
+ weights = self.dropout(weights) # (bs, n_heads, q_length, k_length)
226
+
227
+ # Mask heads if we want to
228
+ if head_mask is not None:
229
+ weights = weights * head_mask
230
+
231
+ context = torch.matmul(weights, v) # (bs, n_heads, q_length, dim_per_head)
232
+ context = unshape(context) # (bs, q_length, dim)
233
+ context = self.out_lin(context) # (bs, q_length, dim)
234
+
235
+ if output_attentions:
236
+ return (context, weights)
237
+ else:
238
+ return (context,)
239
+
240
+
241
+ class DistilBertFlashAttention2(MultiHeadSelfAttention):
242
+ """
243
+ DistilBert flash attention module. This module inherits from `MultiHeadSelfAttention` as the weights of the module
244
+ stays untouched. The only required change would be on the forward pass where it needs to correctly call the public
245
+ API of flash attention and deal with padding tokens in case the input contains any of them.
246
+ """
247
+
248
+ def __init__(self, *args, **kwargs):
249
+ super().__init__(*args, **kwargs)
250
+
251
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
252
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
253
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
254
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
255
+
256
+ def forward(
257
+ self,
258
+ query: torch.Tensor,
259
+ key: torch.Tensor,
260
+ value: torch.Tensor,
261
+ mask: torch.Tensor,
262
+ head_mask: Optional[torch.Tensor] = None,
263
+ output_attentions: bool = False,
264
+ ) -> Tuple[torch.Tensor, ...]:
265
+ """
266
+ Parameters:
267
+ query: torch.tensor(bs, seq_length, dim)
268
+ key: torch.tensor(bs, seq_length, dim)
269
+ value: torch.tensor(bs, seq_length, dim)
270
+ mask: torch.tensor(bs, seq_length)
271
+
272
+ Returns:
273
+ weights: torch.tensor(bs, n_heads, seq_length, seq_length) Attention weights context: torch.tensor(bs,
274
+ seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
275
+ """
276
+ batch_size, q_length, dim = query.size()
277
+
278
+ dim_per_head = self.dim // self.n_heads
279
+
280
+ def reshape(x: torch.Tensor) -> torch.Tensor:
281
+ """separate heads"""
282
+ return x.view(batch_size, -1, self.n_heads, dim_per_head)
283
+
284
+ # Flash attention requires the input to have the shape
285
+ # batch_size x seq_length x head_dim x hidden_dim
286
+ query_states = reshape(self.q_lin(query))
287
+ key_states = reshape(self.k_lin(key))
288
+ value_states = reshape(self.v_lin(value))
289
+
290
+ attn_dropout = self.config.attention_dropout if self.training else 0.0
291
+
292
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
293
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
294
+ # cast them back in the correct dtype just to be sure everything works as expected.
295
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
296
+ # in fp32. (LlamaRMSNorm handles it correctly)
297
+
298
+ if query_states.dtype == torch.float32:
299
+ if torch.is_autocast_enabled():
300
+ target_dtype = torch.get_autocast_gpu_dtype()
301
+ # Handle the case where the model is quantized
302
+ elif hasattr(self.config, "_pre_quantization_dtype"):
303
+ target_dtype = self.config._pre_quantization_dtype
304
+ else:
305
+ target_dtype = self.q_lin.weight.dtype
306
+
307
+ logger.warning_once(
308
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
309
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
310
+ f" {target_dtype}."
311
+ )
312
+
313
+ query_states = query_states.to(target_dtype)
314
+ key_states = key_states.to(target_dtype)
315
+ value_states = value_states.to(target_dtype)
316
+
317
+ attn_weights = _flash_attention_forward(
318
+ query_states,
319
+ key_states,
320
+ value_states,
321
+ mask,
322
+ q_length,
323
+ dropout=attn_dropout,
324
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
325
+ is_causal=self.is_causal,
326
+ )
327
+
328
+ attn_weights_reshaped = attn_weights.reshape(batch_size, q_length, self.n_heads * dim_per_head)
329
+ attn_output = self.out_lin(attn_weights_reshaped)
330
+
331
+ if output_attentions:
332
+ return (attn_output, attn_weights)
333
+ else:
334
+ return (attn_output,)
335
+
336
+
337
+ class DistilBertSdpaAttention(MultiHeadSelfAttention):
338
+ def __init__(self, config: PretrainedConfig):
339
+ super().__init__(config=config)
340
+ self.dropout_prob = config.attention_dropout
341
+ self.require_contiguous_qkv = not is_torch_greater_or_equal_than_2_2
342
+
343
+ def forward(
344
+ self,
345
+ query: torch.Tensor,
346
+ key: torch.Tensor,
347
+ value: torch.Tensor,
348
+ mask: torch.Tensor,
349
+ head_mask: Optional[torch.Tensor] = None,
350
+ output_attentions: bool = False,
351
+ ) -> Tuple[torch.Tensor, ...]:
352
+ """
353
+ Parameters:
354
+ query: torch.tensor(bs, seq_length, dim)
355
+ key: torch.tensor(bs, seq_length, dim)
356
+ value: torch.tensor(bs, seq_length, dim)
357
+ mask: torch.tensor(bs, seq_length)
358
+
359
+ Returns:
360
+ weights: torch.tensor(bs, n_heads, seq_length, seq_length) Attention weights context: torch.tensor(bs,
361
+ seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
362
+ """
363
+ if output_attentions or head_mask is not None:
364
+ logger.warning_once(
365
+ "DistilBertSdpaAttention is used but `torch.nn.functional.scaled_dot_product_attention` does not support"
366
+ " `output_attentions=True` or `head_mask`. Falling back to the manual attention implementation, but specifying"
367
+ " the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be"
368
+ ' removed using the argument `attn_implementation="eager"` when loading the model.'
369
+ )
370
+ return super().forward(
371
+ query,
372
+ key,
373
+ value,
374
+ mask,
375
+ head_mask,
376
+ output_attentions,
377
+ )
378
+
379
+ batch_size, _, _ = query.size()
380
+ dim_per_head = self.dim // self.n_heads
381
+
382
+ def shape(x: torch.Tensor) -> torch.Tensor:
383
+ """separate heads"""
384
+ return x.view(batch_size, -1, self.n_heads, dim_per_head).transpose(1, 2)
385
+
386
+ def unshape(x: torch.Tensor) -> torch.Tensor:
387
+ """group heads"""
388
+ return x.transpose(1, 2).contiguous().view(batch_size, -1, self.n_heads * dim_per_head)
389
+
390
+ q = shape(self.q_lin(query)) # (bs, n_heads, q_length, dim_per_head)
391
+ k = shape(self.k_lin(key)) # (bs, n_heads, k_length, dim_per_head)
392
+ v = shape(self.v_lin(value)) # (bs, n_heads, k_length, dim_per_head)
393
+
394
+ # SDPA with memory-efficient backend is broken in torch==2.1.2 when using non-contiguous inputs and a custom
395
+ # attn_mask, so we need to call `.contiguous()` here. This was fixed in torch==2.2.0.
396
+ # Reference: https://github.com/pytorch/pytorch/issues/112577
397
+ if self.require_contiguous_qkv and q.device.type == "cuda" and mask is not None:
398
+ q = q.contiguous()
399
+ k = k.contiguous()
400
+ v = v.contiguous()
401
+
402
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
403
+ q,
404
+ k,
405
+ v,
406
+ attn_mask=mask,
407
+ dropout_p=self.dropout_prob if self.training else 0.0,
408
+ is_causal=False,
409
+ )
410
+
411
+ attn_output = unshape(attn_output)
412
+ attn_output = self.out_lin(attn_output)
413
+
414
+ return (attn_output,)
415
+
416
+
417
+ class FFN(nn.Module):
418
+ def __init__(self, config: PretrainedConfig):
419
+ super().__init__()
420
+ self.dropout = nn.Dropout(p=config.dropout)
421
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
422
+ self.seq_len_dim = 1
423
+ self.lin1 = nn.Linear(in_features=config.dim, out_features=config.hidden_dim)
424
+ self.lin2 = nn.Linear(in_features=config.hidden_dim, out_features=config.dim)
425
+ self.activation = get_activation(config.activation)
426
+
427
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
428
+ return apply_chunking_to_forward(self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, input)
429
+
430
+ def ff_chunk(self, input: torch.Tensor) -> torch.Tensor:
431
+ x = self.lin1(input)
432
+ x = self.activation(x)
433
+ x = self.lin2(x)
434
+ x = self.dropout(x)
435
+ return x
436
+
437
+
438
+ DISTILBERT_ATTENTION_CLASSES = {
439
+ "eager": MultiHeadSelfAttention,
440
+ "flash_attention_2": DistilBertFlashAttention2,
441
+ "sdpa": DistilBertSdpaAttention,
442
+ }
443
+
444
+
445
+ class TransformerBlock(nn.Module):
446
+ def __init__(self, config: PretrainedConfig):
447
+ super().__init__()
448
+
449
+ # Have an even number of Configure multi-heads
450
+ if config.dim % config.n_heads != 0:
451
+ raise ValueError(f"config.n_heads {config.n_heads} must divide config.dim {config.dim} evenly")
452
+
453
+ self.attention = DISTILBERT_ATTENTION_CLASSES[config._attn_implementation](config)
454
+ self.sa_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)
455
+
456
+ self.ffn = FFN(config)
457
+ self.output_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)
458
+
459
+ def forward(
460
+ self,
461
+ x: torch.Tensor,
462
+ attn_mask: Optional[torch.Tensor] = None,
463
+ head_mask: Optional[torch.Tensor] = None,
464
+ output_attentions: bool = False,
465
+ ) -> Tuple[torch.Tensor, ...]:
466
+ """
467
+ Parameters:
468
+ x: torch.tensor(bs, seq_length, dim)
469
+ attn_mask: torch.tensor(bs, seq_length)
470
+
471
+ Returns:
472
+ sa_weights: torch.tensor(bs, n_heads, seq_length, seq_length) The attention weights ffn_output:
473
+ torch.tensor(bs, seq_length, dim) The output of the transformer block contextualization.
474
+ """
475
+ # Self-Attention
476
+ sa_output = self.attention(
477
+ query=x,
478
+ key=x,
479
+ value=x,
480
+ mask=attn_mask,
481
+ head_mask=head_mask,
482
+ output_attentions=output_attentions,
483
+ )
484
+ if output_attentions:
485
+ sa_output, sa_weights = sa_output # (bs, seq_length, dim), (bs, n_heads, seq_length, seq_length)
486
+ else: # To handle these `output_attentions` or `output_hidden_states` cases returning tuples
487
+ if type(sa_output) is not tuple:
488
+ raise TypeError(f"sa_output must be a tuple but it is {type(sa_output)} type")
489
+
490
+ sa_output = sa_output[0]
491
+ sa_output = self.sa_layer_norm(sa_output + x) # (bs, seq_length, dim)
492
+
493
+ # Feed Forward Network
494
+ ffn_output = self.ffn(sa_output) # (bs, seq_length, dim)
495
+ ffn_output: torch.Tensor = self.output_layer_norm(ffn_output + sa_output) # (bs, seq_length, dim)
496
+
497
+ output = (ffn_output,)
498
+ if output_attentions:
499
+ output = (sa_weights,) + output
500
+ return output
501
+
502
+
503
+ class Transformer(nn.Module):
504
+ def __init__(self, config: PretrainedConfig):
505
+ super().__init__()
506
+ self.n_layers = config.n_layers
507
+ self.layer = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layers)])
508
+ self.gradient_checkpointing = False
509
+
510
+ def forward(
511
+ self,
512
+ x: torch.Tensor,
513
+ attn_mask: Optional[torch.Tensor] = None,
514
+ head_mask: Optional[torch.Tensor] = None,
515
+ output_attentions: bool = False,
516
+ output_hidden_states: bool = False,
517
+ return_dict: Optional[bool] = None,
518
+ ) -> Union[BaseModelOutput, Tuple[torch.Tensor, ...]]: # docstyle-ignore
519
+ """
520
+ Parameters:
521
+ x: torch.tensor(bs, seq_length, dim) Input sequence embedded.
522
+ attn_mask: torch.tensor(bs, seq_length) Attention mask on the sequence.
523
+
524
+ Returns:
525
+ hidden_state: torch.tensor(bs, seq_length, dim) Sequence of hidden states in the last (top)
526
+ layer all_hidden_states: Tuple[torch.tensor(bs, seq_length, dim)]
527
+ Tuple of length n_layers with the hidden states from each layer.
528
+ Optional: only if output_hidden_states=True
529
+ all_attentions: Tuple[torch.tensor(bs, n_heads, seq_length, seq_length)]
530
+ Tuple of length n_layers with the attention weights from each layer
531
+ Optional: only if output_attentions=True
532
+ """
533
+ all_hidden_states = () if output_hidden_states else None
534
+ all_attentions = () if output_attentions else None
535
+
536
+ hidden_state = x
537
+ for i, layer_module in enumerate(self.layer):
538
+ if output_hidden_states:
539
+ all_hidden_states = all_hidden_states + (hidden_state,)
540
+
541
+ if self.gradient_checkpointing and self.training:
542
+ layer_outputs = self._gradient_checkpointing_func(
543
+ layer_module.__call__,
544
+ hidden_state,
545
+ attn_mask,
546
+ head_mask[i],
547
+ output_attentions,
548
+ )
549
+ else:
550
+ layer_outputs = layer_module(
551
+ hidden_state,
552
+ attn_mask,
553
+ head_mask[i],
554
+ output_attentions,
555
+ )
556
+
557
+ hidden_state = layer_outputs[-1]
558
+
559
+ if output_attentions:
560
+ if len(layer_outputs) != 2:
561
+ raise ValueError(f"The length of the layer_outputs should be 2, but it is {len(layer_outputs)}")
562
+
563
+ attentions = layer_outputs[0]
564
+ all_attentions = all_attentions + (attentions,)
565
+ else:
566
+ if len(layer_outputs) != 1:
567
+ raise ValueError(f"The length of the layer_outputs should be 1, but it is {len(layer_outputs)}")
568
+
569
+ # Add last layer
570
+ if output_hidden_states:
571
+ all_hidden_states = all_hidden_states + (hidden_state,)
572
+
573
+ if not return_dict:
574
+ return tuple(v for v in [hidden_state, all_hidden_states, all_attentions] if v is not None)
575
+ return BaseModelOutput(
576
+ last_hidden_state=hidden_state, hidden_states=all_hidden_states, attentions=all_attentions
577
+ )
578
+
579
+
580
+ # INTERFACE FOR ENCODER AND TASK SPECIFIC MODEL #
581
+ class DistilBertPreTrainedModel(PreTrainedModel):
582
+ """
583
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
584
+ models.
585
+ """
586
+
587
+ config_class = DistilBertConfig
588
+ load_tf_weights = None
589
+ base_model_prefix = "distilbert"
590
+ supports_gradient_checkpointing = True
591
+ _supports_flash_attn_2 = True
592
+ _supports_sdpa = True
593
+
594
+ def _init_weights(self, module: nn.Module):
595
+ """Initialize the weights."""
596
+ if isinstance(module, nn.Linear):
597
+ # Slightly different from the TF version which uses truncated_normal for initialization
598
+ # cf https://github.com/pytorch/pytorch/pull/5617
599
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
600
+ if module.bias is not None:
601
+ module.bias.data.zero_()
602
+ elif isinstance(module, nn.Embedding):
603
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
604
+ if module.padding_idx is not None:
605
+ module.weight.data[module.padding_idx].zero_()
606
+ elif isinstance(module, nn.LayerNorm):
607
+ module.bias.data.zero_()
608
+ module.weight.data.fill_(1.0)
609
+ elif isinstance(module, Embeddings) and self.config.sinusoidal_pos_embds:
610
+ create_sinusoidal_embeddings(
611
+ self.config.max_position_embeddings, self.config.dim, module.position_embeddings.weight
612
+ )
613
+
614
+
615
+ DISTILBERT_START_DOCSTRING = r"""
616
+
617
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
618
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
619
+ etc.)
620
+
621
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
622
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
623
+ and behavior.
624
+
625
+ Parameters:
626
+ config ([`DistilBertConfig`]): Model configuration class with all the parameters of the model.
627
+ Initializing with a config file does not load the weights associated with the model, only the
628
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
629
+ """
630
+
631
+ DISTILBERT_INPUTS_DOCSTRING = r"""
632
+ Args:
633
+ input_ids (`torch.LongTensor` of shape `({0})`):
634
+ Indices of input sequence tokens in the vocabulary.
635
+
636
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
637
+ [`PreTrainedTokenizer.__call__`] for details.
638
+
639
+ [What are input IDs?](../glossary#input-ids)
640
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
641
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
642
+
643
+ - 1 for tokens that are **not masked**,
644
+ - 0 for tokens that are **masked**.
645
+
646
+ [What are attention masks?](../glossary#attention-mask)
647
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
648
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
649
+
650
+ - 1 indicates the head is **not masked**,
651
+ - 0 indicates the head is **masked**.
652
+
653
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
654
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
655
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
656
+ model's internal embedding lookup matrix.
657
+ output_attentions (`bool`, *optional*):
658
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
659
+ tensors for more detail.
660
+ output_hidden_states (`bool`, *optional*):
661
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
662
+ more detail.
663
+ return_dict (`bool`, *optional*):
664
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
665
+ """
666
+
667
+
668
+ @add_start_docstrings(
669
+ "The bare DistilBERT encoder/transformer outputting raw hidden-states without any specific head on top.",
670
+ DISTILBERT_START_DOCSTRING,
671
+ )
672
+ class DistilBertModel(DistilBertPreTrainedModel):
673
+ def __init__(self, config: PretrainedConfig):
674
+ super().__init__(config)
675
+
676
+ self.embeddings = Embeddings(config) # Embeddings
677
+ self.transformer = Transformer(config) # Encoder
678
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
679
+ self._use_sdpa = config._attn_implementation == "sdpa"
680
+
681
+ # Initialize weights and apply final processing
682
+ self.post_init()
683
+
684
+ def get_position_embeddings(self) -> nn.Embedding:
685
+ """
686
+ Returns the position embeddings
687
+ """
688
+ return self.embeddings.position_embeddings
689
+
690
+ def resize_position_embeddings(self, new_num_position_embeddings: int):
691
+ """
692
+ Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
693
+
694
+ Arguments:
695
+ new_num_position_embeddings (`int`):
696
+ The number of new position embedding matrix. If position embeddings are learned, increasing the size
697
+ will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
698
+ end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
699
+ size will add correct vectors at the end following the position encoding algorithm, whereas reducing
700
+ the size will remove vectors from the end.
701
+ """
702
+ num_position_embeds_diff = new_num_position_embeddings - self.config.max_position_embeddings
703
+
704
+ # no resizing needs to be done if the length stays the same
705
+ if num_position_embeds_diff == 0:
706
+ return
707
+
708
+ logger.info(f"Setting `config.max_position_embeddings={new_num_position_embeddings}`...")
709
+ self.config.max_position_embeddings = new_num_position_embeddings
710
+
711
+ old_position_embeddings_weight = self.embeddings.position_embeddings.weight.clone()
712
+
713
+ self.embeddings.position_embeddings = nn.Embedding(self.config.max_position_embeddings, self.config.dim)
714
+
715
+ if self.config.sinusoidal_pos_embds:
716
+ create_sinusoidal_embeddings(
717
+ n_pos=self.config.max_position_embeddings, dim=self.config.dim, out=self.position_embeddings.weight
718
+ )
719
+ else:
720
+ with torch.no_grad():
721
+ if num_position_embeds_diff > 0:
722
+ self.embeddings.position_embeddings.weight[:-num_position_embeds_diff] = nn.Parameter(
723
+ old_position_embeddings_weight
724
+ )
725
+ else:
726
+ self.embeddings.position_embeddings.weight = nn.Parameter(
727
+ old_position_embeddings_weight[:num_position_embeds_diff]
728
+ )
729
+ # move position_embeddings to correct device
730
+ self.embeddings.position_embeddings.to(self.device)
731
+
732
+ def get_input_embeddings(self) -> nn.Embedding:
733
+ return self.embeddings.word_embeddings
734
+
735
+ def set_input_embeddings(self, new_embeddings: nn.Embedding):
736
+ self.embeddings.word_embeddings = new_embeddings
737
+
738
+ def _prune_heads(self, heads_to_prune: Dict[int, List[List[int]]]):
739
+ """
740
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
741
+ class PreTrainedModel
742
+ """
743
+ for layer, heads in heads_to_prune.items():
744
+ self.transformer.layer[layer].attention.prune_heads(heads)
745
+
746
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, num_choices"))
747
+ @add_code_sample_docstrings(
748
+ checkpoint=_CHECKPOINT_FOR_DOC,
749
+ output_type=BaseModelOutput,
750
+ config_class=_CONFIG_FOR_DOC,
751
+ )
752
+ def forward(
753
+ self,
754
+ input_ids: Optional[torch.Tensor] = None,
755
+ attention_mask: Optional[torch.Tensor] = None,
756
+ head_mask: Optional[torch.Tensor] = None,
757
+ inputs_embeds: Optional[torch.Tensor] = None,
758
+ output_attentions: Optional[bool] = None,
759
+ output_hidden_states: Optional[bool] = None,
760
+ return_dict: Optional[bool] = None,
761
+ ) -> Union[BaseModelOutput, Tuple[torch.Tensor, ...]]:
762
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
763
+ output_hidden_states = (
764
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
765
+ )
766
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
767
+
768
+ if input_ids is not None and inputs_embeds is not None:
769
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
770
+ elif input_ids is not None:
771
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
772
+ input_shape = input_ids.size()
773
+ elif inputs_embeds is not None:
774
+ input_shape = inputs_embeds.size()[:-1]
775
+ else:
776
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
777
+
778
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
779
+
780
+ head_mask_is_none = head_mask is None
781
+ # Prepare head mask if needed
782
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
783
+
784
+ embeddings = self.embeddings(input_ids, inputs_embeds) # (bs, seq_length, dim)
785
+
786
+ if self._use_flash_attention_2:
787
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
788
+ else:
789
+ if attention_mask is None:
790
+ attention_mask = torch.ones(input_shape, device=device) # (bs, seq_length)
791
+
792
+ if self._use_sdpa and head_mask_is_none and not output_attentions:
793
+ attention_mask = _prepare_4d_attention_mask_for_sdpa(
794
+ attention_mask, embeddings.dtype, tgt_len=input_shape[1]
795
+ )
796
+
797
+ return self.transformer(
798
+ x=embeddings,
799
+ attn_mask=attention_mask,
800
+ head_mask=head_mask,
801
+ output_attentions=output_attentions,
802
+ output_hidden_states=output_hidden_states,
803
+ return_dict=return_dict,
804
+ )
805
+
806
+
807
+ @add_start_docstrings(
808
+ """DistilBert Model with a `masked language modeling` head on top.""",
809
+ DISTILBERT_START_DOCSTRING,
810
+ )
811
+ class DistilBertForMaskedLM(DistilBertPreTrainedModel):
812
+ _tied_weights_keys = ["vocab_projector.weight"]
813
+
814
+ def __init__(self, config: PretrainedConfig):
815
+ super().__init__(config)
816
+
817
+ self.activation = get_activation(config.activation)
818
+
819
+ self.distilbert = DistilBertModel(config)
820
+ self.vocab_transform = nn.Linear(config.dim, config.dim)
821
+ self.vocab_layer_norm = nn.LayerNorm(config.dim, eps=1e-12)
822
+ self.vocab_projector = nn.Linear(config.dim, config.vocab_size)
823
+
824
+ # Initialize weights and apply final processing
825
+ self.post_init()
826
+
827
+ self.mlm_loss_fct = nn.CrossEntropyLoss()
828
+
829
+ def get_position_embeddings(self) -> nn.Embedding:
830
+ """
831
+ Returns the position embeddings
832
+ """
833
+ return self.distilbert.get_position_embeddings()
834
+
835
+ def resize_position_embeddings(self, new_num_position_embeddings: int):
836
+ """
837
+ Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
838
+
839
+ Arguments:
840
+ new_num_position_embeddings (`int`):
841
+ The number of new position embedding matrix. If position embeddings are learned, increasing the size
842
+ will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
843
+ end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
844
+ size will add correct vectors at the end following the position encoding algorithm, whereas reducing
845
+ the size will remove vectors from the end.
846
+ """
847
+ self.distilbert.resize_position_embeddings(new_num_position_embeddings)
848
+
849
+ def get_output_embeddings(self) -> nn.Module:
850
+ return self.vocab_projector
851
+
852
+ def set_output_embeddings(self, new_embeddings: nn.Module):
853
+ self.vocab_projector = new_embeddings
854
+
855
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, num_choices"))
856
+ @add_code_sample_docstrings(
857
+ checkpoint=_CHECKPOINT_FOR_DOC,
858
+ output_type=MaskedLMOutput,
859
+ config_class=_CONFIG_FOR_DOC,
860
+ )
861
+ def forward(
862
+ self,
863
+ input_ids: Optional[torch.Tensor] = None,
864
+ attention_mask: Optional[torch.Tensor] = None,
865
+ head_mask: Optional[torch.Tensor] = None,
866
+ inputs_embeds: Optional[torch.Tensor] = None,
867
+ labels: Optional[torch.LongTensor] = None,
868
+ output_attentions: Optional[bool] = None,
869
+ output_hidden_states: Optional[bool] = None,
870
+ return_dict: Optional[bool] = None,
871
+ ) -> Union[MaskedLMOutput, Tuple[torch.Tensor, ...]]:
872
+ r"""
873
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
874
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
875
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
876
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
877
+ """
878
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
879
+
880
+ dlbrt_output = self.distilbert(
881
+ input_ids=input_ids,
882
+ attention_mask=attention_mask,
883
+ head_mask=head_mask,
884
+ inputs_embeds=inputs_embeds,
885
+ output_attentions=output_attentions,
886
+ output_hidden_states=output_hidden_states,
887
+ return_dict=return_dict,
888
+ )
889
+ hidden_states = dlbrt_output[0] # (bs, seq_length, dim)
890
+ prediction_logits = self.vocab_transform(hidden_states) # (bs, seq_length, dim)
891
+ prediction_logits = self.activation(prediction_logits) # (bs, seq_length, dim)
892
+ prediction_logits = self.vocab_layer_norm(prediction_logits) # (bs, seq_length, dim)
893
+ prediction_logits = self.vocab_projector(prediction_logits) # (bs, seq_length, vocab_size)
894
+
895
+ mlm_loss = None
896
+ if labels is not None:
897
+ mlm_loss = self.mlm_loss_fct(prediction_logits.view(-1, prediction_logits.size(-1)), labels.view(-1))
898
+
899
+ if not return_dict:
900
+ output = (prediction_logits,) + dlbrt_output[1:]
901
+ return ((mlm_loss,) + output) if mlm_loss is not None else output
902
+
903
+ return MaskedLMOutput(
904
+ loss=mlm_loss,
905
+ logits=prediction_logits,
906
+ hidden_states=dlbrt_output.hidden_states,
907
+ attentions=dlbrt_output.attentions,
908
+ )
909
+
910
+
911
+ @add_start_docstrings(
912
+ """
913
+ DistilBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
914
+ pooled output) e.g. for GLUE tasks.
915
+ """,
916
+ DISTILBERT_START_DOCSTRING,
917
+ )
918
+ class DistilBertForSequenceClassification(DistilBertPreTrainedModel):
919
+ def __init__(self, config: PretrainedConfig):
920
+ super().__init__(config)
921
+ self.num_labels = config.num_labels
922
+ self.config = config
923
+
924
+ self.distilbert = DistilBertModel(config)
925
+ self.pre_classifier = nn.Linear(config.dim, config.dim)
926
+ self.classifier = nn.Linear(config.dim, config.num_labels)
927
+ self.dropout = nn.Dropout(config.seq_classif_dropout)
928
+
929
+ # Initialize weights and apply final processing
930
+ self.post_init()
931
+
932
+ def get_position_embeddings(self) -> nn.Embedding:
933
+ """
934
+ Returns the position embeddings
935
+ """
936
+ return self.distilbert.get_position_embeddings()
937
+
938
+ def resize_position_embeddings(self, new_num_position_embeddings: int):
939
+ """
940
+ Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
941
+
942
+ Arguments:
943
+ new_num_position_embeddings (`int`):
944
+ The number of new position embedding matrix. If position embeddings are learned, increasing the size
945
+ will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
946
+ end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
947
+ size will add correct vectors at the end following the position encoding algorithm, whereas reducing
948
+ the size will remove vectors from the end.
949
+ """
950
+ self.distilbert.resize_position_embeddings(new_num_position_embeddings)
951
+
952
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
953
+ @add_code_sample_docstrings(
954
+ checkpoint=_CHECKPOINT_FOR_DOC,
955
+ output_type=SequenceClassifierOutput,
956
+ config_class=_CONFIG_FOR_DOC,
957
+ )
958
+ def forward(
959
+ self,
960
+ input_ids: Optional[torch.Tensor] = None,
961
+ attention_mask: Optional[torch.Tensor] = None,
962
+ head_mask: Optional[torch.Tensor] = None,
963
+ inputs_embeds: Optional[torch.Tensor] = None,
964
+ labels: Optional[torch.LongTensor] = None,
965
+ output_attentions: Optional[bool] = None,
966
+ output_hidden_states: Optional[bool] = None,
967
+ return_dict: Optional[bool] = None,
968
+ ) -> Union[SequenceClassifierOutput, Tuple[torch.Tensor, ...]]:
969
+ r"""
970
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
971
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
972
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
973
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
974
+ """
975
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
976
+
977
+ distilbert_output = self.distilbert(
978
+ input_ids=input_ids,
979
+ attention_mask=attention_mask,
980
+ head_mask=head_mask,
981
+ inputs_embeds=inputs_embeds,
982
+ output_attentions=output_attentions,
983
+ output_hidden_states=output_hidden_states,
984
+ return_dict=return_dict,
985
+ )
986
+ hidden_state = distilbert_output[0] # (bs, seq_len, dim)
987
+ pooled_output = hidden_state[:, 0] # (bs, dim)
988
+ pooled_output = self.pre_classifier(pooled_output) # (bs, dim)
989
+ pooled_output = nn.ReLU()(pooled_output) # (bs, dim)
990
+ pooled_output = self.dropout(pooled_output) # (bs, dim)
991
+ logits = self.classifier(pooled_output) # (bs, num_labels)
992
+
993
+ loss = None
994
+ if labels is not None:
995
+ if self.config.problem_type is None:
996
+ if self.num_labels == 1:
997
+ self.config.problem_type = "regression"
998
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
999
+ self.config.problem_type = "single_label_classification"
1000
+ else:
1001
+ self.config.problem_type = "multi_label_classification"
1002
+
1003
+ if self.config.problem_type == "regression":
1004
+ loss_fct = MSELoss()
1005
+ if self.num_labels == 1:
1006
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1007
+ else:
1008
+ loss = loss_fct(logits, labels)
1009
+ elif self.config.problem_type == "single_label_classification":
1010
+ loss_fct = CrossEntropyLoss()
1011
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1012
+ elif self.config.problem_type == "multi_label_classification":
1013
+ loss_fct = BCEWithLogitsLoss()
1014
+ loss = loss_fct(logits, labels)
1015
+
1016
+ if not return_dict:
1017
+ output = (logits,) + distilbert_output[1:]
1018
+ return ((loss,) + output) if loss is not None else output
1019
+
1020
+ return SequenceClassifierOutput(
1021
+ loss=loss,
1022
+ logits=logits,
1023
+ hidden_states=distilbert_output.hidden_states,
1024
+ attentions=distilbert_output.attentions,
1025
+ )
1026
+
1027
+
1028
+ @add_start_docstrings(
1029
+ """
1030
+ DistilBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
1031
+ linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1032
+ """,
1033
+ DISTILBERT_START_DOCSTRING,
1034
+ )
1035
+ class DistilBertForQuestionAnswering(DistilBertPreTrainedModel):
1036
+ def __init__(self, config: PretrainedConfig):
1037
+ super().__init__(config)
1038
+
1039
+ self.distilbert = DistilBertModel(config)
1040
+ self.qa_outputs = nn.Linear(config.dim, config.num_labels)
1041
+ if config.num_labels != 2:
1042
+ raise ValueError(f"config.num_labels should be 2, but it is {config.num_labels}")
1043
+
1044
+ self.dropout = nn.Dropout(config.qa_dropout)
1045
+
1046
+ # Initialize weights and apply final processing
1047
+ self.post_init()
1048
+
1049
+ def get_position_embeddings(self) -> nn.Embedding:
1050
+ """
1051
+ Returns the position embeddings
1052
+ """
1053
+ return self.distilbert.get_position_embeddings()
1054
+
1055
+ def resize_position_embeddings(self, new_num_position_embeddings: int):
1056
+ """
1057
+ Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
1058
+
1059
+ Arguments:
1060
+ new_num_position_embeddings (`int`):
1061
+ The number of new position embedding matrix. If position embeddings are learned, increasing the size
1062
+ will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
1063
+ end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
1064
+ size will add correct vectors at the end following the position encoding algorithm, whereas reducing
1065
+ the size will remove vectors from the end.
1066
+ """
1067
+ self.distilbert.resize_position_embeddings(new_num_position_embeddings)
1068
+
1069
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, num_choices"))
1070
+ @add_code_sample_docstrings(
1071
+ checkpoint=_CHECKPOINT_FOR_DOC,
1072
+ output_type=QuestionAnsweringModelOutput,
1073
+ config_class=_CONFIG_FOR_DOC,
1074
+ )
1075
+ def forward(
1076
+ self,
1077
+ input_ids: Optional[torch.Tensor] = None,
1078
+ attention_mask: Optional[torch.Tensor] = None,
1079
+ head_mask: Optional[torch.Tensor] = None,
1080
+ inputs_embeds: Optional[torch.Tensor] = None,
1081
+ start_positions: Optional[torch.Tensor] = None,
1082
+ end_positions: Optional[torch.Tensor] = None,
1083
+ output_attentions: Optional[bool] = None,
1084
+ output_hidden_states: Optional[bool] = None,
1085
+ return_dict: Optional[bool] = None,
1086
+ ) -> Union[QuestionAnsweringModelOutput, Tuple[torch.Tensor, ...]]:
1087
+ r"""
1088
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1089
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1090
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1091
+ are not taken into account for computing the loss.
1092
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1093
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1094
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1095
+ are not taken into account for computing the loss.
1096
+ """
1097
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1098
+
1099
+ distilbert_output = self.distilbert(
1100
+ input_ids=input_ids,
1101
+ attention_mask=attention_mask,
1102
+ head_mask=head_mask,
1103
+ inputs_embeds=inputs_embeds,
1104
+ output_attentions=output_attentions,
1105
+ output_hidden_states=output_hidden_states,
1106
+ return_dict=return_dict,
1107
+ )
1108
+ hidden_states = distilbert_output[0] # (bs, max_query_len, dim)
1109
+
1110
+ hidden_states = self.dropout(hidden_states) # (bs, max_query_len, dim)
1111
+ logits = self.qa_outputs(hidden_states) # (bs, max_query_len, 2)
1112
+ start_logits, end_logits = logits.split(1, dim=-1)
1113
+ start_logits = start_logits.squeeze(-1).contiguous() # (bs, max_query_len)
1114
+ end_logits = end_logits.squeeze(-1).contiguous() # (bs, max_query_len)
1115
+
1116
+ total_loss = None
1117
+ if start_positions is not None and end_positions is not None:
1118
+ # If we are on multi-GPU, split add a dimension
1119
+ if len(start_positions.size()) > 1:
1120
+ start_positions = start_positions.squeeze(-1)
1121
+ if len(end_positions.size()) > 1:
1122
+ end_positions = end_positions.squeeze(-1)
1123
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1124
+ ignored_index = start_logits.size(1)
1125
+ start_positions = start_positions.clamp(0, ignored_index)
1126
+ end_positions = end_positions.clamp(0, ignored_index)
1127
+
1128
+ loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
1129
+ start_loss = loss_fct(start_logits, start_positions)
1130
+ end_loss = loss_fct(end_logits, end_positions)
1131
+ total_loss = (start_loss + end_loss) / 2
1132
+
1133
+ if not return_dict:
1134
+ output = (start_logits, end_logits) + distilbert_output[1:]
1135
+ return ((total_loss,) + output) if total_loss is not None else output
1136
+
1137
+ return QuestionAnsweringModelOutput(
1138
+ loss=total_loss,
1139
+ start_logits=start_logits,
1140
+ end_logits=end_logits,
1141
+ hidden_states=distilbert_output.hidden_states,
1142
+ attentions=distilbert_output.attentions,
1143
+ )
1144
+
1145
+
1146
+ @add_start_docstrings(
1147
+ """
1148
+ DistilBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
1149
+ for Named-Entity-Recognition (NER) tasks.
1150
+ """,
1151
+ DISTILBERT_START_DOCSTRING,
1152
+ )
1153
+ class DistilBertForTokenClassification(DistilBertPreTrainedModel):
1154
+ def __init__(self, config: PretrainedConfig):
1155
+ super().__init__(config)
1156
+ self.num_labels = config.num_labels
1157
+
1158
+ self.distilbert = DistilBertModel(config)
1159
+ self.dropout = nn.Dropout(config.dropout)
1160
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1161
+
1162
+ # Initialize weights and apply final processing
1163
+ self.post_init()
1164
+
1165
+ def get_position_embeddings(self) -> nn.Embedding:
1166
+ """
1167
+ Returns the position embeddings
1168
+ """
1169
+ return self.distilbert.get_position_embeddings()
1170
+
1171
+ def resize_position_embeddings(self, new_num_position_embeddings: int):
1172
+ """
1173
+ Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
1174
+
1175
+ Arguments:
1176
+ new_num_position_embeddings (`int`):
1177
+ The number of new position embedding matrix. If position embeddings are learned, increasing the size
1178
+ will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
1179
+ end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
1180
+ size will add correct vectors at the end following the position encoding algorithm, whereas reducing
1181
+ the size will remove vectors from the end.
1182
+ """
1183
+ self.distilbert.resize_position_embeddings(new_num_position_embeddings)
1184
+
1185
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING)
1186
+ @add_code_sample_docstrings(
1187
+ checkpoint=_CHECKPOINT_FOR_DOC,
1188
+ output_type=TokenClassifierOutput,
1189
+ config_class=_CONFIG_FOR_DOC,
1190
+ )
1191
+ def forward(
1192
+ self,
1193
+ input_ids: Optional[torch.Tensor] = None,
1194
+ attention_mask: Optional[torch.Tensor] = None,
1195
+ head_mask: Optional[torch.Tensor] = None,
1196
+ inputs_embeds: Optional[torch.Tensor] = None,
1197
+ labels: Optional[torch.LongTensor] = None,
1198
+ output_attentions: Optional[bool] = None,
1199
+ output_hidden_states: Optional[bool] = None,
1200
+ return_dict: Optional[bool] = None,
1201
+ ) -> Union[TokenClassifierOutput, Tuple[torch.Tensor, ...]]:
1202
+ r"""
1203
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1204
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1205
+ """
1206
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1207
+
1208
+ outputs = self.distilbert(
1209
+ input_ids,
1210
+ attention_mask=attention_mask,
1211
+ head_mask=head_mask,
1212
+ inputs_embeds=inputs_embeds,
1213
+ output_attentions=output_attentions,
1214
+ output_hidden_states=output_hidden_states,
1215
+ return_dict=return_dict,
1216
+ )
1217
+
1218
+ sequence_output = outputs[0]
1219
+
1220
+ sequence_output = self.dropout(sequence_output)
1221
+ logits = self.classifier(sequence_output)
1222
+
1223
+ loss = None
1224
+ if labels is not None:
1225
+ loss_fct = CrossEntropyLoss()
1226
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1227
+
1228
+ if not return_dict:
1229
+ output = (logits,) + outputs[1:]
1230
+ return ((loss,) + output) if loss is not None else output
1231
+
1232
+ return TokenClassifierOutput(
1233
+ loss=loss,
1234
+ logits=logits,
1235
+ hidden_states=outputs.hidden_states,
1236
+ attentions=outputs.attentions,
1237
+ )
1238
+
1239
+
1240
+ @add_start_docstrings(
1241
+ """
1242
+ DistilBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
1243
+ a softmax) e.g. for RocStories/SWAG tasks.
1244
+ """,
1245
+ DISTILBERT_START_DOCSTRING,
1246
+ )
1247
+ class DistilBertForMultipleChoice(DistilBertPreTrainedModel):
1248
+ def __init__(self, config: PretrainedConfig):
1249
+ super().__init__(config)
1250
+
1251
+ self.distilbert = DistilBertModel(config)
1252
+ self.pre_classifier = nn.Linear(config.dim, config.dim)
1253
+ self.classifier = nn.Linear(config.dim, 1)
1254
+ self.dropout = nn.Dropout(config.seq_classif_dropout)
1255
+
1256
+ # Initialize weights and apply final processing
1257
+ self.post_init()
1258
+
1259
+ def get_position_embeddings(self) -> nn.Embedding:
1260
+ """
1261
+ Returns the position embeddings
1262
+ """
1263
+ return self.distilbert.get_position_embeddings()
1264
+
1265
+ def resize_position_embeddings(self, new_num_position_embeddings: int):
1266
+ """
1267
+ Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
1268
+
1269
+ Arguments:
1270
+ new_num_position_embeddings (`int`)
1271
+ The number of new position embeddings. If position embeddings are learned, increasing the size will add
1272
+ newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
1273
+ position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
1274
+ add correct vectors at the end following the position encoding algorithm, whereas reducing the size
1275
+ will remove vectors from the end.
1276
+ """
1277
+ self.distilbert.resize_position_embeddings(new_num_position_embeddings)
1278
+
1279
+ @add_start_docstrings_to_model_forward(
1280
+ DISTILBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
1281
+ )
1282
+ @replace_return_docstrings(output_type=MultipleChoiceModelOutput, config_class=_CONFIG_FOR_DOC)
1283
+ def forward(
1284
+ self,
1285
+ input_ids: Optional[torch.Tensor] = None,
1286
+ attention_mask: Optional[torch.Tensor] = None,
1287
+ head_mask: Optional[torch.Tensor] = None,
1288
+ inputs_embeds: Optional[torch.Tensor] = None,
1289
+ labels: Optional[torch.LongTensor] = None,
1290
+ output_attentions: Optional[bool] = None,
1291
+ output_hidden_states: Optional[bool] = None,
1292
+ return_dict: Optional[bool] = None,
1293
+ ) -> Union[MultipleChoiceModelOutput, Tuple[torch.Tensor, ...]]:
1294
+ r"""
1295
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1296
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1297
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1298
+ `input_ids` above)
1299
+
1300
+ Returns:
1301
+
1302
+ Examples:
1303
+
1304
+ ```python
1305
+ >>> from transformers import AutoTokenizer, DistilBertForMultipleChoice
1306
+ >>> import torch
1307
+
1308
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased")
1309
+ >>> model = DistilBertForMultipleChoice.from_pretrained("distilbert-base-cased")
1310
+
1311
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1312
+ >>> choice0 = "It is eaten with a fork and a knife."
1313
+ >>> choice1 = "It is eaten while held in the hand."
1314
+ >>> labels = torch.tensor(0).unsqueeze(0) # choice0 is correct (according to Wikipedia ;)), batch size 1
1315
+
1316
+ >>> encoding = tokenizer([[prompt, choice0], [prompt, choice1]], return_tensors="pt", padding=True)
1317
+ >>> outputs = model(**{k: v.unsqueeze(0) for k, v in encoding.items()}, labels=labels) # batch size is 1
1318
+
1319
+ >>> # the linear classifier still needs to be trained
1320
+ >>> loss = outputs.loss
1321
+ >>> logits = outputs.logits
1322
+ ```"""
1323
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1324
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1325
+
1326
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1327
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1328
+ inputs_embeds = (
1329
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1330
+ if inputs_embeds is not None
1331
+ else None
1332
+ )
1333
+
1334
+ outputs = self.distilbert(
1335
+ input_ids,
1336
+ attention_mask=attention_mask,
1337
+ head_mask=head_mask,
1338
+ inputs_embeds=inputs_embeds,
1339
+ output_attentions=output_attentions,
1340
+ output_hidden_states=output_hidden_states,
1341
+ return_dict=return_dict,
1342
+ )
1343
+
1344
+ hidden_state = outputs[0] # (bs * num_choices, seq_len, dim)
1345
+ pooled_output = hidden_state[:, 0] # (bs * num_choices, dim)
1346
+ pooled_output = self.pre_classifier(pooled_output) # (bs * num_choices, dim)
1347
+ pooled_output = nn.ReLU()(pooled_output) # (bs * num_choices, dim)
1348
+ pooled_output = self.dropout(pooled_output) # (bs * num_choices, dim)
1349
+ logits = self.classifier(pooled_output) # (bs * num_choices, 1)
1350
+
1351
+ reshaped_logits = logits.view(-1, num_choices) # (bs, num_choices)
1352
+
1353
+ loss = None
1354
+ if labels is not None:
1355
+ loss_fct = CrossEntropyLoss()
1356
+ loss = loss_fct(reshaped_logits, labels)
1357
+
1358
+ if not return_dict:
1359
+ output = (reshaped_logits,) + outputs[1:]
1360
+ return ((loss,) + output) if loss is not None else output
1361
+
1362
+ return MultipleChoiceModelOutput(
1363
+ loss=loss,
1364
+ logits=reshaped_logits,
1365
+ hidden_states=outputs.hidden_states,
1366
+ attentions=outputs.attentions,
1367
+ )
1368
+
1369
+
1370
+ __all__ = [
1371
+ "DistilBertForMaskedLM",
1372
+ "DistilBertForMultipleChoice",
1373
+ "DistilBertForQuestionAnswering",
1374
+ "DistilBertForSequenceClassification",
1375
+ "DistilBertForTokenClassification",
1376
+ "DistilBertModel",
1377
+ "DistilBertPreTrainedModel",
1378
+ ]
vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/modeling_flax_distilbert.py ADDED
@@ -0,0 +1,906 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
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 math
17
+ from typing import Callable, Optional, Tuple
18
+
19
+ import flax.linen as nn
20
+ import jax
21
+ import jax.numpy as jnp
22
+ import numpy as np
23
+ from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
24
+ from flax.traverse_util import flatten_dict, unflatten_dict
25
+ from jax import lax
26
+
27
+ from ...modeling_flax_outputs import (
28
+ FlaxBaseModelOutput,
29
+ FlaxMaskedLMOutput,
30
+ FlaxMultipleChoiceModelOutput,
31
+ FlaxQuestionAnsweringModelOutput,
32
+ FlaxSequenceClassifierOutput,
33
+ FlaxTokenClassifierOutput,
34
+ )
35
+ from ...modeling_flax_utils import ACT2FN, FlaxPreTrainedModel, append_call_sample_docstring, overwrite_call_docstring
36
+ from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging
37
+ from .configuration_distilbert import DistilBertConfig
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+ _CHECKPOINT_FOR_DOC = "distilbert-base-uncased"
43
+ _CONFIG_FOR_DOC = "DistilBertConfig"
44
+
45
+
46
+ FLAX_DISTILBERT_START_DOCSTRING = r"""
47
+
48
+ This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
49
+ library implements for all its model (such as downloading, saving and converting weights from PyTorch models)
50
+
51
+ This model is also a
52
+ [flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html) subclass. Use it as
53
+ a regular Flax linen Module and refer to the Flax documentation for all matter related to general usage and
54
+ behavior.
55
+
56
+ Finally, this model supports inherent JAX features such as:
57
+
58
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
59
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
60
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
61
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
62
+
63
+ Parameters:
64
+ config ([`DistilBertConfig`]): Model configuration class with all the parameters of the model.
65
+ Initializing with a config file does not load the weights associated with the model, only the
66
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
67
+ """
68
+
69
+ DISTILBERT_INPUTS_DOCSTRING = r"""
70
+ Args:
71
+ input_ids (`numpy.ndarray` of shape `({0})`):
72
+ Indices of input sequence tokens in the vocabulary.
73
+
74
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
75
+ [`PreTrainedTokenizer.__call__`] for details.
76
+
77
+ [What are input IDs?](../glossary#input-ids)
78
+ attention_mask (`numpy.ndarray` of shape `({0})`, *optional*):
79
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
80
+
81
+ - 1 for tokens that are **not masked**,
82
+ - 0 for tokens that are **masked**.
83
+
84
+ [What are attention masks?](../glossary#attention-mask)
85
+ output_attentions (`bool`, *optional*):
86
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
87
+ tensors for more detail.
88
+ output_hidden_states (`bool`, *optional*):
89
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
90
+ more detail.
91
+ return_dict (`bool`, *optional*):
92
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
93
+ """
94
+
95
+
96
+ def get_angles(pos, i, d_model):
97
+ angle_rates = 1 / np.power(10000, (2 * (i // 2)) / np.float32(d_model))
98
+ return pos * angle_rates
99
+
100
+
101
+ def positional_encoding(position, d_model):
102
+ # create the sinusoidal pattern for the positional encoding
103
+ angle_rads = get_angles(np.arange(position)[:, np.newaxis], np.arange(d_model)[np.newaxis, :], d_model)
104
+
105
+ # apply sin to even indices in the array; 2i
106
+ angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])
107
+
108
+ # apply cos to odd indices in the array; 2i+1
109
+ angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])
110
+
111
+ pos_encoding = angle_rads[np.newaxis, ...]
112
+
113
+ return jnp.array(pos_encoding)
114
+
115
+
116
+ class FlaxEmbeddings(nn.Module):
117
+ """Construct the embeddings from word, position and token_type embeddings."""
118
+
119
+ config: DistilBertConfig
120
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
121
+
122
+ def setup(self):
123
+ self.word_embeddings = nn.Embed(
124
+ self.config.vocab_size,
125
+ self.config.dim,
126
+ embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
127
+ )
128
+ if not self.config.sinusoidal_pos_embds:
129
+ self.position_embeddings = nn.Embed(
130
+ self.config.max_position_embeddings,
131
+ self.config.dim,
132
+ embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
133
+ )
134
+ else:
135
+ self.pos_encoding = positional_encoding(self.config.max_position_embeddings, self.config.dim)
136
+ self.LayerNorm = nn.LayerNorm(epsilon=1e-12, dtype=self.dtype)
137
+ self.dropout = nn.Dropout(rate=self.config.dropout)
138
+
139
+ def __call__(self, input_ids, deterministic: bool = True):
140
+ # Embed
141
+ batch_size, seq_length = input_ids.shape
142
+ inputs_embeds = self.word_embeddings(input_ids.astype("i4"))
143
+ if not self.config.sinusoidal_pos_embds:
144
+ position_ids = jnp.arange(seq_length).astype("i4")
145
+ position_ids = jnp.broadcast_to(position_ids, shape=(batch_size, seq_length))
146
+ position_embeds = self.position_embeddings(position_ids.astype("i4"))
147
+ else:
148
+ position_embeds = self.pos_encoding[:, :seq_length, :]
149
+ # explicitly cast the positions here, since self.embed_positions are not registered as parameters
150
+ position_embeds = position_embeds.astype(inputs_embeds.dtype)
151
+
152
+ # Sum all embeddings
153
+ hidden_states = inputs_embeds + position_embeds
154
+
155
+ # Layer Norm
156
+ hidden_states = self.LayerNorm(hidden_states)
157
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
158
+ return hidden_states
159
+
160
+
161
+ class FlaxMultiHeadSelfAttention(nn.Module):
162
+ config: DistilBertConfig
163
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
164
+
165
+ def setup(self):
166
+ self.n_heads = self.config.n_heads
167
+ self.dim = self.config.dim
168
+ self.dropout = nn.Dropout(rate=self.config.attention_dropout)
169
+
170
+ if not (self.dim % self.n_heads == 0):
171
+ raise ValueError(f"Hidden size {self.dim} not dividable by number of heads {self.n_heads}")
172
+
173
+ self.q_lin = nn.Dense(
174
+ self.dim,
175
+ dtype=self.dtype,
176
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
177
+ )
178
+ self.k_lin = nn.Dense(
179
+ self.dim,
180
+ dtype=self.dtype,
181
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
182
+ )
183
+ self.v_lin = nn.Dense(
184
+ self.dim,
185
+ dtype=self.dtype,
186
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
187
+ )
188
+ self.out_lin = nn.Dense(
189
+ self.dim,
190
+ dtype=self.dtype,
191
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
192
+ )
193
+
194
+ def __call__(
195
+ self,
196
+ query,
197
+ key,
198
+ value,
199
+ mask,
200
+ deterministic: bool = True,
201
+ output_attentions: bool = False,
202
+ ):
203
+ bs, q_len, dim = query.shape
204
+ k_len = key.shape[1]
205
+ # assert dim == self.dim, f'Dimensions do not match: {dim} input vs {self.dim} configured'
206
+ # assert key.size() == value.size()
207
+
208
+ dim_per_head = self.dim // self.n_heads
209
+
210
+ mask_reshp = (bs, 1, 1, k_len)
211
+
212
+ def shape(x):
213
+ """separate heads"""
214
+ return x.reshape(bs, -1, self.n_heads, dim_per_head).transpose(0, 2, 1, 3)
215
+
216
+ def unshape(x):
217
+ """group heads"""
218
+ return x.transpose(0, 2, 1, 3).reshape(bs, -1, self.n_heads * dim_per_head)
219
+
220
+ q = shape(self.q_lin(query)) # (bs, n_heads, q_len, dim_per_head)
221
+ k = shape(self.k_lin(key)) # (bs, n_heads, k_len, dim_per_head)
222
+ v = shape(self.v_lin(value)) # (bs, n_heads, k_len, dim_per_head)
223
+
224
+ q = q / math.sqrt(dim_per_head) # (bs, n_heads, q_len, dim_per_head)
225
+ scores = jnp.matmul(q, k.transpose(0, 1, 3, 2)) # (bs, n_heads, q_len, k_len)
226
+ mask = jnp.reshape(mask, mask_reshp)
227
+
228
+ mask = mask.astype(scores.dtype)
229
+ scores = scores - 1e30 * (1.0 - mask)
230
+
231
+ weights = nn.softmax(scores, axis=-1) # (bs, n_heads, q_len, k_len)
232
+ weights = self.dropout(weights, deterministic=deterministic)
233
+
234
+ context = jnp.matmul(weights, v) # (bs, n_heads, q_len, dim_per_head)
235
+ context = unshape(context) # (bs, q_len, dim)
236
+ context = self.out_lin(context) # (bs, q_len, dim)
237
+
238
+ if output_attentions:
239
+ return (context, weights)
240
+ else:
241
+ return (context,)
242
+
243
+
244
+ class FlaxFFN(nn.Module):
245
+ config: DistilBertConfig
246
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
247
+
248
+ def setup(self):
249
+ self.dropout = nn.Dropout(rate=self.config.dropout)
250
+ self.chunk_size_feed_forward = self.config.chunk_size_feed_forward
251
+ self.seq_len_dim = 1
252
+ self.lin1 = nn.Dense(
253
+ self.config.hidden_dim,
254
+ dtype=self.dtype,
255
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
256
+ )
257
+ self.lin2 = nn.Dense(
258
+ self.config.dim,
259
+ dtype=self.dtype,
260
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
261
+ )
262
+
263
+ self.activation = ACT2FN[self.config.activation]
264
+
265
+ def __call__(self, hidden_states, deterministic: bool = True):
266
+ hidden_states = self.lin1(hidden_states)
267
+ hidden_states = self.activation(hidden_states)
268
+ hidden_states = self.lin2(hidden_states)
269
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
270
+ return hidden_states
271
+
272
+
273
+ class FlaxTransformerBlock(nn.Module):
274
+ config: DistilBertConfig
275
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
276
+
277
+ def setup(self):
278
+ assert (
279
+ self.config.dim % self.config.n_heads == 0
280
+ ), f"Hidden size {self.config.dim} not dividable by number of heads {self.config.n_heads}"
281
+
282
+ self.attention = FlaxMultiHeadSelfAttention(self.config, dtype=self.dtype)
283
+ self.sa_layer_norm = nn.LayerNorm(epsilon=1e-12, dtype=self.dtype)
284
+
285
+ self.ffn = FlaxFFN(self.config, dtype=self.dtype)
286
+ self.output_layer_norm = nn.LayerNorm(epsilon=1e-12, dtype=self.dtype)
287
+
288
+ def __call__(
289
+ self,
290
+ hidden_states,
291
+ attn_mask,
292
+ output_attentions: bool = False,
293
+ deterministic: bool = True,
294
+ ):
295
+ # Self-Attention
296
+ sa_output = self.attention(
297
+ query=hidden_states,
298
+ key=hidden_states,
299
+ value=hidden_states,
300
+ mask=attn_mask,
301
+ output_attentions=output_attentions,
302
+ deterministic=deterministic,
303
+ )
304
+ if output_attentions:
305
+ sa_output, sa_weights = sa_output
306
+ else:
307
+ assert type(sa_output) is tuple
308
+ sa_output = sa_output[0]
309
+ sa_output = self.sa_layer_norm(sa_output + hidden_states)
310
+
311
+ # Feed Forward Network
312
+ ffn_output = self.ffn(sa_output, deterministic=deterministic)
313
+ ffn_output = self.output_layer_norm(ffn_output + sa_output)
314
+ output = (ffn_output,)
315
+ if output_attentions:
316
+ output = (sa_weights,) + output
317
+ return output
318
+
319
+
320
+ class FlaxTransformer(nn.Module):
321
+ config: DistilBertConfig
322
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
323
+
324
+ def setup(self):
325
+ self.layers = [
326
+ FlaxTransformerBlock(self.config, name=str(i), dtype=self.dtype) for i in range(self.config.n_layers)
327
+ ]
328
+
329
+ def __call__(
330
+ self,
331
+ hidden_states,
332
+ attention_mask,
333
+ output_attentions: bool = False,
334
+ output_hidden_states: bool = False,
335
+ deterministic: bool = True,
336
+ return_dict: bool = False,
337
+ ):
338
+ all_hidden_states = () if output_hidden_states else None
339
+ all_attentions = () if output_attentions else None
340
+
341
+ for layer_module in self.layers:
342
+ if output_hidden_states:
343
+ all_hidden_states = all_hidden_states + (hidden_states,)
344
+
345
+ layer_outputs = layer_module(
346
+ hidden_states=hidden_states,
347
+ attn_mask=attention_mask,
348
+ output_attentions=output_attentions,
349
+ deterministic=deterministic,
350
+ )
351
+ hidden_states = layer_outputs[-1]
352
+
353
+ if output_attentions:
354
+ assert len(layer_outputs) == 2
355
+ attentions = layer_outputs[0]
356
+ all_attentions = all_attentions + (attentions,)
357
+ else:
358
+ assert len(layer_outputs) == 1
359
+
360
+ # Add last layer
361
+ if output_hidden_states:
362
+ all_hidden_states = all_hidden_states + (hidden_states,)
363
+
364
+ if not return_dict:
365
+ return tuple(v for v in [hidden_states, all_attentions, all_hidden_states] if v is not None)
366
+ return FlaxBaseModelOutput(
367
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
368
+ )
369
+
370
+
371
+ class FlaxTransformerEncoder(nn.Module):
372
+ config: DistilBertConfig
373
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
374
+
375
+ def setup(self):
376
+ self.layer = FlaxTransformer(self.config, dtype=self.dtype)
377
+
378
+ def __call__(
379
+ self,
380
+ hidden_states,
381
+ attention_mask,
382
+ output_attentions: bool = False,
383
+ output_hidden_states: bool = False,
384
+ deterministic: bool = True,
385
+ return_dict: bool = False,
386
+ ):
387
+ return self.layer(
388
+ hidden_states=hidden_states,
389
+ attention_mask=attention_mask,
390
+ output_attentions=output_attentions,
391
+ output_hidden_states=output_hidden_states,
392
+ deterministic=deterministic,
393
+ return_dict=return_dict,
394
+ )
395
+
396
+
397
+ class FlaxDistilBertLMDecoder(nn.Module):
398
+ config: DistilBertConfig
399
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
400
+ bias_init: Callable[..., np.ndarray] = jax.nn.initializers.zeros
401
+
402
+ def setup(self):
403
+ self.bias = self.param("bias", self.bias_init, (self.config.vocab_size,))
404
+
405
+ def __call__(self, inputs, kernel):
406
+ inputs = jnp.asarray(inputs, self.dtype)
407
+ kernel = jnp.asarray(kernel, self.dtype)
408
+ y = lax.dot_general(inputs, kernel, (((inputs.ndim - 1,), (0,)), ((), ())))
409
+ bias = jnp.asarray(self.bias, self.dtype)
410
+ y = y + bias
411
+ return y
412
+
413
+
414
+ class FlaxDistilBertPreTrainedModel(FlaxPreTrainedModel):
415
+ """
416
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
417
+ models.
418
+ """
419
+
420
+ config_class = DistilBertConfig
421
+ base_model_prefix = "distilbert"
422
+ module_class: nn.Module = None
423
+
424
+ def __init__(
425
+ self,
426
+ config: DistilBertConfig,
427
+ input_shape: Tuple = (1, 1),
428
+ seed: int = 0,
429
+ dtype: jnp.dtype = jnp.float32,
430
+ _do_init: bool = True,
431
+ **kwargs,
432
+ ):
433
+ module = self.module_class(config=config, dtype=dtype, **kwargs)
434
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
435
+
436
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
437
+ # init input tensors
438
+ input_ids = jnp.zeros(input_shape, dtype="i4")
439
+ attention_mask = jnp.ones_like(input_ids)
440
+
441
+ params_rng, dropout_rng = jax.random.split(rng)
442
+ rngs = {"params": params_rng, "dropout": dropout_rng}
443
+
444
+ random_params = self.module.init(rngs, input_ids, attention_mask, return_dict=False)["params"]
445
+
446
+ if params is not None:
447
+ random_params = flatten_dict(unfreeze(random_params))
448
+ params = flatten_dict(unfreeze(params))
449
+ for missing_key in self._missing_keys:
450
+ params[missing_key] = random_params[missing_key]
451
+ self._missing_keys = set()
452
+ return freeze(unflatten_dict(params))
453
+ else:
454
+ return random_params
455
+
456
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
457
+ def __call__(
458
+ self,
459
+ input_ids,
460
+ attention_mask=None,
461
+ head_mask=None,
462
+ params: dict = None,
463
+ dropout_rng: jax.random.PRNGKey = None,
464
+ train: bool = False,
465
+ output_attentions: Optional[bool] = None,
466
+ output_hidden_states: Optional[bool] = None,
467
+ return_dict: Optional[bool] = None,
468
+ ):
469
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
470
+ output_hidden_states = (
471
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
472
+ )
473
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
474
+
475
+ if attention_mask is None:
476
+ attention_mask = jnp.ones_like(input_ids)
477
+
478
+ # Handle any PRNG if needed
479
+ rngs = {}
480
+ if dropout_rng is not None:
481
+ rngs["dropout"] = dropout_rng
482
+
483
+ return self.module.apply(
484
+ {"params": params or self.params},
485
+ jnp.array(input_ids, dtype="i4"),
486
+ jnp.array(attention_mask, dtype="i4"),
487
+ not train,
488
+ output_attentions,
489
+ output_hidden_states,
490
+ return_dict,
491
+ rngs=rngs,
492
+ )
493
+
494
+
495
+ class FlaxDistilBertModule(nn.Module):
496
+ config: DistilBertConfig
497
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
498
+
499
+ def setup(self):
500
+ self.embeddings = FlaxEmbeddings(self.config, dtype=self.dtype)
501
+ self.transformer = FlaxTransformerEncoder(self.config, dtype=self.dtype)
502
+
503
+ def __call__(
504
+ self,
505
+ input_ids,
506
+ attention_mask,
507
+ deterministic: bool = True,
508
+ output_attentions: bool = False,
509
+ output_hidden_states: bool = False,
510
+ return_dict: bool = True,
511
+ ):
512
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
513
+ output_hidden_states = (
514
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
515
+ )
516
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
517
+
518
+ input_embeds = self.embeddings(input_ids, deterministic=deterministic)
519
+ return self.transformer(
520
+ hidden_states=input_embeds,
521
+ attention_mask=attention_mask,
522
+ deterministic=deterministic,
523
+ output_attentions=output_attentions,
524
+ output_hidden_states=output_hidden_states,
525
+ return_dict=return_dict,
526
+ )
527
+
528
+
529
+ @add_start_docstrings(
530
+ "The bare DistilBert Model transformer outputting raw hidden-states without any specific head on top.",
531
+ FLAX_DISTILBERT_START_DOCSTRING,
532
+ )
533
+ class FlaxDistilBertModel(FlaxDistilBertPreTrainedModel):
534
+ module_class = FlaxDistilBertModule
535
+
536
+
537
+ append_call_sample_docstring(FlaxDistilBertModel, _CHECKPOINT_FOR_DOC, None, _CONFIG_FOR_DOC)
538
+
539
+
540
+ class FlaxDistilBertForMaskedLMModule(nn.Module):
541
+ config: DistilBertConfig
542
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
543
+
544
+ def setup(self):
545
+ self.distilbert = FlaxDistilBertModule(self.config, dtype=self.dtype)
546
+ self.vocab_transform = nn.Dense(
547
+ self.config.dim,
548
+ dtype=self.dtype,
549
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
550
+ )
551
+ self.vocab_layer_norm = nn.LayerNorm(epsilon=1e-12, dtype=self.dtype)
552
+ if self.config.tie_word_embeddings:
553
+ self.vocab_projector = FlaxDistilBertLMDecoder(
554
+ self.config,
555
+ dtype=self.dtype,
556
+ )
557
+ else:
558
+ self.vocab_projector = nn.Dense(
559
+ self.config.vocab_size,
560
+ dtype=self.dtype,
561
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
562
+ )
563
+
564
+ def __call__(
565
+ self,
566
+ input_ids,
567
+ attention_mask,
568
+ deterministic: bool = True,
569
+ output_attentions: bool = False,
570
+ output_hidden_states: bool = False,
571
+ return_dict: bool = True,
572
+ ):
573
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
574
+
575
+ dlbrt_output = self.distilbert(
576
+ input_ids=input_ids,
577
+ attention_mask=attention_mask,
578
+ output_attentions=output_attentions,
579
+ output_hidden_states=output_hidden_states,
580
+ deterministic=deterministic,
581
+ return_dict=return_dict,
582
+ )
583
+ hidden_states = dlbrt_output[0]
584
+ prediction_logits = self.vocab_transform(hidden_states)
585
+ prediction_logits = ACT2FN[self.config.activation](prediction_logits)
586
+ prediction_logits = self.vocab_layer_norm(prediction_logits)
587
+
588
+ if self.config.tie_word_embeddings:
589
+ shared_embedding = self.distilbert.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
590
+ prediction_logits = self.vocab_projector(prediction_logits, shared_embedding.T)
591
+ else:
592
+ prediction_logits = self.vocab_projector(prediction_logits)
593
+
594
+ if not return_dict:
595
+ output = (prediction_logits,) + dlbrt_output[1:]
596
+ return output
597
+
598
+ return FlaxMaskedLMOutput(
599
+ logits=prediction_logits,
600
+ hidden_states=dlbrt_output.hidden_states,
601
+ attentions=dlbrt_output.attentions,
602
+ )
603
+
604
+
605
+ @add_start_docstrings("""DistilBert Model with a `language modeling` head on top.""", FLAX_DISTILBERT_START_DOCSTRING)
606
+ class FlaxDistilBertForMaskedLM(FlaxDistilBertPreTrainedModel):
607
+ module_class = FlaxDistilBertForMaskedLMModule
608
+
609
+
610
+ append_call_sample_docstring(FlaxDistilBertForMaskedLM, _CHECKPOINT_FOR_DOC, FlaxMaskedLMOutput, _CONFIG_FOR_DOC)
611
+
612
+
613
+ class FlaxDistilBertForSequenceClassificationModule(nn.Module):
614
+ config: DistilBertConfig
615
+ dtype: jnp.dtype = jnp.float32
616
+
617
+ def setup(self):
618
+ self.distilbert = FlaxDistilBertModule(config=self.config, dtype=self.dtype)
619
+ self.pre_classifier = nn.Dense(
620
+ self.config.dim,
621
+ dtype=self.dtype,
622
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
623
+ )
624
+ self.dropout = nn.Dropout(rate=self.config.seq_classif_dropout)
625
+ self.classifier = nn.Dense(
626
+ self.config.num_labels,
627
+ dtype=self.dtype,
628
+ )
629
+
630
+ def __call__(
631
+ self,
632
+ input_ids,
633
+ attention_mask,
634
+ deterministic: bool = True,
635
+ output_attentions: bool = False,
636
+ output_hidden_states: bool = False,
637
+ return_dict: bool = True,
638
+ ):
639
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
640
+ # Model
641
+ distilbert_output = self.distilbert(
642
+ input_ids,
643
+ attention_mask,
644
+ deterministic=deterministic,
645
+ output_attentions=output_attentions,
646
+ output_hidden_states=output_hidden_states,
647
+ return_dict=return_dict,
648
+ )
649
+ hidden_state = distilbert_output[0] # (bs, seq_len, dim)
650
+ pooled_output = hidden_state[:, 0] # (bs, dim)
651
+ pooled_output = self.pre_classifier(pooled_output) # (bs, dim)
652
+ pooled_output = ACT2FN["relu"](pooled_output)
653
+ pooled_output = self.dropout(pooled_output, deterministic=deterministic)
654
+ logits = self.classifier(pooled_output) # (bs, dim)
655
+
656
+ if not return_dict:
657
+ return (logits,) + distilbert_output[1:]
658
+
659
+ return FlaxSequenceClassifierOutput(
660
+ logits=logits,
661
+ hidden_states=distilbert_output.hidden_states,
662
+ attentions=distilbert_output.attentions,
663
+ )
664
+
665
+
666
+ @add_start_docstrings(
667
+ """
668
+ DistilBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
669
+ pooled output) e.g. for GLUE tasks.
670
+ """,
671
+ FLAX_DISTILBERT_START_DOCSTRING,
672
+ )
673
+ class FlaxDistilBertForSequenceClassification(FlaxDistilBertPreTrainedModel):
674
+ module_class = FlaxDistilBertForSequenceClassificationModule
675
+
676
+
677
+ append_call_sample_docstring(
678
+ FlaxDistilBertForSequenceClassification,
679
+ _CHECKPOINT_FOR_DOC,
680
+ FlaxSequenceClassifierOutput,
681
+ _CONFIG_FOR_DOC,
682
+ )
683
+
684
+
685
+ class FlaxDistilBertForMultipleChoiceModule(nn.Module):
686
+ config: DistilBertConfig
687
+ dtype: jnp.dtype = jnp.float32
688
+
689
+ def setup(self):
690
+ self.distilbert = FlaxDistilBertModule(config=self.config, dtype=self.dtype)
691
+ self.pre_classifier = nn.Dense(
692
+ self.config.dim,
693
+ dtype=self.dtype,
694
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
695
+ )
696
+ self.dropout = nn.Dropout(rate=self.config.seq_classif_dropout)
697
+ self.classifier = nn.Dense(
698
+ 1,
699
+ dtype=self.dtype,
700
+ )
701
+
702
+ def __call__(
703
+ self,
704
+ input_ids,
705
+ attention_mask,
706
+ deterministic: bool = True,
707
+ output_attentions: bool = False,
708
+ output_hidden_states: bool = False,
709
+ return_dict: bool = True,
710
+ ):
711
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
712
+ num_choices = input_ids.shape[1]
713
+ input_ids = input_ids.reshape(-1, input_ids.shape[-1]) if input_ids is not None else None
714
+ attention_mask = attention_mask.reshape(-1, attention_mask.shape[-1]) if attention_mask is not None else None
715
+
716
+ # Model
717
+ outputs = self.distilbert(
718
+ input_ids,
719
+ attention_mask,
720
+ deterministic=deterministic,
721
+ output_attentions=output_attentions,
722
+ output_hidden_states=output_hidden_states,
723
+ return_dict=return_dict,
724
+ )
725
+
726
+ hidden_state = outputs[0]
727
+ pooled_output = hidden_state[:, 0]
728
+ pooled_output = self.pre_classifier(pooled_output)
729
+ pooled_output = ACT2FN["relu"](pooled_output)
730
+ pooled_output = self.dropout(pooled_output, deterministic=deterministic)
731
+ logits = self.classifier(pooled_output)
732
+
733
+ reshaped_logits = logits.reshape(-1, num_choices)
734
+
735
+ if not return_dict:
736
+ return (reshaped_logits,) + outputs[2:]
737
+
738
+ return FlaxMultipleChoiceModelOutput(
739
+ logits=reshaped_logits,
740
+ hidden_states=outputs.hidden_states,
741
+ attentions=outputs.attentions,
742
+ )
743
+
744
+
745
+ @add_start_docstrings(
746
+ """
747
+ DistilBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
748
+ a softmax) e.g. for RocStories/SWAG tasks.
749
+ """,
750
+ FLAX_DISTILBERT_START_DOCSTRING,
751
+ )
752
+ class FlaxDistilBertForMultipleChoice(FlaxDistilBertPreTrainedModel):
753
+ module_class = FlaxDistilBertForMultipleChoiceModule
754
+
755
+
756
+ overwrite_call_docstring(
757
+ FlaxDistilBertForMultipleChoice, DISTILBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
758
+ )
759
+ append_call_sample_docstring(
760
+ FlaxDistilBertForMultipleChoice,
761
+ _CHECKPOINT_FOR_DOC,
762
+ FlaxMultipleChoiceModelOutput,
763
+ _CONFIG_FOR_DOC,
764
+ )
765
+
766
+
767
+ class FlaxDistilBertForTokenClassificationModule(nn.Module):
768
+ config: DistilBertConfig
769
+ dtype: jnp.dtype = jnp.float32
770
+
771
+ def setup(self):
772
+ self.distilbert = FlaxDistilBertModule(config=self.config, dtype=self.dtype)
773
+ self.dropout = nn.Dropout(rate=self.config.dropout)
774
+ self.classifier = nn.Dense(self.config.num_labels, dtype=self.dtype)
775
+
776
+ def __call__(
777
+ self,
778
+ input_ids,
779
+ attention_mask,
780
+ deterministic: bool = True,
781
+ output_attentions: bool = False,
782
+ output_hidden_states: bool = False,
783
+ return_dict: bool = True,
784
+ ):
785
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
786
+ # Model
787
+ outputs = self.distilbert(
788
+ input_ids,
789
+ attention_mask,
790
+ deterministic=deterministic,
791
+ output_attentions=output_attentions,
792
+ output_hidden_states=output_hidden_states,
793
+ return_dict=return_dict,
794
+ )
795
+
796
+ hidden_states = outputs[0]
797
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
798
+ logits = self.classifier(hidden_states)
799
+
800
+ if not return_dict:
801
+ return (logits,) + outputs[1:]
802
+
803
+ return FlaxTokenClassifierOutput(
804
+ logits=logits,
805
+ hidden_states=outputs.hidden_states,
806
+ attentions=outputs.attentions,
807
+ )
808
+
809
+
810
+ @add_start_docstrings(
811
+ """
812
+ DistilBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
813
+ for Named-Entity-Recognition (NER) tasks.
814
+ """,
815
+ FLAX_DISTILBERT_START_DOCSTRING,
816
+ )
817
+ class FlaxDistilBertForTokenClassification(FlaxDistilBertPreTrainedModel):
818
+ module_class = FlaxDistilBertForTokenClassificationModule
819
+
820
+
821
+ append_call_sample_docstring(
822
+ FlaxDistilBertForTokenClassification,
823
+ _CHECKPOINT_FOR_DOC,
824
+ FlaxTokenClassifierOutput,
825
+ _CONFIG_FOR_DOC,
826
+ )
827
+
828
+
829
+ class FlaxDistilBertForQuestionAnsweringModule(nn.Module):
830
+ config: DistilBertConfig
831
+ dtype: jnp.dtype = jnp.float32
832
+
833
+ def setup(self):
834
+ self.distilbert = FlaxDistilBertModule(config=self.config, dtype=self.dtype)
835
+ self.qa_outputs = nn.Dense(self.config.num_labels, dtype=self.dtype)
836
+ assert self.config.num_labels == 2
837
+ self.dropout = nn.Dropout(rate=self.config.qa_dropout)
838
+
839
+ def __call__(
840
+ self,
841
+ input_ids,
842
+ attention_mask,
843
+ deterministic: bool = True,
844
+ output_attentions: bool = False,
845
+ output_hidden_states: bool = False,
846
+ return_dict: bool = True,
847
+ ):
848
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
849
+
850
+ # Model
851
+ distilbert_output = self.distilbert(
852
+ input_ids,
853
+ attention_mask,
854
+ deterministic=deterministic,
855
+ output_attentions=output_attentions,
856
+ output_hidden_states=output_hidden_states,
857
+ return_dict=return_dict,
858
+ )
859
+
860
+ hidden_states = distilbert_output[0]
861
+
862
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
863
+ logits = self.qa_outputs(hidden_states)
864
+ start_logits, end_logits = logits.split(self.config.num_labels, axis=-1)
865
+ start_logits = start_logits.squeeze(-1)
866
+ end_logits = end_logits.squeeze(-1)
867
+
868
+ if not return_dict:
869
+ return (start_logits, end_logits) + distilbert_output[1:]
870
+
871
+ return FlaxQuestionAnsweringModelOutput(
872
+ start_logits=start_logits,
873
+ end_logits=end_logits,
874
+ hidden_states=distilbert_output.hidden_states,
875
+ attentions=distilbert_output.attentions,
876
+ )
877
+
878
+
879
+ @add_start_docstrings(
880
+ """
881
+ DistilBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
882
+ linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
883
+ """,
884
+ FLAX_DISTILBERT_START_DOCSTRING,
885
+ )
886
+ class FlaxDistilBertForQuestionAnswering(FlaxDistilBertPreTrainedModel):
887
+ module_class = FlaxDistilBertForQuestionAnsweringModule
888
+
889
+
890
+ append_call_sample_docstring(
891
+ FlaxDistilBertForQuestionAnswering,
892
+ _CHECKPOINT_FOR_DOC,
893
+ FlaxQuestionAnsweringModelOutput,
894
+ _CONFIG_FOR_DOC,
895
+ )
896
+
897
+
898
+ __all__ = [
899
+ "FlaxDistilBertForMaskedLM",
900
+ "FlaxDistilBertForMultipleChoice",
901
+ "FlaxDistilBertForQuestionAnswering",
902
+ "FlaxDistilBertForSequenceClassification",
903
+ "FlaxDistilBertForTokenClassification",
904
+ "FlaxDistilBertModel",
905
+ "FlaxDistilBertPreTrainedModel",
906
+ ]
vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/modeling_tf_distilbert.py ADDED
@@ -0,0 +1,1147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ TF 2.0 DistilBERT model
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import warnings
22
+ from typing import Optional, Tuple, Union
23
+
24
+ import numpy as np
25
+ import tensorflow as tf
26
+
27
+ from ...activations_tf import get_tf_activation
28
+ from ...modeling_tf_outputs import (
29
+ TFBaseModelOutput,
30
+ TFMaskedLMOutput,
31
+ TFMultipleChoiceModelOutput,
32
+ TFQuestionAnsweringModelOutput,
33
+ TFSequenceClassifierOutput,
34
+ TFTokenClassifierOutput,
35
+ )
36
+ from ...modeling_tf_utils import (
37
+ TFMaskedLanguageModelingLoss,
38
+ TFModelInputType,
39
+ TFMultipleChoiceLoss,
40
+ TFPreTrainedModel,
41
+ TFQuestionAnsweringLoss,
42
+ TFSequenceClassificationLoss,
43
+ TFTokenClassificationLoss,
44
+ get_initializer,
45
+ keras,
46
+ keras_serializable,
47
+ unpack_inputs,
48
+ )
49
+ from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
50
+ from ...utils import (
51
+ add_code_sample_docstrings,
52
+ add_start_docstrings,
53
+ add_start_docstrings_to_model_forward,
54
+ logging,
55
+ )
56
+ from .configuration_distilbert import DistilBertConfig
57
+
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+ _CHECKPOINT_FOR_DOC = "distilbert-base-uncased"
62
+ _CONFIG_FOR_DOC = "DistilBertConfig"
63
+
64
+
65
+ class TFEmbeddings(keras.layers.Layer):
66
+ """Construct the embeddings from word, position and token_type embeddings."""
67
+
68
+ def __init__(self, config, **kwargs):
69
+ super().__init__(**kwargs)
70
+ self.config = config
71
+ self.dim = config.dim
72
+ self.initializer_range = config.initializer_range
73
+ self.max_position_embeddings = config.max_position_embeddings
74
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=1e-12, name="LayerNorm")
75
+ self.dropout = keras.layers.Dropout(rate=config.dropout)
76
+
77
+ def build(self, input_shape=None):
78
+ with tf.name_scope("word_embeddings"):
79
+ self.weight = self.add_weight(
80
+ name="weight",
81
+ shape=[self.config.vocab_size, self.dim],
82
+ initializer=get_initializer(initializer_range=self.initializer_range),
83
+ )
84
+
85
+ with tf.name_scope("position_embeddings"):
86
+ self.position_embeddings = self.add_weight(
87
+ name="embeddings",
88
+ shape=[self.max_position_embeddings, self.dim],
89
+ initializer=get_initializer(initializer_range=self.initializer_range),
90
+ )
91
+
92
+ if self.built:
93
+ return
94
+ self.built = True
95
+ if getattr(self, "LayerNorm", None) is not None:
96
+ with tf.name_scope(self.LayerNorm.name):
97
+ self.LayerNorm.build([None, None, self.config.dim])
98
+
99
+ def call(self, input_ids=None, position_ids=None, inputs_embeds=None, training=False):
100
+ """
101
+ Applies embedding based on inputs tensor.
102
+
103
+ Returns:
104
+ final_embeddings (`tf.Tensor`): output embedding tensor.
105
+ """
106
+ assert not (input_ids is None and inputs_embeds is None)
107
+
108
+ if input_ids is not None:
109
+ check_embeddings_within_bounds(input_ids, self.config.vocab_size)
110
+ inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
111
+
112
+ input_shape = shape_list(inputs_embeds)[:-1]
113
+
114
+ if position_ids is None:
115
+ position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
116
+
117
+ position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
118
+ final_embeddings = inputs_embeds + position_embeds
119
+ final_embeddings = self.LayerNorm(inputs=final_embeddings)
120
+ final_embeddings = self.dropout(inputs=final_embeddings, training=training)
121
+
122
+ return final_embeddings
123
+
124
+
125
+ class TFMultiHeadSelfAttention(keras.layers.Layer):
126
+ def __init__(self, config, **kwargs):
127
+ super().__init__(**kwargs)
128
+
129
+ self.n_heads = config.n_heads
130
+ self.dim = config.dim
131
+ self.dropout = keras.layers.Dropout(config.attention_dropout)
132
+ self.output_attentions = config.output_attentions
133
+
134
+ assert self.dim % self.n_heads == 0, f"Hidden size {self.dim} not dividable by number of heads {self.n_heads}"
135
+
136
+ self.q_lin = keras.layers.Dense(
137
+ config.dim, kernel_initializer=get_initializer(config.initializer_range), name="q_lin"
138
+ )
139
+ self.k_lin = keras.layers.Dense(
140
+ config.dim, kernel_initializer=get_initializer(config.initializer_range), name="k_lin"
141
+ )
142
+ self.v_lin = keras.layers.Dense(
143
+ config.dim, kernel_initializer=get_initializer(config.initializer_range), name="v_lin"
144
+ )
145
+ self.out_lin = keras.layers.Dense(
146
+ config.dim, kernel_initializer=get_initializer(config.initializer_range), name="out_lin"
147
+ )
148
+
149
+ self.pruned_heads = set()
150
+ self.config = config
151
+
152
+ def prune_heads(self, heads):
153
+ raise NotImplementedError
154
+
155
+ def call(self, query, key, value, mask, head_mask, output_attentions, training=False):
156
+ """
157
+ Parameters:
158
+ query: tf.Tensor(bs, seq_length, dim)
159
+ key: tf.Tensor(bs, seq_length, dim)
160
+ value: tf.Tensor(bs, seq_length, dim)
161
+ mask: tf.Tensor(bs, seq_length)
162
+
163
+ Returns:
164
+ weights: tf.Tensor(bs, n_heads, seq_length, seq_length) Attention weights context: tf.Tensor(bs,
165
+ seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
166
+ """
167
+ bs, q_length, dim = shape_list(query)
168
+ k_length = shape_list(key)[1]
169
+ # assert dim == self.dim, f'Dimensions do not match: {dim} input vs {self.dim} configured'
170
+ # assert key.size() == value.size()
171
+ dim_per_head = int(self.dim / self.n_heads)
172
+ dim_per_head = tf.cast(dim_per_head, dtype=tf.int32)
173
+ mask_reshape = [bs, 1, 1, k_length]
174
+
175
+ def shape(x):
176
+ """separate heads"""
177
+ return tf.transpose(tf.reshape(x, (bs, -1, self.n_heads, dim_per_head)), perm=(0, 2, 1, 3))
178
+
179
+ def unshape(x):
180
+ """group heads"""
181
+ return tf.reshape(tf.transpose(x, perm=(0, 2, 1, 3)), (bs, -1, self.n_heads * dim_per_head))
182
+
183
+ q = shape(self.q_lin(query)) # (bs, n_heads, q_length, dim_per_head)
184
+ k = shape(self.k_lin(key)) # (bs, n_heads, k_length, dim_per_head)
185
+ v = shape(self.v_lin(value)) # (bs, n_heads, k_length, dim_per_head)
186
+ q = tf.cast(q, dtype=tf.float32)
187
+ q = tf.multiply(q, tf.math.rsqrt(tf.cast(dim_per_head, dtype=tf.float32)))
188
+ k = tf.cast(k, dtype=q.dtype)
189
+ scores = tf.matmul(q, k, transpose_b=True) # (bs, n_heads, q_length, k_length)
190
+ mask = tf.reshape(mask, mask_reshape) # (bs, n_heads, qlen, klen)
191
+ # scores.masked_fill_(mask, -float('inf')) # (bs, n_heads, q_length, k_length)
192
+
193
+ mask = tf.cast(mask, dtype=scores.dtype)
194
+ scores = scores - 1e30 * (1.0 - mask)
195
+ weights = stable_softmax(scores, axis=-1) # (bs, n_heads, qlen, klen)
196
+ weights = self.dropout(weights, training=training) # (bs, n_heads, qlen, klen)
197
+
198
+ # Mask heads if we want to
199
+ if head_mask is not None:
200
+ weights = weights * head_mask
201
+
202
+ context = tf.matmul(weights, v) # (bs, n_heads, qlen, dim_per_head)
203
+ context = unshape(context) # (bs, q_length, dim)
204
+ context = self.out_lin(context) # (bs, q_length, dim)
205
+
206
+ if output_attentions:
207
+ return (context, weights)
208
+ else:
209
+ return (context,)
210
+
211
+ def build(self, input_shape=None):
212
+ if self.built:
213
+ return
214
+ self.built = True
215
+ if getattr(self, "q_lin", None) is not None:
216
+ with tf.name_scope(self.q_lin.name):
217
+ self.q_lin.build([None, None, self.config.dim])
218
+ if getattr(self, "k_lin", None) is not None:
219
+ with tf.name_scope(self.k_lin.name):
220
+ self.k_lin.build([None, None, self.config.dim])
221
+ if getattr(self, "v_lin", None) is not None:
222
+ with tf.name_scope(self.v_lin.name):
223
+ self.v_lin.build([None, None, self.config.dim])
224
+ if getattr(self, "out_lin", None) is not None:
225
+ with tf.name_scope(self.out_lin.name):
226
+ self.out_lin.build([None, None, self.config.dim])
227
+
228
+
229
+ class TFFFN(keras.layers.Layer):
230
+ def __init__(self, config, **kwargs):
231
+ super().__init__(**kwargs)
232
+ self.dropout = keras.layers.Dropout(config.dropout)
233
+ self.lin1 = keras.layers.Dense(
234
+ config.hidden_dim, kernel_initializer=get_initializer(config.initializer_range), name="lin1"
235
+ )
236
+ self.lin2 = keras.layers.Dense(
237
+ config.dim, kernel_initializer=get_initializer(config.initializer_range), name="lin2"
238
+ )
239
+ self.activation = get_tf_activation(config.activation)
240
+ self.config = config
241
+
242
+ def call(self, input, training=False):
243
+ x = self.lin1(input)
244
+ x = self.activation(x)
245
+ x = self.lin2(x)
246
+ x = self.dropout(x, training=training)
247
+ return x
248
+
249
+ def build(self, input_shape=None):
250
+ if self.built:
251
+ return
252
+ self.built = True
253
+ if getattr(self, "lin1", None) is not None:
254
+ with tf.name_scope(self.lin1.name):
255
+ self.lin1.build([None, None, self.config.dim])
256
+ if getattr(self, "lin2", None) is not None:
257
+ with tf.name_scope(self.lin2.name):
258
+ self.lin2.build([None, None, self.config.hidden_dim])
259
+
260
+
261
+ class TFTransformerBlock(keras.layers.Layer):
262
+ def __init__(self, config, **kwargs):
263
+ super().__init__(**kwargs)
264
+
265
+ self.n_heads = config.n_heads
266
+ self.dim = config.dim
267
+ self.hidden_dim = config.hidden_dim
268
+ self.dropout = keras.layers.Dropout(config.dropout)
269
+ self.activation = config.activation
270
+ self.output_attentions = config.output_attentions
271
+
272
+ assert (
273
+ config.dim % config.n_heads == 0
274
+ ), f"Hidden size {config.dim} not dividable by number of heads {config.n_heads}"
275
+
276
+ self.attention = TFMultiHeadSelfAttention(config, name="attention")
277
+ self.sa_layer_norm = keras.layers.LayerNormalization(epsilon=1e-12, name="sa_layer_norm")
278
+
279
+ self.ffn = TFFFN(config, name="ffn")
280
+ self.output_layer_norm = keras.layers.LayerNormalization(epsilon=1e-12, name="output_layer_norm")
281
+ self.config = config
282
+
283
+ def call(self, x, attn_mask, head_mask, output_attentions, training=False): # removed: src_enc=None, src_len=None
284
+ """
285
+ Parameters:
286
+ x: tf.Tensor(bs, seq_length, dim)
287
+ attn_mask: tf.Tensor(bs, seq_length)
288
+
289
+ Outputs: sa_weights: tf.Tensor(bs, n_heads, seq_length, seq_length) The attention weights ffn_output:
290
+ tf.Tensor(bs, seq_length, dim) The output of the transformer block contextualization.
291
+ """
292
+ # Self-Attention
293
+ sa_output = self.attention(x, x, x, attn_mask, head_mask, output_attentions, training=training)
294
+ if output_attentions:
295
+ sa_output, sa_weights = sa_output # (bs, seq_length, dim), (bs, n_heads, seq_length, seq_length)
296
+ else: # To handle these `output_attentions` or `output_hidden_states` cases returning tuples
297
+ # assert type(sa_output) == tuple
298
+ sa_output = sa_output[0]
299
+ sa_output = self.sa_layer_norm(sa_output + x) # (bs, seq_length, dim)
300
+
301
+ # Feed Forward Network
302
+ ffn_output = self.ffn(sa_output, training=training) # (bs, seq_length, dim)
303
+ ffn_output = self.output_layer_norm(ffn_output + sa_output) # (bs, seq_length, dim)
304
+
305
+ output = (ffn_output,)
306
+ if output_attentions:
307
+ output = (sa_weights,) + output
308
+ return output
309
+
310
+ def build(self, input_shape=None):
311
+ if self.built:
312
+ return
313
+ self.built = True
314
+ if getattr(self, "attention", None) is not None:
315
+ with tf.name_scope(self.attention.name):
316
+ self.attention.build(None)
317
+ if getattr(self, "sa_layer_norm", None) is not None:
318
+ with tf.name_scope(self.sa_layer_norm.name):
319
+ self.sa_layer_norm.build([None, None, self.config.dim])
320
+ if getattr(self, "ffn", None) is not None:
321
+ with tf.name_scope(self.ffn.name):
322
+ self.ffn.build(None)
323
+ if getattr(self, "output_layer_norm", None) is not None:
324
+ with tf.name_scope(self.output_layer_norm.name):
325
+ self.output_layer_norm.build([None, None, self.config.dim])
326
+
327
+
328
+ class TFTransformer(keras.layers.Layer):
329
+ def __init__(self, config, **kwargs):
330
+ super().__init__(**kwargs)
331
+ self.n_layers = config.n_layers
332
+ self.output_hidden_states = config.output_hidden_states
333
+ self.output_attentions = config.output_attentions
334
+
335
+ self.layer = [TFTransformerBlock(config, name=f"layer_._{i}") for i in range(config.n_layers)]
336
+
337
+ def call(self, x, attn_mask, head_mask, output_attentions, output_hidden_states, return_dict, training=False):
338
+ # docstyle-ignore
339
+ """
340
+ Parameters:
341
+ x: tf.Tensor(bs, seq_length, dim) Input sequence embedded.
342
+ attn_mask: tf.Tensor(bs, seq_length) Attention mask on the sequence.
343
+
344
+ Returns:
345
+ hidden_state: tf.Tensor(bs, seq_length, dim)
346
+ Sequence of hidden states in the last (top) layer
347
+ all_hidden_states: Tuple[tf.Tensor(bs, seq_length, dim)]
348
+ Tuple of length n_layers with the hidden states from each layer.
349
+ Optional: only if output_hidden_states=True
350
+ all_attentions: Tuple[tf.Tensor(bs, n_heads, seq_length, seq_length)]
351
+ Tuple of length n_layers with the attention weights from each layer
352
+ Optional: only if output_attentions=True
353
+ """
354
+ all_hidden_states = () if output_hidden_states else None
355
+ all_attentions = () if output_attentions else None
356
+
357
+ hidden_state = x
358
+ for i, layer_module in enumerate(self.layer):
359
+ if output_hidden_states:
360
+ all_hidden_states = all_hidden_states + (hidden_state,)
361
+
362
+ layer_outputs = layer_module(hidden_state, attn_mask, head_mask[i], output_attentions, training=training)
363
+ hidden_state = layer_outputs[-1]
364
+
365
+ if output_attentions:
366
+ assert len(layer_outputs) == 2
367
+ attentions = layer_outputs[0]
368
+ all_attentions = all_attentions + (attentions,)
369
+ else:
370
+ assert len(layer_outputs) == 1, f"Incorrect number of outputs {len(layer_outputs)} instead of 1"
371
+
372
+ # Add last layer
373
+ if output_hidden_states:
374
+ all_hidden_states = all_hidden_states + (hidden_state,)
375
+
376
+ if not return_dict:
377
+ return tuple(v for v in [hidden_state, all_hidden_states, all_attentions] if v is not None)
378
+ return TFBaseModelOutput(
379
+ last_hidden_state=hidden_state, hidden_states=all_hidden_states, attentions=all_attentions
380
+ )
381
+
382
+ def build(self, input_shape=None):
383
+ if self.built:
384
+ return
385
+ self.built = True
386
+ if getattr(self, "layer", None) is not None:
387
+ for layer in self.layer:
388
+ with tf.name_scope(layer.name):
389
+ layer.build(None)
390
+
391
+
392
+ @keras_serializable
393
+ class TFDistilBertMainLayer(keras.layers.Layer):
394
+ config_class = DistilBertConfig
395
+
396
+ def __init__(self, config, **kwargs):
397
+ super().__init__(**kwargs)
398
+
399
+ self.config = config
400
+ self.num_hidden_layers = config.num_hidden_layers
401
+ self.output_attentions = config.output_attentions
402
+ self.output_hidden_states = config.output_hidden_states
403
+ self.return_dict = config.use_return_dict
404
+
405
+ self.embeddings = TFEmbeddings(config, name="embeddings") # Embeddings
406
+ self.transformer = TFTransformer(config, name="transformer") # Encoder
407
+
408
+ def get_input_embeddings(self):
409
+ return self.embeddings
410
+
411
+ def set_input_embeddings(self, value):
412
+ self.embeddings.weight = value
413
+ self.embeddings.vocab_size = value.shape[0]
414
+
415
+ def _prune_heads(self, heads_to_prune):
416
+ raise NotImplementedError
417
+
418
+ @unpack_inputs
419
+ def call(
420
+ self,
421
+ input_ids=None,
422
+ attention_mask=None,
423
+ head_mask=None,
424
+ inputs_embeds=None,
425
+ output_attentions=None,
426
+ output_hidden_states=None,
427
+ return_dict=None,
428
+ training=False,
429
+ ):
430
+ if input_ids is not None and inputs_embeds is not None:
431
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
432
+ elif input_ids is not None:
433
+ input_shape = shape_list(input_ids)
434
+ elif inputs_embeds is not None:
435
+ input_shape = shape_list(inputs_embeds)[:-1]
436
+ else:
437
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
438
+
439
+ if attention_mask is None:
440
+ attention_mask = tf.ones(input_shape) # (bs, seq_length)
441
+
442
+ attention_mask = tf.cast(attention_mask, dtype=tf.float32)
443
+
444
+ # Prepare head mask if needed
445
+ # 1.0 in head_mask indicate we keep the head
446
+ # attention_probs has shape bsz x n_heads x N x N
447
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
448
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
449
+ if head_mask is not None:
450
+ raise NotImplementedError
451
+ else:
452
+ head_mask = [None] * self.num_hidden_layers
453
+
454
+ embedding_output = self.embeddings(input_ids, inputs_embeds=inputs_embeds) # (bs, seq_length, dim)
455
+ tfmr_output = self.transformer(
456
+ embedding_output,
457
+ attention_mask,
458
+ head_mask,
459
+ output_attentions,
460
+ output_hidden_states,
461
+ return_dict,
462
+ training=training,
463
+ )
464
+
465
+ return tfmr_output # last-layer hidden-state, (all hidden_states), (all attentions)
466
+
467
+ def build(self, input_shape=None):
468
+ if self.built:
469
+ return
470
+ self.built = True
471
+ if getattr(self, "embeddings", None) is not None:
472
+ with tf.name_scope(self.embeddings.name):
473
+ self.embeddings.build(None)
474
+ if getattr(self, "transformer", None) is not None:
475
+ with tf.name_scope(self.transformer.name):
476
+ self.transformer.build(None)
477
+
478
+
479
+ # INTERFACE FOR ENCODER AND TASK SPECIFIC MODEL #
480
+ class TFDistilBertPreTrainedModel(TFPreTrainedModel):
481
+ """
482
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
483
+ models.
484
+ """
485
+
486
+ config_class = DistilBertConfig
487
+ base_model_prefix = "distilbert"
488
+
489
+
490
+ DISTILBERT_START_DOCSTRING = r"""
491
+
492
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
493
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
494
+ etc.)
495
+
496
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
497
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
498
+ behavior.
499
+
500
+ <Tip>
501
+
502
+ TensorFlow models and layers in `transformers` accept two formats as input:
503
+
504
+ - having all inputs as keyword arguments (like PyTorch models), or
505
+ - having all inputs as a list, tuple or dict in the first positional argument.
506
+
507
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
508
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
509
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
510
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
511
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
512
+ positional argument:
513
+
514
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
515
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
516
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
517
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
518
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
519
+
520
+ Note that when creating models and layers with
521
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
522
+ about any of this, as you can just pass inputs like you would to any other Python function!
523
+
524
+ </Tip>
525
+
526
+ Parameters:
527
+ config ([`DistilBertConfig`]): Model configuration class with all the parameters of the model.
528
+ Initializing with a config file does not load the weights associated with the model, only the
529
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
530
+ """
531
+
532
+ DISTILBERT_INPUTS_DOCSTRING = r"""
533
+ Args:
534
+ input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
535
+ Indices of input sequence tokens in the vocabulary.
536
+
537
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
538
+ [`PreTrainedTokenizer.encode`] for details.
539
+
540
+ [What are input IDs?](../glossary#input-ids)
541
+ attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
542
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
543
+
544
+ - 1 for tokens that are **not masked**,
545
+ - 0 for tokens that are **masked**.
546
+
547
+ [What are attention masks?](../glossary#attention-mask)
548
+ head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
549
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
550
+
551
+ - 1 indicates the head is **not masked**,
552
+ - 0 indicates the head is **masked**.
553
+
554
+ inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
555
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
556
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
557
+ model's internal embedding lookup matrix.
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. This argument can be used only in eager mode, in graph mode the value in the
561
+ config will be used instead.
562
+ output_hidden_states (`bool`, *optional*):
563
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
564
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
565
+ used instead.
566
+ return_dict (`bool`, *optional*):
567
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
568
+ eager mode, in graph mode the value will always be set to True.
569
+ training (`bool`, *optional*, defaults to `False`):
570
+ Whether or not to use the model in training mode (some modules like dropout modules have different
571
+ behaviors between training and evaluation).
572
+ """
573
+
574
+
575
+ @add_start_docstrings(
576
+ "The bare DistilBERT encoder/transformer outputting raw hidden-states without any specific head on top.",
577
+ DISTILBERT_START_DOCSTRING,
578
+ )
579
+ class TFDistilBertModel(TFDistilBertPreTrainedModel):
580
+ def __init__(self, config, *inputs, **kwargs):
581
+ super().__init__(config, *inputs, **kwargs)
582
+ self.distilbert = TFDistilBertMainLayer(config, name="distilbert") # Embeddings
583
+
584
+ @unpack_inputs
585
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
586
+ @add_code_sample_docstrings(
587
+ checkpoint=_CHECKPOINT_FOR_DOC,
588
+ output_type=TFBaseModelOutput,
589
+ config_class=_CONFIG_FOR_DOC,
590
+ )
591
+ def call(
592
+ self,
593
+ input_ids: TFModelInputType | None = None,
594
+ attention_mask: np.ndarray | tf.Tensor | None = None,
595
+ head_mask: np.ndarray | tf.Tensor | None = None,
596
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
597
+ output_attentions: Optional[bool] = None,
598
+ output_hidden_states: Optional[bool] = None,
599
+ return_dict: Optional[bool] = None,
600
+ training: Optional[bool] = False,
601
+ ) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:
602
+ outputs = self.distilbert(
603
+ input_ids=input_ids,
604
+ attention_mask=attention_mask,
605
+ head_mask=head_mask,
606
+ inputs_embeds=inputs_embeds,
607
+ output_attentions=output_attentions,
608
+ output_hidden_states=output_hidden_states,
609
+ return_dict=return_dict,
610
+ training=training,
611
+ )
612
+ return outputs
613
+
614
+ def build(self, input_shape=None):
615
+ if self.built:
616
+ return
617
+ self.built = True
618
+ if getattr(self, "distilbert", None) is not None:
619
+ with tf.name_scope(self.distilbert.name):
620
+ self.distilbert.build(None)
621
+
622
+
623
+ class TFDistilBertLMHead(keras.layers.Layer):
624
+ def __init__(self, config, input_embeddings, **kwargs):
625
+ super().__init__(**kwargs)
626
+
627
+ self.config = config
628
+ self.dim = config.dim
629
+
630
+ # The output weights are the same as the input embeddings, but there is
631
+ # an output-only bias for each token.
632
+ self.input_embeddings = input_embeddings
633
+
634
+ def build(self, input_shape):
635
+ self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
636
+
637
+ super().build(input_shape)
638
+
639
+ def get_output_embeddings(self):
640
+ return self.input_embeddings
641
+
642
+ def set_output_embeddings(self, value):
643
+ self.input_embeddings.weight = value
644
+ self.input_embeddings.vocab_size = shape_list(value)[0]
645
+
646
+ def get_bias(self):
647
+ return {"bias": self.bias}
648
+
649
+ def set_bias(self, value):
650
+ self.bias = value["bias"]
651
+ self.config.vocab_size = shape_list(value["bias"])[0]
652
+
653
+ def call(self, hidden_states):
654
+ seq_length = shape_list(tensor=hidden_states)[1]
655
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.dim])
656
+ hidden_states = tf.matmul(a=hidden_states, b=self.input_embeddings.weight, transpose_b=True)
657
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
658
+ hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
659
+
660
+ return hidden_states
661
+
662
+
663
+ @add_start_docstrings(
664
+ """DistilBert Model with a `masked language modeling` head on top.""",
665
+ DISTILBERT_START_DOCSTRING,
666
+ )
667
+ class TFDistilBertForMaskedLM(TFDistilBertPreTrainedModel, TFMaskedLanguageModelingLoss):
668
+ def __init__(self, config, *inputs, **kwargs):
669
+ super().__init__(config, *inputs, **kwargs)
670
+ self.config = config
671
+
672
+ self.distilbert = TFDistilBertMainLayer(config, name="distilbert")
673
+ self.vocab_transform = keras.layers.Dense(
674
+ config.dim, kernel_initializer=get_initializer(config.initializer_range), name="vocab_transform"
675
+ )
676
+ self.act = get_tf_activation(config.activation)
677
+ self.vocab_layer_norm = keras.layers.LayerNormalization(epsilon=1e-12, name="vocab_layer_norm")
678
+ self.vocab_projector = TFDistilBertLMHead(config, self.distilbert.embeddings, name="vocab_projector")
679
+
680
+ def get_lm_head(self):
681
+ return self.vocab_projector
682
+
683
+ def get_prefix_bias_name(self):
684
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
685
+ return self.name + "/" + self.vocab_projector.name
686
+
687
+ @unpack_inputs
688
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
689
+ @add_code_sample_docstrings(
690
+ checkpoint=_CHECKPOINT_FOR_DOC,
691
+ output_type=TFMaskedLMOutput,
692
+ config_class=_CONFIG_FOR_DOC,
693
+ )
694
+ def call(
695
+ self,
696
+ input_ids: TFModelInputType | None = None,
697
+ attention_mask: np.ndarray | tf.Tensor | None = None,
698
+ head_mask: np.ndarray | tf.Tensor | None = None,
699
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
700
+ output_attentions: Optional[bool] = None,
701
+ output_hidden_states: Optional[bool] = None,
702
+ return_dict: Optional[bool] = None,
703
+ labels: np.ndarray | tf.Tensor | None = None,
704
+ training: Optional[bool] = False,
705
+ ) -> Union[TFMaskedLMOutput, Tuple[tf.Tensor]]:
706
+ r"""
707
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
708
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
709
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
710
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
711
+ """
712
+ distilbert_output = self.distilbert(
713
+ input_ids=input_ids,
714
+ attention_mask=attention_mask,
715
+ head_mask=head_mask,
716
+ inputs_embeds=inputs_embeds,
717
+ output_attentions=output_attentions,
718
+ output_hidden_states=output_hidden_states,
719
+ return_dict=return_dict,
720
+ training=training,
721
+ )
722
+ hidden_states = distilbert_output[0] # (bs, seq_length, dim)
723
+ prediction_logits = self.vocab_transform(hidden_states) # (bs, seq_length, dim)
724
+ prediction_logits = self.act(prediction_logits) # (bs, seq_length, dim)
725
+ prediction_logits = self.vocab_layer_norm(prediction_logits) # (bs, seq_length, dim)
726
+ prediction_logits = self.vocab_projector(prediction_logits)
727
+
728
+ loss = None if labels is None else self.hf_compute_loss(labels, prediction_logits)
729
+
730
+ if not return_dict:
731
+ output = (prediction_logits,) + distilbert_output[1:]
732
+ return ((loss,) + output) if loss is not None else output
733
+
734
+ return TFMaskedLMOutput(
735
+ loss=loss,
736
+ logits=prediction_logits,
737
+ hidden_states=distilbert_output.hidden_states,
738
+ attentions=distilbert_output.attentions,
739
+ )
740
+
741
+ def build(self, input_shape=None):
742
+ if self.built:
743
+ return
744
+ self.built = True
745
+ if getattr(self, "distilbert", None) is not None:
746
+ with tf.name_scope(self.distilbert.name):
747
+ self.distilbert.build(None)
748
+ if getattr(self, "vocab_transform", None) is not None:
749
+ with tf.name_scope(self.vocab_transform.name):
750
+ self.vocab_transform.build([None, None, self.config.dim])
751
+ if getattr(self, "vocab_layer_norm", None) is not None:
752
+ with tf.name_scope(self.vocab_layer_norm.name):
753
+ self.vocab_layer_norm.build([None, None, self.config.dim])
754
+ if getattr(self, "vocab_projector", None) is not None:
755
+ with tf.name_scope(self.vocab_projector.name):
756
+ self.vocab_projector.build(None)
757
+
758
+
759
+ @add_start_docstrings(
760
+ """
761
+ DistilBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
762
+ pooled output) e.g. for GLUE tasks.
763
+ """,
764
+ DISTILBERT_START_DOCSTRING,
765
+ )
766
+ class TFDistilBertForSequenceClassification(TFDistilBertPreTrainedModel, TFSequenceClassificationLoss):
767
+ def __init__(self, config, *inputs, **kwargs):
768
+ super().__init__(config, *inputs, **kwargs)
769
+ self.num_labels = config.num_labels
770
+
771
+ self.distilbert = TFDistilBertMainLayer(config, name="distilbert")
772
+ self.pre_classifier = keras.layers.Dense(
773
+ config.dim,
774
+ kernel_initializer=get_initializer(config.initializer_range),
775
+ activation="relu",
776
+ name="pre_classifier",
777
+ )
778
+ self.classifier = keras.layers.Dense(
779
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
780
+ )
781
+ self.dropout = keras.layers.Dropout(config.seq_classif_dropout)
782
+ self.config = config
783
+
784
+ @unpack_inputs
785
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
786
+ @add_code_sample_docstrings(
787
+ checkpoint=_CHECKPOINT_FOR_DOC,
788
+ output_type=TFSequenceClassifierOutput,
789
+ config_class=_CONFIG_FOR_DOC,
790
+ )
791
+ def call(
792
+ self,
793
+ input_ids: TFModelInputType | None = None,
794
+ attention_mask: np.ndarray | tf.Tensor | None = None,
795
+ head_mask: np.ndarray | tf.Tensor | None = None,
796
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
797
+ output_attentions: Optional[bool] = None,
798
+ output_hidden_states: Optional[bool] = None,
799
+ return_dict: Optional[bool] = None,
800
+ labels: np.ndarray | tf.Tensor | None = None,
801
+ training: Optional[bool] = False,
802
+ ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
803
+ r"""
804
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
805
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
806
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
807
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
808
+ """
809
+ distilbert_output = self.distilbert(
810
+ input_ids=input_ids,
811
+ attention_mask=attention_mask,
812
+ head_mask=head_mask,
813
+ inputs_embeds=inputs_embeds,
814
+ output_attentions=output_attentions,
815
+ output_hidden_states=output_hidden_states,
816
+ return_dict=return_dict,
817
+ training=training,
818
+ )
819
+ hidden_state = distilbert_output[0] # (bs, seq_len, dim)
820
+ pooled_output = hidden_state[:, 0] # (bs, dim)
821
+ pooled_output = self.pre_classifier(pooled_output) # (bs, dim)
822
+ pooled_output = self.dropout(pooled_output, training=training) # (bs, dim)
823
+ logits = self.classifier(pooled_output) # (bs, dim)
824
+
825
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
826
+
827
+ if not return_dict:
828
+ output = (logits,) + distilbert_output[1:]
829
+ return ((loss,) + output) if loss is not None else output
830
+
831
+ return TFSequenceClassifierOutput(
832
+ loss=loss,
833
+ logits=logits,
834
+ hidden_states=distilbert_output.hidden_states,
835
+ attentions=distilbert_output.attentions,
836
+ )
837
+
838
+ def build(self, input_shape=None):
839
+ if self.built:
840
+ return
841
+ self.built = True
842
+ if getattr(self, "distilbert", None) is not None:
843
+ with tf.name_scope(self.distilbert.name):
844
+ self.distilbert.build(None)
845
+ if getattr(self, "pre_classifier", None) is not None:
846
+ with tf.name_scope(self.pre_classifier.name):
847
+ self.pre_classifier.build([None, None, self.config.dim])
848
+ if getattr(self, "classifier", None) is not None:
849
+ with tf.name_scope(self.classifier.name):
850
+ self.classifier.build([None, None, self.config.dim])
851
+
852
+
853
+ @add_start_docstrings(
854
+ """
855
+ DistilBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
856
+ for Named-Entity-Recognition (NER) tasks.
857
+ """,
858
+ DISTILBERT_START_DOCSTRING,
859
+ )
860
+ class TFDistilBertForTokenClassification(TFDistilBertPreTrainedModel, TFTokenClassificationLoss):
861
+ def __init__(self, config, *inputs, **kwargs):
862
+ super().__init__(config, *inputs, **kwargs)
863
+ self.num_labels = config.num_labels
864
+
865
+ self.distilbert = TFDistilBertMainLayer(config, name="distilbert")
866
+ self.dropout = keras.layers.Dropout(config.dropout)
867
+ self.classifier = keras.layers.Dense(
868
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
869
+ )
870
+ self.config = config
871
+
872
+ @unpack_inputs
873
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
874
+ @add_code_sample_docstrings(
875
+ checkpoint=_CHECKPOINT_FOR_DOC,
876
+ output_type=TFTokenClassifierOutput,
877
+ config_class=_CONFIG_FOR_DOC,
878
+ )
879
+ def call(
880
+ self,
881
+ input_ids: TFModelInputType | None = None,
882
+ attention_mask: np.ndarray | tf.Tensor | None = None,
883
+ head_mask: np.ndarray | tf.Tensor | None = None,
884
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
885
+ output_attentions: Optional[bool] = None,
886
+ output_hidden_states: Optional[bool] = None,
887
+ return_dict: Optional[bool] = None,
888
+ labels: np.ndarray | tf.Tensor | None = None,
889
+ training: Optional[bool] = False,
890
+ ) -> Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]:
891
+ r"""
892
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
893
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
894
+ """
895
+ outputs = self.distilbert(
896
+ input_ids=input_ids,
897
+ attention_mask=attention_mask,
898
+ head_mask=head_mask,
899
+ inputs_embeds=inputs_embeds,
900
+ output_attentions=output_attentions,
901
+ output_hidden_states=output_hidden_states,
902
+ return_dict=return_dict,
903
+ training=training,
904
+ )
905
+ sequence_output = outputs[0]
906
+ sequence_output = self.dropout(sequence_output, training=training)
907
+ logits = self.classifier(sequence_output)
908
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
909
+
910
+ if not return_dict:
911
+ output = (logits,) + outputs[1:]
912
+ return ((loss,) + output) if loss is not None else output
913
+
914
+ return TFTokenClassifierOutput(
915
+ loss=loss,
916
+ logits=logits,
917
+ hidden_states=outputs.hidden_states,
918
+ attentions=outputs.attentions,
919
+ )
920
+
921
+ def build(self, input_shape=None):
922
+ if self.built:
923
+ return
924
+ self.built = True
925
+ if getattr(self, "distilbert", None) is not None:
926
+ with tf.name_scope(self.distilbert.name):
927
+ self.distilbert.build(None)
928
+ if getattr(self, "classifier", None) is not None:
929
+ with tf.name_scope(self.classifier.name):
930
+ self.classifier.build([None, None, self.config.hidden_size])
931
+
932
+
933
+ @add_start_docstrings(
934
+ """
935
+ DistilBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
936
+ a softmax) e.g. for RocStories/SWAG tasks.
937
+ """,
938
+ DISTILBERT_START_DOCSTRING,
939
+ )
940
+ class TFDistilBertForMultipleChoice(TFDistilBertPreTrainedModel, TFMultipleChoiceLoss):
941
+ def __init__(self, config, *inputs, **kwargs):
942
+ super().__init__(config, *inputs, **kwargs)
943
+
944
+ self.distilbert = TFDistilBertMainLayer(config, name="distilbert")
945
+ self.dropout = keras.layers.Dropout(config.seq_classif_dropout)
946
+ self.pre_classifier = keras.layers.Dense(
947
+ config.dim,
948
+ kernel_initializer=get_initializer(config.initializer_range),
949
+ activation="relu",
950
+ name="pre_classifier",
951
+ )
952
+ self.classifier = keras.layers.Dense(
953
+ 1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
954
+ )
955
+ self.config = config
956
+
957
+ @unpack_inputs
958
+ @add_start_docstrings_to_model_forward(
959
+ DISTILBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
960
+ )
961
+ @add_code_sample_docstrings(
962
+ checkpoint=_CHECKPOINT_FOR_DOC,
963
+ output_type=TFMultipleChoiceModelOutput,
964
+ config_class=_CONFIG_FOR_DOC,
965
+ )
966
+ def call(
967
+ self,
968
+ input_ids: TFModelInputType | None = None,
969
+ attention_mask: np.ndarray | tf.Tensor | None = None,
970
+ head_mask: np.ndarray | tf.Tensor | None = None,
971
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
972
+ output_attentions: Optional[bool] = None,
973
+ output_hidden_states: Optional[bool] = None,
974
+ return_dict: Optional[bool] = None,
975
+ labels: np.ndarray | tf.Tensor | None = None,
976
+ training: Optional[bool] = False,
977
+ ) -> Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]:
978
+ r"""
979
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
980
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
981
+ where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
982
+ """
983
+ if input_ids is not None:
984
+ num_choices = shape_list(input_ids)[1]
985
+ seq_length = shape_list(input_ids)[2]
986
+ else:
987
+ num_choices = shape_list(inputs_embeds)[1]
988
+ seq_length = shape_list(inputs_embeds)[2]
989
+
990
+ flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
991
+ flat_attention_mask = tf.reshape(attention_mask, (-1, seq_length)) if attention_mask is not None else None
992
+ flat_inputs_embeds = (
993
+ tf.reshape(inputs_embeds, (-1, seq_length, shape_list(inputs_embeds)[3]))
994
+ if inputs_embeds is not None
995
+ else None
996
+ )
997
+ distilbert_output = self.distilbert(
998
+ flat_input_ids,
999
+ flat_attention_mask,
1000
+ head_mask,
1001
+ flat_inputs_embeds,
1002
+ output_attentions,
1003
+ output_hidden_states,
1004
+ return_dict=return_dict,
1005
+ training=training,
1006
+ )
1007
+ hidden_state = distilbert_output[0] # (bs, seq_len, dim)
1008
+ pooled_output = hidden_state[:, 0] # (bs, dim)
1009
+ pooled_output = self.pre_classifier(pooled_output) # (bs, dim)
1010
+ pooled_output = self.dropout(pooled_output, training=training) # (bs, dim)
1011
+ logits = self.classifier(pooled_output)
1012
+ reshaped_logits = tf.reshape(logits, (-1, num_choices))
1013
+
1014
+ loss = None if labels is None else self.hf_compute_loss(labels, reshaped_logits)
1015
+
1016
+ if not return_dict:
1017
+ output = (reshaped_logits,) + distilbert_output[1:]
1018
+ return ((loss,) + output) if loss is not None else output
1019
+
1020
+ return TFMultipleChoiceModelOutput(
1021
+ loss=loss,
1022
+ logits=reshaped_logits,
1023
+ hidden_states=distilbert_output.hidden_states,
1024
+ attentions=distilbert_output.attentions,
1025
+ )
1026
+
1027
+ def build(self, input_shape=None):
1028
+ if self.built:
1029
+ return
1030
+ self.built = True
1031
+ if getattr(self, "distilbert", None) is not None:
1032
+ with tf.name_scope(self.distilbert.name):
1033
+ self.distilbert.build(None)
1034
+ if getattr(self, "pre_classifier", None) is not None:
1035
+ with tf.name_scope(self.pre_classifier.name):
1036
+ self.pre_classifier.build([None, None, self.config.dim])
1037
+ if getattr(self, "classifier", None) is not None:
1038
+ with tf.name_scope(self.classifier.name):
1039
+ self.classifier.build([None, None, self.config.dim])
1040
+
1041
+
1042
+ @add_start_docstrings(
1043
+ """
1044
+ DistilBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
1045
+ linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1046
+ """,
1047
+ DISTILBERT_START_DOCSTRING,
1048
+ )
1049
+ class TFDistilBertForQuestionAnswering(TFDistilBertPreTrainedModel, TFQuestionAnsweringLoss):
1050
+ def __init__(self, config, *inputs, **kwargs):
1051
+ super().__init__(config, *inputs, **kwargs)
1052
+
1053
+ self.distilbert = TFDistilBertMainLayer(config, name="distilbert")
1054
+ self.qa_outputs = keras.layers.Dense(
1055
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
1056
+ )
1057
+ assert config.num_labels == 2, f"Incorrect number of labels {config.num_labels} instead of 2"
1058
+ self.dropout = keras.layers.Dropout(config.qa_dropout)
1059
+ self.config = config
1060
+
1061
+ @unpack_inputs
1062
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1063
+ @add_code_sample_docstrings(
1064
+ checkpoint=_CHECKPOINT_FOR_DOC,
1065
+ output_type=TFQuestionAnsweringModelOutput,
1066
+ config_class=_CONFIG_FOR_DOC,
1067
+ )
1068
+ def call(
1069
+ self,
1070
+ input_ids: TFModelInputType | None = None,
1071
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1072
+ head_mask: np.ndarray | tf.Tensor | None = None,
1073
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1074
+ output_attentions: Optional[bool] = None,
1075
+ output_hidden_states: Optional[bool] = None,
1076
+ return_dict: Optional[bool] = None,
1077
+ start_positions: np.ndarray | tf.Tensor | None = None,
1078
+ end_positions: np.ndarray | tf.Tensor | None = None,
1079
+ training: Optional[bool] = False,
1080
+ ) -> Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]:
1081
+ r"""
1082
+ start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1083
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1084
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1085
+ are not taken into account for computing the loss.
1086
+ end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1087
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1088
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1089
+ are not taken into account for computing the loss.
1090
+ """
1091
+ distilbert_output = self.distilbert(
1092
+ input_ids=input_ids,
1093
+ attention_mask=attention_mask,
1094
+ head_mask=head_mask,
1095
+ inputs_embeds=inputs_embeds,
1096
+ output_attentions=output_attentions,
1097
+ output_hidden_states=output_hidden_states,
1098
+ return_dict=return_dict,
1099
+ training=training,
1100
+ )
1101
+ hidden_states = distilbert_output[0] # (bs, max_query_len, dim)
1102
+ hidden_states = self.dropout(hidden_states, training=training) # (bs, max_query_len, dim)
1103
+ logits = self.qa_outputs(hidden_states) # (bs, max_query_len, 2)
1104
+ start_logits, end_logits = tf.split(logits, 2, axis=-1)
1105
+ start_logits = tf.squeeze(start_logits, axis=-1)
1106
+ end_logits = tf.squeeze(end_logits, axis=-1)
1107
+
1108
+ loss = None
1109
+ if start_positions is not None and end_positions is not None:
1110
+ labels = {"start_position": start_positions}
1111
+ labels["end_position"] = end_positions
1112
+ loss = self.hf_compute_loss(labels, (start_logits, end_logits))
1113
+
1114
+ if not return_dict:
1115
+ output = (start_logits, end_logits) + distilbert_output[1:]
1116
+ return ((loss,) + output) if loss is not None else output
1117
+
1118
+ return TFQuestionAnsweringModelOutput(
1119
+ loss=loss,
1120
+ start_logits=start_logits,
1121
+ end_logits=end_logits,
1122
+ hidden_states=distilbert_output.hidden_states,
1123
+ attentions=distilbert_output.attentions,
1124
+ )
1125
+
1126
+ def build(self, input_shape=None):
1127
+ if self.built:
1128
+ return
1129
+ self.built = True
1130
+ if getattr(self, "distilbert", None) is not None:
1131
+ with tf.name_scope(self.distilbert.name):
1132
+ self.distilbert.build(None)
1133
+ if getattr(self, "qa_outputs", None) is not None:
1134
+ with tf.name_scope(self.qa_outputs.name):
1135
+ self.qa_outputs.build([None, None, self.config.dim])
1136
+
1137
+
1138
+ __all__ = [
1139
+ "TFDistilBertForMaskedLM",
1140
+ "TFDistilBertForMultipleChoice",
1141
+ "TFDistilBertForQuestionAnswering",
1142
+ "TFDistilBertForSequenceClassification",
1143
+ "TFDistilBertForTokenClassification",
1144
+ "TFDistilBertMainLayer",
1145
+ "TFDistilBertModel",
1146
+ "TFDistilBertPreTrainedModel",
1147
+ ]
vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/tokenization_distilbert.py ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for DistilBERT."""
16
+
17
+ import collections
18
+ import os
19
+ import unicodedata
20
+ from typing import List, Optional, Tuple
21
+
22
+ from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
23
+ from ...utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
29
+
30
+
31
+ # Copied from transformers.models.bert.tokenization_bert.load_vocab
32
+ def load_vocab(vocab_file):
33
+ """Loads a vocabulary file into a dictionary."""
34
+ vocab = collections.OrderedDict()
35
+ with open(vocab_file, "r", encoding="utf-8") as reader:
36
+ tokens = reader.readlines()
37
+ for index, token in enumerate(tokens):
38
+ token = token.rstrip("\n")
39
+ vocab[token] = index
40
+ return vocab
41
+
42
+
43
+ # Copied from transformers.models.bert.tokenization_bert.whitespace_tokenize
44
+ def whitespace_tokenize(text):
45
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
46
+ text = text.strip()
47
+ if not text:
48
+ return []
49
+ tokens = text.split()
50
+ return tokens
51
+
52
+
53
+ class DistilBertTokenizer(PreTrainedTokenizer):
54
+ r"""
55
+ Construct a DistilBERT tokenizer. Based on WordPiece.
56
+
57
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
58
+ this superclass for more information regarding those methods.
59
+
60
+ Args:
61
+ vocab_file (`str`):
62
+ File containing the vocabulary.
63
+ do_lower_case (`bool`, *optional*, defaults to `True`):
64
+ Whether or not to lowercase the input when tokenizing.
65
+ do_basic_tokenize (`bool`, *optional*, defaults to `True`):
66
+ Whether or not to do basic tokenization before WordPiece.
67
+ never_split (`Iterable`, *optional*):
68
+ Collection of tokens which will never be split during tokenization. Only has an effect when
69
+ `do_basic_tokenize=True`
70
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
71
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
72
+ token instead.
73
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
74
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
75
+ sequence classification or for a text and a question for question answering. It is also used as the last
76
+ token of a sequence built with special tokens.
77
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
78
+ The token used for padding, for example when batching sequences of different lengths.
79
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
80
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
81
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
82
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
83
+ The token used for masking values. This is the token used when training this model with masked language
84
+ modeling. This is the token which the model will try to predict.
85
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
86
+ Whether or not to tokenize Chinese characters.
87
+
88
+ This should likely be deactivated for Japanese (see this
89
+ [issue](https://github.com/huggingface/transformers/issues/328)).
90
+ strip_accents (`bool`, *optional*):
91
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
92
+ value for `lowercase` (as in the original BERT).
93
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
94
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
95
+ extra spaces.
96
+ """
97
+
98
+ vocab_files_names = VOCAB_FILES_NAMES
99
+ model_input_names = ["input_ids", "attention_mask"]
100
+
101
+ def __init__(
102
+ self,
103
+ vocab_file,
104
+ do_lower_case=True,
105
+ do_basic_tokenize=True,
106
+ never_split=None,
107
+ unk_token="[UNK]",
108
+ sep_token="[SEP]",
109
+ pad_token="[PAD]",
110
+ cls_token="[CLS]",
111
+ mask_token="[MASK]",
112
+ tokenize_chinese_chars=True,
113
+ strip_accents=None,
114
+ clean_up_tokenization_spaces=True,
115
+ **kwargs,
116
+ ):
117
+ if not os.path.isfile(vocab_file):
118
+ raise ValueError(
119
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
120
+ " model use `tokenizer = DistilBertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
121
+ )
122
+ self.vocab = load_vocab(vocab_file)
123
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
124
+ self.do_basic_tokenize = do_basic_tokenize
125
+ if do_basic_tokenize:
126
+ self.basic_tokenizer = BasicTokenizer(
127
+ do_lower_case=do_lower_case,
128
+ never_split=never_split,
129
+ tokenize_chinese_chars=tokenize_chinese_chars,
130
+ strip_accents=strip_accents,
131
+ )
132
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
133
+
134
+ super().__init__(
135
+ do_lower_case=do_lower_case,
136
+ do_basic_tokenize=do_basic_tokenize,
137
+ never_split=never_split,
138
+ unk_token=unk_token,
139
+ sep_token=sep_token,
140
+ pad_token=pad_token,
141
+ cls_token=cls_token,
142
+ mask_token=mask_token,
143
+ tokenize_chinese_chars=tokenize_chinese_chars,
144
+ strip_accents=strip_accents,
145
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
146
+ **kwargs,
147
+ )
148
+
149
+ @property
150
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.do_lower_case
151
+ def do_lower_case(self):
152
+ return self.basic_tokenizer.do_lower_case
153
+
154
+ @property
155
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.vocab_size
156
+ def vocab_size(self):
157
+ return len(self.vocab)
158
+
159
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.get_vocab
160
+ def get_vocab(self):
161
+ return dict(self.vocab, **self.added_tokens_encoder)
162
+
163
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer._tokenize
164
+ def _tokenize(self, text, split_special_tokens=False):
165
+ split_tokens = []
166
+ if self.do_basic_tokenize:
167
+ for token in self.basic_tokenizer.tokenize(
168
+ text, never_split=self.all_special_tokens if not split_special_tokens else None
169
+ ):
170
+ # If the token is part of the never_split set
171
+ if token in self.basic_tokenizer.never_split:
172
+ split_tokens.append(token)
173
+ else:
174
+ split_tokens += self.wordpiece_tokenizer.tokenize(token)
175
+ else:
176
+ split_tokens = self.wordpiece_tokenizer.tokenize(text)
177
+ return split_tokens
178
+
179
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer._convert_token_to_id
180
+ def _convert_token_to_id(self, token):
181
+ """Converts a token (str) in an id using the vocab."""
182
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
183
+
184
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer._convert_id_to_token
185
+ def _convert_id_to_token(self, index):
186
+ """Converts an index (integer) in a token (str) using the vocab."""
187
+ return self.ids_to_tokens.get(index, self.unk_token)
188
+
189
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.convert_tokens_to_string
190
+ def convert_tokens_to_string(self, tokens):
191
+ """Converts a sequence of tokens (string) in a single string."""
192
+ out_string = " ".join(tokens).replace(" ##", "").strip()
193
+ return out_string
194
+
195
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.build_inputs_with_special_tokens
196
+ def build_inputs_with_special_tokens(
197
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
198
+ ) -> List[int]:
199
+ """
200
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
201
+ adding special tokens. A BERT sequence has the following format:
202
+
203
+ - single sequence: `[CLS] X [SEP]`
204
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
205
+
206
+ Args:
207
+ token_ids_0 (`List[int]`):
208
+ List of IDs to which the special tokens will be added.
209
+ token_ids_1 (`List[int]`, *optional*):
210
+ Optional second list of IDs for sequence pairs.
211
+
212
+ Returns:
213
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
214
+ """
215
+ if token_ids_1 is None:
216
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
217
+ cls = [self.cls_token_id]
218
+ sep = [self.sep_token_id]
219
+ return cls + token_ids_0 + sep + token_ids_1 + sep
220
+
221
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.get_special_tokens_mask
222
+ def get_special_tokens_mask(
223
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
224
+ ) -> List[int]:
225
+ """
226
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
227
+ special tokens using the tokenizer `prepare_for_model` method.
228
+
229
+ Args:
230
+ token_ids_0 (`List[int]`):
231
+ List of IDs.
232
+ token_ids_1 (`List[int]`, *optional*):
233
+ Optional second list of IDs for sequence pairs.
234
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
235
+ Whether or not the token list is already formatted with special tokens for the model.
236
+
237
+ Returns:
238
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
239
+ """
240
+
241
+ if already_has_special_tokens:
242
+ return super().get_special_tokens_mask(
243
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
244
+ )
245
+
246
+ if token_ids_1 is not None:
247
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
248
+ return [1] + ([0] * len(token_ids_0)) + [1]
249
+
250
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.create_token_type_ids_from_sequences
251
+ def create_token_type_ids_from_sequences(
252
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
253
+ ) -> List[int]:
254
+ """
255
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence
256
+ pair mask has the following format:
257
+
258
+ ```
259
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
260
+ | first sequence | second sequence |
261
+ ```
262
+
263
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
264
+
265
+ Args:
266
+ token_ids_0 (`List[int]`):
267
+ List of IDs.
268
+ token_ids_1 (`List[int]`, *optional*):
269
+ Optional second list of IDs for sequence pairs.
270
+
271
+ Returns:
272
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
273
+ """
274
+ sep = [self.sep_token_id]
275
+ cls = [self.cls_token_id]
276
+ if token_ids_1 is None:
277
+ return len(cls + token_ids_0 + sep) * [0]
278
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
279
+
280
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.save_vocabulary
281
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
282
+ index = 0
283
+ if os.path.isdir(save_directory):
284
+ vocab_file = os.path.join(
285
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
286
+ )
287
+ else:
288
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
289
+ with open(vocab_file, "w", encoding="utf-8") as writer:
290
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
291
+ if index != token_index:
292
+ logger.warning(
293
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
294
+ " Please check that the vocabulary is not corrupted!"
295
+ )
296
+ index = token_index
297
+ writer.write(token + "\n")
298
+ index += 1
299
+ return (vocab_file,)
300
+
301
+
302
+ # Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
303
+ class BasicTokenizer:
304
+ """
305
+ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
306
+
307
+ Args:
308
+ do_lower_case (`bool`, *optional*, defaults to `True`):
309
+ Whether or not to lowercase the input when tokenizing.
310
+ never_split (`Iterable`, *optional*):
311
+ Collection of tokens which will never be split during tokenization. Only has an effect when
312
+ `do_basic_tokenize=True`
313
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
314
+ Whether or not to tokenize Chinese characters.
315
+
316
+ This should likely be deactivated for Japanese (see this
317
+ [issue](https://github.com/huggingface/transformers/issues/328)).
318
+ strip_accents (`bool`, *optional*):
319
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
320
+ value for `lowercase` (as in the original BERT).
321
+ do_split_on_punc (`bool`, *optional*, defaults to `True`):
322
+ In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
323
+ the full context of the words, such as contractions.
324
+ """
325
+
326
+ def __init__(
327
+ self,
328
+ do_lower_case=True,
329
+ never_split=None,
330
+ tokenize_chinese_chars=True,
331
+ strip_accents=None,
332
+ do_split_on_punc=True,
333
+ ):
334
+ if never_split is None:
335
+ never_split = []
336
+ self.do_lower_case = do_lower_case
337
+ self.never_split = set(never_split)
338
+ self.tokenize_chinese_chars = tokenize_chinese_chars
339
+ self.strip_accents = strip_accents
340
+ self.do_split_on_punc = do_split_on_punc
341
+
342
+ def tokenize(self, text, never_split=None):
343
+ """
344
+ Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
345
+
346
+ Args:
347
+ never_split (`List[str]`, *optional*)
348
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
349
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
350
+ """
351
+ # union() returns a new set by concatenating the two sets.
352
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
353
+ text = self._clean_text(text)
354
+
355
+ # This was added on November 1st, 2018 for the multilingual and Chinese
356
+ # models. This is also applied to the English models now, but it doesn't
357
+ # matter since the English models were not trained on any Chinese data
358
+ # and generally don't have any Chinese data in them (there are Chinese
359
+ # characters in the vocabulary because Wikipedia does have some Chinese
360
+ # words in the English Wikipedia.).
361
+ if self.tokenize_chinese_chars:
362
+ text = self._tokenize_chinese_chars(text)
363
+ # prevents treating the same character with different unicode codepoints as different characters
364
+ unicode_normalized_text = unicodedata.normalize("NFC", text)
365
+ orig_tokens = whitespace_tokenize(unicode_normalized_text)
366
+ split_tokens = []
367
+ for token in orig_tokens:
368
+ if token not in never_split:
369
+ if self.do_lower_case:
370
+ token = token.lower()
371
+ if self.strip_accents is not False:
372
+ token = self._run_strip_accents(token)
373
+ elif self.strip_accents:
374
+ token = self._run_strip_accents(token)
375
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
376
+
377
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
378
+ return output_tokens
379
+
380
+ def _run_strip_accents(self, text):
381
+ """Strips accents from a piece of text."""
382
+ text = unicodedata.normalize("NFD", text)
383
+ output = []
384
+ for char in text:
385
+ cat = unicodedata.category(char)
386
+ if cat == "Mn":
387
+ continue
388
+ output.append(char)
389
+ return "".join(output)
390
+
391
+ def _run_split_on_punc(self, text, never_split=None):
392
+ """Splits punctuation on a piece of text."""
393
+ if not self.do_split_on_punc or (never_split is not None and text in never_split):
394
+ return [text]
395
+ chars = list(text)
396
+ i = 0
397
+ start_new_word = True
398
+ output = []
399
+ while i < len(chars):
400
+ char = chars[i]
401
+ if _is_punctuation(char):
402
+ output.append([char])
403
+ start_new_word = True
404
+ else:
405
+ if start_new_word:
406
+ output.append([])
407
+ start_new_word = False
408
+ output[-1].append(char)
409
+ i += 1
410
+
411
+ return ["".join(x) for x in output]
412
+
413
+ def _tokenize_chinese_chars(self, text):
414
+ """Adds whitespace around any CJK character."""
415
+ output = []
416
+ for char in text:
417
+ cp = ord(char)
418
+ if self._is_chinese_char(cp):
419
+ output.append(" ")
420
+ output.append(char)
421
+ output.append(" ")
422
+ else:
423
+ output.append(char)
424
+ return "".join(output)
425
+
426
+ def _is_chinese_char(self, cp):
427
+ """Checks whether CP is the codepoint of a CJK character."""
428
+ # This defines a "chinese character" as anything in the CJK Unicode block:
429
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
430
+ #
431
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
432
+ # despite its name. The modern Korean Hangul alphabet is a different block,
433
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
434
+ # space-separated words, so they are not treated specially and handled
435
+ # like the all of the other languages.
436
+ if (
437
+ (cp >= 0x4E00 and cp <= 0x9FFF)
438
+ or (cp >= 0x3400 and cp <= 0x4DBF) #
439
+ or (cp >= 0x20000 and cp <= 0x2A6DF) #
440
+ or (cp >= 0x2A700 and cp <= 0x2B73F) #
441
+ or (cp >= 0x2B740 and cp <= 0x2B81F) #
442
+ or (cp >= 0x2B820 and cp <= 0x2CEAF) #
443
+ or (cp >= 0xF900 and cp <= 0xFAFF)
444
+ or (cp >= 0x2F800 and cp <= 0x2FA1F) #
445
+ ): #
446
+ return True
447
+
448
+ return False
449
+
450
+ def _clean_text(self, text):
451
+ """Performs invalid character removal and whitespace cleanup on text."""
452
+ output = []
453
+ for char in text:
454
+ cp = ord(char)
455
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
456
+ continue
457
+ if _is_whitespace(char):
458
+ output.append(" ")
459
+ else:
460
+ output.append(char)
461
+ return "".join(output)
462
+
463
+
464
+ # Copied from transformers.models.bert.tokenization_bert.WordpieceTokenizer
465
+ class WordpieceTokenizer:
466
+ """Runs WordPiece tokenization."""
467
+
468
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
469
+ self.vocab = vocab
470
+ self.unk_token = unk_token
471
+ self.max_input_chars_per_word = max_input_chars_per_word
472
+
473
+ def tokenize(self, text):
474
+ """
475
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
476
+ tokenization using the given vocabulary.
477
+
478
+ For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.
479
+
480
+ Args:
481
+ text: A single token or whitespace separated tokens. This should have
482
+ already been passed through *BasicTokenizer*.
483
+
484
+ Returns:
485
+ A list of wordpiece tokens.
486
+ """
487
+
488
+ output_tokens = []
489
+ for token in whitespace_tokenize(text):
490
+ chars = list(token)
491
+ if len(chars) > self.max_input_chars_per_word:
492
+ output_tokens.append(self.unk_token)
493
+ continue
494
+
495
+ is_bad = False
496
+ start = 0
497
+ sub_tokens = []
498
+ while start < len(chars):
499
+ end = len(chars)
500
+ cur_substr = None
501
+ while start < end:
502
+ substr = "".join(chars[start:end])
503
+ if start > 0:
504
+ substr = "##" + substr
505
+ if substr in self.vocab:
506
+ cur_substr = substr
507
+ break
508
+ end -= 1
509
+ if cur_substr is None:
510
+ is_bad = True
511
+ break
512
+ sub_tokens.append(cur_substr)
513
+ start = end
514
+
515
+ if is_bad:
516
+ output_tokens.append(self.unk_token)
517
+ else:
518
+ output_tokens.extend(sub_tokens)
519
+ return output_tokens
520
+
521
+
522
+ __all__ = ["DistilBertTokenizer"]
vlmpy310/lib/python3.10/site-packages/transformers/models/distilbert/tokenization_distilbert_fast.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for DistilBERT."""
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_distilbert import DistilBertTokenizer
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 DistilBertTokenizerFast(PreTrainedTokenizerFast):
33
+ r"""
34
+ Construct a "fast" DistilBERT 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
+ model_input_names = ["input_ids", "attention_mask"]
74
+ slow_tokenizer_class = DistilBertTokenizer
75
+
76
+ def __init__(
77
+ self,
78
+ vocab_file=None,
79
+ tokenizer_file=None,
80
+ do_lower_case=True,
81
+ unk_token="[UNK]",
82
+ sep_token="[SEP]",
83
+ pad_token="[PAD]",
84
+ cls_token="[CLS]",
85
+ mask_token="[MASK]",
86
+ tokenize_chinese_chars=True,
87
+ strip_accents=None,
88
+ **kwargs,
89
+ ):
90
+ super().__init__(
91
+ vocab_file,
92
+ tokenizer_file=tokenizer_file,
93
+ do_lower_case=do_lower_case,
94
+ unk_token=unk_token,
95
+ sep_token=sep_token,
96
+ pad_token=pad_token,
97
+ cls_token=cls_token,
98
+ mask_token=mask_token,
99
+ tokenize_chinese_chars=tokenize_chinese_chars,
100
+ strip_accents=strip_accents,
101
+ **kwargs,
102
+ )
103
+
104
+ normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
105
+ if (
106
+ normalizer_state.get("lowercase", do_lower_case) != do_lower_case
107
+ or normalizer_state.get("strip_accents", strip_accents) != strip_accents
108
+ or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
109
+ ):
110
+ normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
111
+ normalizer_state["lowercase"] = do_lower_case
112
+ normalizer_state["strip_accents"] = strip_accents
113
+ normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
114
+ self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
115
+
116
+ self.do_lower_case = do_lower_case
117
+
118
+ # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast.build_inputs_with_special_tokens
119
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
120
+ """
121
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
122
+ adding special tokens. A BERT sequence has the following format:
123
+
124
+ - single sequence: `[CLS] X [SEP]`
125
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
126
+
127
+ Args:
128
+ token_ids_0 (`List[int]`):
129
+ List of IDs to which the special tokens will be added.
130
+ token_ids_1 (`List[int]`, *optional*):
131
+ Optional second list of IDs for sequence pairs.
132
+
133
+ Returns:
134
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
135
+ """
136
+ output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
137
+
138
+ if token_ids_1 is not None:
139
+ output += token_ids_1 + [self.sep_token_id]
140
+
141
+ return output
142
+
143
+ # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast.create_token_type_ids_from_sequences
144
+ def create_token_type_ids_from_sequences(
145
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
146
+ ) -> List[int]:
147
+ """
148
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence
149
+ pair mask has the following format:
150
+
151
+ ```
152
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
153
+ | first sequence | second sequence |
154
+ ```
155
+
156
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
157
+
158
+ Args:
159
+ token_ids_0 (`List[int]`):
160
+ List of IDs.
161
+ token_ids_1 (`List[int]`, *optional*):
162
+ Optional second list of IDs for sequence pairs.
163
+
164
+ Returns:
165
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
166
+ """
167
+ sep = [self.sep_token_id]
168
+ cls = [self.cls_token_id]
169
+ if token_ids_1 is None:
170
+ return len(cls + token_ids_0 + sep) * [0]
171
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
172
+
173
+ # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast.save_vocabulary
174
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
175
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
176
+ return tuple(files)
177
+
178
+
179
+ __all__ = ["DistilBertTokenizerFast"]
vlmpy310/lib/python3.10/site-packages/transformers/models/levit/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_levit import *
22
+ from .feature_extraction_levit import *
23
+ from .image_processing_levit import *
24
+ from .modeling_levit import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
vlmpy310/lib/python3.10/site-packages/transformers/models/levit/configuration_levit.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Meta Platforms, Inc. and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """LeViT model configuration"""
16
+
17
+ from collections import OrderedDict
18
+ from typing import Mapping
19
+
20
+ from packaging import version
21
+
22
+ from ...configuration_utils import PretrainedConfig
23
+ from ...onnx import OnnxConfig
24
+ from ...utils import logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ class LevitConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`LevitModel`]. It is used to instantiate a LeViT
33
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
34
+ defaults will yield a similar configuration to that of the LeViT
35
+ [facebook/levit-128S](https://huggingface.co/facebook/levit-128S) architecture.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+ Args:
41
+ image_size (`int`, *optional*, defaults to 224):
42
+ The size of the input image.
43
+ num_channels (`int`, *optional*, defaults to 3):
44
+ Number of channels in the input image.
45
+ kernel_size (`int`, *optional*, defaults to 3):
46
+ The kernel size for the initial convolution layers of patch embedding.
47
+ stride (`int`, *optional*, defaults to 2):
48
+ The stride size for the initial convolution layers of patch embedding.
49
+ padding (`int`, *optional*, defaults to 1):
50
+ The padding size for the initial convolution layers of patch embedding.
51
+ patch_size (`int`, *optional*, defaults to 16):
52
+ The patch size for embeddings.
53
+ hidden_sizes (`List[int]`, *optional*, defaults to `[128, 256, 384]`):
54
+ Dimension of each of the encoder blocks.
55
+ num_attention_heads (`List[int]`, *optional*, defaults to `[4, 8, 12]`):
56
+ Number of attention heads for each attention layer in each block of the Transformer encoder.
57
+ depths (`List[int]`, *optional*, defaults to `[4, 4, 4]`):
58
+ The number of layers in each encoder block.
59
+ key_dim (`List[int]`, *optional*, defaults to `[16, 16, 16]`):
60
+ The size of key in each of the encoder blocks.
61
+ drop_path_rate (`int`, *optional*, defaults to 0):
62
+ The dropout probability for stochastic depths, used in the blocks of the Transformer encoder.
63
+ mlp_ratios (`List[int]`, *optional*, defaults to `[2, 2, 2]`):
64
+ Ratio of the size of the hidden layer compared to the size of the input layer of the Mix FFNs in the
65
+ encoder blocks.
66
+ attention_ratios (`List[int]`, *optional*, defaults to `[2, 2, 2]`):
67
+ Ratio of the size of the output dimension compared to input dimension of attention layers.
68
+ initializer_range (`float`, *optional*, defaults to 0.02):
69
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
70
+
71
+ Example:
72
+
73
+ ```python
74
+ >>> from transformers import LevitConfig, LevitModel
75
+
76
+ >>> # Initializing a LeViT levit-128S style configuration
77
+ >>> configuration = LevitConfig()
78
+
79
+ >>> # Initializing a model (with random weights) from the levit-128S style configuration
80
+ >>> model = LevitModel(configuration)
81
+
82
+ >>> # Accessing the model configuration
83
+ >>> configuration = model.config
84
+ ```"""
85
+
86
+ model_type = "levit"
87
+
88
+ def __init__(
89
+ self,
90
+ image_size=224,
91
+ num_channels=3,
92
+ kernel_size=3,
93
+ stride=2,
94
+ padding=1,
95
+ patch_size=16,
96
+ hidden_sizes=[128, 256, 384],
97
+ num_attention_heads=[4, 8, 12],
98
+ depths=[4, 4, 4],
99
+ key_dim=[16, 16, 16],
100
+ drop_path_rate=0,
101
+ mlp_ratio=[2, 2, 2],
102
+ attention_ratio=[2, 2, 2],
103
+ initializer_range=0.02,
104
+ **kwargs,
105
+ ):
106
+ super().__init__(**kwargs)
107
+ self.image_size = image_size
108
+ self.num_channels = num_channels
109
+ self.kernel_size = kernel_size
110
+ self.stride = stride
111
+ self.padding = padding
112
+ self.hidden_sizes = hidden_sizes
113
+ self.num_attention_heads = num_attention_heads
114
+ self.depths = depths
115
+ self.key_dim = key_dim
116
+ self.drop_path_rate = drop_path_rate
117
+ self.patch_size = patch_size
118
+ self.attention_ratio = attention_ratio
119
+ self.mlp_ratio = mlp_ratio
120
+ self.initializer_range = initializer_range
121
+ self.down_ops = [
122
+ ["Subsample", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
123
+ ["Subsample", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
124
+ ]
125
+
126
+
127
+ # Copied from transformers.models.vit.configuration_vit.ViTOnnxConfig
128
+ class LevitOnnxConfig(OnnxConfig):
129
+ torch_onnx_minimum_version = version.parse("1.11")
130
+
131
+ @property
132
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
133
+ return OrderedDict(
134
+ [
135
+ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
136
+ ]
137
+ )
138
+
139
+ @property
140
+ def atol_for_validation(self) -> float:
141
+ return 1e-4
142
+
143
+
144
+ __all__ = ["LevitConfig", "LevitOnnxConfig"]
vlmpy310/lib/python3.10/site-packages/transformers/models/levit/convert_levit_timm_to_pytorch.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Convert LeViT checkpoints from timm."""
16
+
17
+ import argparse
18
+ import json
19
+ from collections import OrderedDict
20
+ from functools import partial
21
+ from pathlib import Path
22
+
23
+ import timm
24
+ import torch
25
+ from huggingface_hub import hf_hub_download
26
+
27
+ from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor
28
+ from transformers.utils import logging
29
+
30
+
31
+ logging.set_verbosity_info()
32
+ logger = logging.get_logger()
33
+
34
+
35
+ def convert_weight_and_push(
36
+ hidden_sizes: int, name: str, config: LevitConfig, save_directory: Path, push_to_hub: bool = True
37
+ ):
38
+ print(f"Converting {name}...")
39
+
40
+ with torch.no_grad():
41
+ if hidden_sizes == 128:
42
+ if name[-1] == "S":
43
+ from_model = timm.create_model("levit_128s", pretrained=True)
44
+ else:
45
+ from_model = timm.create_model("levit_128", pretrained=True)
46
+ if hidden_sizes == 192:
47
+ from_model = timm.create_model("levit_192", pretrained=True)
48
+ if hidden_sizes == 256:
49
+ from_model = timm.create_model("levit_256", pretrained=True)
50
+ if hidden_sizes == 384:
51
+ from_model = timm.create_model("levit_384", pretrained=True)
52
+
53
+ from_model.eval()
54
+ our_model = LevitForImageClassificationWithTeacher(config).eval()
55
+ huggingface_weights = OrderedDict()
56
+
57
+ weights = from_model.state_dict()
58
+ og_keys = list(from_model.state_dict().keys())
59
+ new_keys = list(our_model.state_dict().keys())
60
+ print(len(og_keys), len(new_keys))
61
+ for i in range(len(og_keys)):
62
+ huggingface_weights[new_keys[i]] = weights[og_keys[i]]
63
+ our_model.load_state_dict(huggingface_weights)
64
+
65
+ x = torch.randn((2, 3, 224, 224))
66
+ out1 = from_model(x)
67
+ out2 = our_model(x).logits
68
+
69
+ assert torch.allclose(out1, out2), "The model logits don't match the original one."
70
+
71
+ checkpoint_name = name
72
+ print(checkpoint_name)
73
+
74
+ if push_to_hub:
75
+ our_model.save_pretrained(save_directory / checkpoint_name)
76
+ image_processor = LevitImageProcessor()
77
+ image_processor.save_pretrained(save_directory / checkpoint_name)
78
+
79
+ print(f"Pushed {checkpoint_name}")
80
+
81
+
82
+ def convert_weights_and_push(save_directory: Path, model_name: str = None, push_to_hub: bool = True):
83
+ filename = "imagenet-1k-id2label.json"
84
+ num_labels = 1000
85
+ expected_shape = (1, num_labels)
86
+
87
+ repo_id = "huggingface/label-files"
88
+ num_labels = num_labels
89
+ id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
90
+ id2label = {int(k): v for k, v in id2label.items()}
91
+
92
+ id2label = id2label
93
+ label2id = {v: k for k, v in id2label.items()}
94
+
95
+ ImageNetPreTrainedConfig = partial(LevitConfig, num_labels=num_labels, id2label=id2label, label2id=label2id)
96
+
97
+ names_to_hidden_sizes = {
98
+ "levit-128S": 128,
99
+ "levit-128": 128,
100
+ "levit-192": 192,
101
+ "levit-256": 256,
102
+ "levit-384": 384,
103
+ }
104
+
105
+ names_to_config = {
106
+ "levit-128S": ImageNetPreTrainedConfig(
107
+ hidden_sizes=[128, 256, 384],
108
+ num_attention_heads=[4, 6, 8],
109
+ depths=[2, 3, 4],
110
+ key_dim=[16, 16, 16],
111
+ drop_path_rate=0,
112
+ ),
113
+ "levit-128": ImageNetPreTrainedConfig(
114
+ hidden_sizes=[128, 256, 384],
115
+ num_attention_heads=[4, 8, 12],
116
+ depths=[4, 4, 4],
117
+ key_dim=[16, 16, 16],
118
+ drop_path_rate=0,
119
+ ),
120
+ "levit-192": ImageNetPreTrainedConfig(
121
+ hidden_sizes=[192, 288, 384],
122
+ num_attention_heads=[3, 5, 6],
123
+ depths=[4, 4, 4],
124
+ key_dim=[32, 32, 32],
125
+ drop_path_rate=0,
126
+ ),
127
+ "levit-256": ImageNetPreTrainedConfig(
128
+ hidden_sizes=[256, 384, 512],
129
+ num_attention_heads=[4, 6, 8],
130
+ depths=[4, 4, 4],
131
+ key_dim=[32, 32, 32],
132
+ drop_path_rate=0,
133
+ ),
134
+ "levit-384": ImageNetPreTrainedConfig(
135
+ hidden_sizes=[384, 512, 768],
136
+ num_attention_heads=[6, 9, 12],
137
+ depths=[4, 4, 4],
138
+ key_dim=[32, 32, 32],
139
+ drop_path_rate=0.1,
140
+ ),
141
+ }
142
+
143
+ if model_name:
144
+ convert_weight_and_push(
145
+ names_to_hidden_sizes[model_name], model_name, names_to_config[model_name], save_directory, push_to_hub
146
+ )
147
+ else:
148
+ for model_name, config in names_to_config.items():
149
+ convert_weight_and_push(names_to_hidden_sizes[model_name], model_name, config, save_directory, push_to_hub)
150
+ return config, expected_shape
151
+
152
+
153
+ if __name__ == "__main__":
154
+ parser = argparse.ArgumentParser()
155
+ # Required parameters
156
+ parser.add_argument(
157
+ "--model_name",
158
+ default=None,
159
+ type=str,
160
+ help="The name of the model you wish to convert, it must be one of the supported Levit* architecture,",
161
+ )
162
+ parser.add_argument(
163
+ "--pytorch_dump_folder_path",
164
+ default="levit-dump-folder/",
165
+ type=Path,
166
+ required=False,
167
+ help="Path to the output PyTorch model directory.",
168
+ )
169
+ parser.add_argument("--push_to_hub", action="store_true", help="Push model and image processor to the hub")
170
+ parser.add_argument(
171
+ "--no-push_to_hub",
172
+ dest="push_to_hub",
173
+ action="store_false",
174
+ help="Do not push model and image processor to the hub",
175
+ )
176
+
177
+ args = parser.parse_args()
178
+ pytorch_dump_folder_path: Path = args.pytorch_dump_folder_path
179
+ pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
180
+ convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
vlmpy310/lib/python3.10/site-packages/transformers/models/levit/feature_extraction_levit.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Meta Platforms, Inc. and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Feature extractor class for LeViT."""
16
+
17
+ import warnings
18
+
19
+ from ...utils import logging
20
+ from .image_processing_levit import LevitImageProcessor
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class LevitFeatureExtractor(LevitImageProcessor):
27
+ def __init__(self, *args, **kwargs) -> None:
28
+ warnings.warn(
29
+ "The class LevitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
30
+ " use LevitImageProcessor instead.",
31
+ FutureWarning,
32
+ )
33
+ super().__init__(*args, **kwargs)
34
+
35
+
36
+ __all__ = ["LevitFeatureExtractor"]
vlmpy310/lib/python3.10/site-packages/transformers/models/levit/image_processing_levit.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 LeViT."""
16
+
17
+ from typing import Dict, Iterable, 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 (
23
+ get_resize_output_image_size,
24
+ resize,
25
+ to_channel_dimension_format,
26
+ )
27
+ from ...image_utils import (
28
+ IMAGENET_DEFAULT_MEAN,
29
+ IMAGENET_DEFAULT_STD,
30
+ ChannelDimension,
31
+ ImageInput,
32
+ PILImageResampling,
33
+ infer_channel_dimension_format,
34
+ is_scaled_image,
35
+ make_list_of_images,
36
+ to_numpy_array,
37
+ valid_images,
38
+ validate_preprocess_arguments,
39
+ )
40
+ from ...utils import TensorType, filter_out_non_signature_kwargs, logging
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ class LevitImageProcessor(BaseImageProcessor):
47
+ r"""
48
+ Constructs a LeViT image processor.
49
+
50
+ Args:
51
+ do_resize (`bool`, *optional*, defaults to `True`):
52
+ Wwhether to resize the shortest edge of the input to int(256/224 *`size`). Can be overridden by the
53
+ `do_resize` parameter in the `preprocess` method.
54
+ size (`Dict[str, int]`, *optional*, defaults to `{"shortest_edge": 224}`):
55
+ Size of the output image after resizing. If size is a dict with keys "width" and "height", the image will
56
+ be resized to `(size["height"], size["width"])`. If size is a dict with key "shortest_edge", the shortest
57
+ edge value `c` is rescaled to `int(c * (256/224))`. The smaller edge of the image will be matched to this
58
+ value i.e, if height > width, then image will be rescaled to `(size["shortest_egde"] * height / width,
59
+ size["shortest_egde"])`. Can be overridden by the `size` parameter in the `preprocess` method.
60
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
61
+ Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
62
+ `preprocess` method.
63
+ do_center_crop (`bool`, *optional*, defaults to `True`):
64
+ Whether or not to center crop the input to `(crop_size["height"], crop_size["width"])`. Can be overridden
65
+ by the `do_center_crop` parameter in the `preprocess` method.
66
+ crop_size (`Dict`, *optional*, defaults to `{"height": 224, "width": 224}`):
67
+ Desired image size after `center_crop`. Can be overridden by the `crop_size` parameter in the `preprocess`
68
+ method.
69
+ do_rescale (`bool`, *optional*, defaults to `True`):
70
+ Controls whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
71
+ `do_rescale` parameter in the `preprocess` method.
72
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
73
+ Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
74
+ `preprocess` method.
75
+ do_normalize (`bool`, *optional*, defaults to `True`):
76
+ Controls whether to normalize the image. Can be overridden by the `do_normalize` parameter in the
77
+ `preprocess` method.
78
+ image_mean (`List[int]`, *optional*, defaults to `[0.485, 0.456, 0.406]`):
79
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
80
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
81
+ image_std (`List[int]`, *optional*, defaults to `[0.229, 0.224, 0.225]`):
82
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
83
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
84
+ """
85
+
86
+ model_input_names = ["pixel_values"]
87
+
88
+ def __init__(
89
+ self,
90
+ do_resize: bool = True,
91
+ size: Dict[str, int] = None,
92
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
93
+ do_center_crop: bool = True,
94
+ crop_size: Dict[str, int] = None,
95
+ do_rescale: bool = True,
96
+ rescale_factor: Union[int, float] = 1 / 255,
97
+ do_normalize: bool = True,
98
+ image_mean: Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN,
99
+ image_std: Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD,
100
+ **kwargs,
101
+ ) -> None:
102
+ super().__init__(**kwargs)
103
+ size = size if size is not None else {"shortest_edge": 224}
104
+ size = get_size_dict(size, default_to_square=False)
105
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
106
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
107
+
108
+ self.do_resize = do_resize
109
+ self.size = size
110
+ self.resample = resample
111
+ self.do_center_crop = do_center_crop
112
+ self.crop_size = crop_size
113
+ self.do_rescale = do_rescale
114
+ self.rescale_factor = rescale_factor
115
+ self.do_normalize = do_normalize
116
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
117
+ self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
118
+
119
+ def resize(
120
+ self,
121
+ image: np.ndarray,
122
+ size: Dict[str, int],
123
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
124
+ data_format: Optional[Union[str, ChannelDimension]] = None,
125
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
126
+ **kwargs,
127
+ ) -> np.ndarray:
128
+ """
129
+ Resize an image.
130
+
131
+ If size is a dict with keys "width" and "height", the image will be resized to `(size["height"],
132
+ size["width"])`.
133
+
134
+ If size is a dict with key "shortest_edge", the shortest edge value `c` is rescaled to `int(c * (256/224))`.
135
+ The smaller edge of the image will be matched to this value i.e, if height > width, then image will be rescaled
136
+ to `(size["shortest_egde"] * height / width, size["shortest_egde"])`.
137
+
138
+ Args:
139
+ image (`np.ndarray`):
140
+ Image to resize.
141
+ size (`Dict[str, int]`):
142
+ Size of the output image after resizing. If size is a dict with keys "width" and "height", the image
143
+ will be resized to (height, width). If size is a dict with key "shortest_edge", the shortest edge value
144
+ `c` is rescaled to int(`c` * (256/224)). The smaller edge of the image will be matched to this value
145
+ i.e, if height > width, then image will be rescaled to (size * height / width, size).
146
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
147
+ Resampling filter to use when resiizing the image.
148
+ data_format (`str` or `ChannelDimension`, *optional*):
149
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
150
+ input_data_format (`ChannelDimension` or `str`, *optional*):
151
+ The channel dimension format of the input image. If not provided, it will be inferred.
152
+ """
153
+ size_dict = get_size_dict(size, default_to_square=False)
154
+ # size_dict is a dict with either keys "height" and "width" or "shortest_edge"
155
+ if "shortest_edge" in size:
156
+ shortest_edge = int((256 / 224) * size["shortest_edge"])
157
+ output_size = get_resize_output_image_size(
158
+ image, size=shortest_edge, default_to_square=False, input_data_format=input_data_format
159
+ )
160
+ size_dict = {"height": output_size[0], "width": output_size[1]}
161
+ if "height" not in size_dict or "width" not in size_dict:
162
+ raise ValueError(
163
+ f"Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size_dict.keys()}"
164
+ )
165
+ return resize(
166
+ image,
167
+ size=(size_dict["height"], size_dict["width"]),
168
+ resample=resample,
169
+ data_format=data_format,
170
+ input_data_format=input_data_format,
171
+ **kwargs,
172
+ )
173
+
174
+ @filter_out_non_signature_kwargs()
175
+ def preprocess(
176
+ self,
177
+ images: ImageInput,
178
+ do_resize: Optional[bool] = None,
179
+ size: Optional[Dict[str, int]] = None,
180
+ resample: PILImageResampling = None,
181
+ do_center_crop: Optional[bool] = None,
182
+ crop_size: Optional[Dict[str, int]] = None,
183
+ do_rescale: Optional[bool] = None,
184
+ rescale_factor: Optional[float] = None,
185
+ do_normalize: Optional[bool] = None,
186
+ image_mean: Optional[Union[float, Iterable[float]]] = None,
187
+ image_std: Optional[Union[float, Iterable[float]]] = None,
188
+ return_tensors: Optional[TensorType] = None,
189
+ data_format: ChannelDimension = ChannelDimension.FIRST,
190
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
191
+ ) -> BatchFeature:
192
+ """
193
+ Preprocess an image or batch of images to be used as input to a LeViT model.
194
+
195
+ Args:
196
+ images (`ImageInput`):
197
+ Image or batch of images to preprocess. Expects a single or batch of images with pixel values ranging
198
+ from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.
199
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
200
+ Whether to resize the image.
201
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
202
+ Size of the output image after resizing. If size is a dict with keys "width" and "height", the image
203
+ will be resized to (height, width). If size is a dict with key "shortest_edge", the shortest edge value
204
+ `c` is rescaled to int(`c` * (256/224)). The smaller edge of the image will be matched to this value
205
+ i.e, if height > width, then image will be rescaled to (size * height / width, size).
206
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
207
+ Resampling filter to use when resiizing the image.
208
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
209
+ Whether to center crop the image.
210
+ crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
211
+ Size of the output image after center cropping. Crops images to (crop_size["height"],
212
+ crop_size["width"]).
213
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
214
+ Whether to rescale the image pixel values by `rescaling_factor` - typical to values between 0 and 1.
215
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
216
+ Factor to rescale the image pixel values by.
217
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
218
+ Whether to normalize the image pixel values by `image_mean` and `image_std`.
219
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
220
+ Mean to normalize the image pixel values by.
221
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
222
+ Standard deviation to normalize the image pixel values by.
223
+ return_tensors (`str` or `TensorType`, *optional*):
224
+ The type of tensors to return. Can be one of:
225
+ - Unset: Return a list of `np.ndarray`.
226
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
227
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
228
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
229
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
230
+ data_format (`str` or `ChannelDimension`, *optional*, defaults to `ChannelDimension.FIRST`):
231
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
232
+ image is used. Can be one of:
233
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
234
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
235
+ input_data_format (`ChannelDimension` or `str`, *optional*):
236
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
237
+ from the input image. Can be one of:
238
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
239
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
240
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
241
+ """
242
+ do_resize = do_resize if do_resize is not None else self.do_resize
243
+ resample = resample if resample is not None else self.resample
244
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
245
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
246
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
247
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
248
+ image_mean = image_mean if image_mean is not None else self.image_mean
249
+ image_std = image_std if image_std is not None else self.image_std
250
+
251
+ size = size if size is not None else self.size
252
+ size = get_size_dict(size, default_to_square=False)
253
+ crop_size = crop_size if crop_size is not None else self.crop_size
254
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
255
+ images = make_list_of_images(images)
256
+
257
+ if not valid_images(images):
258
+ raise ValueError(
259
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
260
+ "torch.Tensor, tf.Tensor or jax.ndarray."
261
+ )
262
+ validate_preprocess_arguments(
263
+ do_rescale=do_rescale,
264
+ rescale_factor=rescale_factor,
265
+ do_normalize=do_normalize,
266
+ image_mean=image_mean,
267
+ image_std=image_std,
268
+ do_center_crop=do_center_crop,
269
+ crop_size=crop_size,
270
+ do_resize=do_resize,
271
+ size=size,
272
+ resample=resample,
273
+ )
274
+ # All transformations expect numpy arrays.
275
+ images = [to_numpy_array(image) for image in images]
276
+
277
+ if do_rescale and is_scaled_image(images[0]):
278
+ logger.warning_once(
279
+ "It looks like you are trying to rescale already rescaled images. If the input"
280
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
281
+ )
282
+
283
+ if input_data_format is None:
284
+ # We assume that all images have the same channel dimension format.
285
+ input_data_format = infer_channel_dimension_format(images[0])
286
+
287
+ if do_resize:
288
+ images = [self.resize(image, size, resample, input_data_format=input_data_format) for image in images]
289
+
290
+ if do_center_crop:
291
+ images = [self.center_crop(image, crop_size, input_data_format=input_data_format) for image in images]
292
+
293
+ if do_rescale:
294
+ images = [self.rescale(image, rescale_factor, input_data_format=input_data_format) for image in images]
295
+
296
+ if do_normalize:
297
+ images = [
298
+ self.normalize(image, image_mean, image_std, input_data_format=input_data_format) for image in images
299
+ ]
300
+
301
+ images = [
302
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
303
+ ]
304
+
305
+ data = {"pixel_values": images}
306
+ return BatchFeature(data=data, tensor_type=return_tensors)
307
+
308
+
309
+ __all__ = ["LevitImageProcessor"]
vlmpy310/lib/python3.10/site-packages/transformers/models/levit/modeling_levit.py ADDED
@@ -0,0 +1,743 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Meta Platforms, Inc. and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch LeViT model."""
16
+
17
+ import itertools
18
+ from dataclasses import dataclass
19
+ from typing import Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
25
+
26
+ from ...modeling_outputs import (
27
+ BaseModelOutputWithNoAttention,
28
+ BaseModelOutputWithPoolingAndNoAttention,
29
+ ImageClassifierOutputWithNoAttention,
30
+ ModelOutput,
31
+ )
32
+ from ...modeling_utils import PreTrainedModel
33
+ from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
34
+ from .configuration_levit import LevitConfig
35
+
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+ # General docstring
40
+ _CONFIG_FOR_DOC = "LevitConfig"
41
+
42
+ # Base docstring
43
+ _CHECKPOINT_FOR_DOC = "facebook/levit-128S"
44
+ _EXPECTED_OUTPUT_SHAPE = [1, 16, 384]
45
+
46
+ # Image classification docstring
47
+ _IMAGE_CLASS_CHECKPOINT = "facebook/levit-128S"
48
+ _IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
49
+
50
+
51
+ @dataclass
52
+ class LevitForImageClassificationWithTeacherOutput(ModelOutput):
53
+ """
54
+ Output type of [`LevitForImageClassificationWithTeacher`].
55
+
56
+ Args:
57
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
58
+ Prediction scores as the average of the `cls_logits` and `distillation_logits`.
59
+ cls_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
60
+ Prediction scores of the classification head (i.e. the linear layer on top of the final hidden state of the
61
+ class token).
62
+ distillation_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
63
+ Prediction scores of the distillation head (i.e. the linear layer on top of the final hidden state of the
64
+ distillation token).
65
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
66
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
67
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
68
+ plus the initial embedding outputs.
69
+ """
70
+
71
+ logits: torch.FloatTensor = None
72
+ cls_logits: torch.FloatTensor = None
73
+ distillation_logits: torch.FloatTensor = None
74
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
75
+
76
+
77
+ class LevitConvEmbeddings(nn.Module):
78
+ """
79
+ LeViT Conv Embeddings with Batch Norm, used in the initial patch embedding layer.
80
+ """
81
+
82
+ def __init__(
83
+ self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, groups=1, bn_weight_init=1
84
+ ):
85
+ super().__init__()
86
+ self.convolution = nn.Conv2d(
87
+ in_channels, out_channels, kernel_size, stride, padding, dilation=dilation, groups=groups, bias=False
88
+ )
89
+ self.batch_norm = nn.BatchNorm2d(out_channels)
90
+
91
+ def forward(self, embeddings):
92
+ embeddings = self.convolution(embeddings)
93
+ embeddings = self.batch_norm(embeddings)
94
+ return embeddings
95
+
96
+
97
+ class LevitPatchEmbeddings(nn.Module):
98
+ """
99
+ LeViT patch embeddings, for final embeddings to be passed to transformer blocks. It consists of multiple
100
+ `LevitConvEmbeddings`.
101
+ """
102
+
103
+ def __init__(self, config):
104
+ super().__init__()
105
+ self.embedding_layer_1 = LevitConvEmbeddings(
106
+ config.num_channels, config.hidden_sizes[0] // 8, config.kernel_size, config.stride, config.padding
107
+ )
108
+ self.activation_layer_1 = nn.Hardswish()
109
+
110
+ self.embedding_layer_2 = LevitConvEmbeddings(
111
+ config.hidden_sizes[0] // 8, config.hidden_sizes[0] // 4, config.kernel_size, config.stride, config.padding
112
+ )
113
+ self.activation_layer_2 = nn.Hardswish()
114
+
115
+ self.embedding_layer_3 = LevitConvEmbeddings(
116
+ config.hidden_sizes[0] // 4, config.hidden_sizes[0] // 2, config.kernel_size, config.stride, config.padding
117
+ )
118
+ self.activation_layer_3 = nn.Hardswish()
119
+
120
+ self.embedding_layer_4 = LevitConvEmbeddings(
121
+ config.hidden_sizes[0] // 2, config.hidden_sizes[0], config.kernel_size, config.stride, config.padding
122
+ )
123
+ self.num_channels = config.num_channels
124
+
125
+ def forward(self, pixel_values):
126
+ num_channels = pixel_values.shape[1]
127
+ if num_channels != self.num_channels:
128
+ raise ValueError(
129
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
130
+ )
131
+ embeddings = self.embedding_layer_1(pixel_values)
132
+ embeddings = self.activation_layer_1(embeddings)
133
+ embeddings = self.embedding_layer_2(embeddings)
134
+ embeddings = self.activation_layer_2(embeddings)
135
+ embeddings = self.embedding_layer_3(embeddings)
136
+ embeddings = self.activation_layer_3(embeddings)
137
+ embeddings = self.embedding_layer_4(embeddings)
138
+ return embeddings.flatten(2).transpose(1, 2)
139
+
140
+
141
+ class MLPLayerWithBN(nn.Module):
142
+ def __init__(self, input_dim, output_dim, bn_weight_init=1):
143
+ super().__init__()
144
+ self.linear = nn.Linear(in_features=input_dim, out_features=output_dim, bias=False)
145
+ self.batch_norm = nn.BatchNorm1d(output_dim)
146
+
147
+ def forward(self, hidden_state):
148
+ hidden_state = self.linear(hidden_state)
149
+ hidden_state = self.batch_norm(hidden_state.flatten(0, 1)).reshape_as(hidden_state)
150
+ return hidden_state
151
+
152
+
153
+ class LevitSubsample(nn.Module):
154
+ def __init__(self, stride, resolution):
155
+ super().__init__()
156
+ self.stride = stride
157
+ self.resolution = resolution
158
+
159
+ def forward(self, hidden_state):
160
+ batch_size, _, channels = hidden_state.shape
161
+ hidden_state = hidden_state.view(batch_size, self.resolution, self.resolution, channels)[
162
+ :, :: self.stride, :: self.stride
163
+ ].reshape(batch_size, -1, channels)
164
+ return hidden_state
165
+
166
+
167
+ class LevitAttention(nn.Module):
168
+ def __init__(self, hidden_sizes, key_dim, num_attention_heads, attention_ratio, resolution):
169
+ super().__init__()
170
+ self.num_attention_heads = num_attention_heads
171
+ self.scale = key_dim**-0.5
172
+ self.key_dim = key_dim
173
+ self.attention_ratio = attention_ratio
174
+ self.out_dim_keys_values = attention_ratio * key_dim * num_attention_heads + key_dim * num_attention_heads * 2
175
+ self.out_dim_projection = attention_ratio * key_dim * num_attention_heads
176
+
177
+ self.queries_keys_values = MLPLayerWithBN(hidden_sizes, self.out_dim_keys_values)
178
+ self.activation = nn.Hardswish()
179
+ self.projection = MLPLayerWithBN(self.out_dim_projection, hidden_sizes, bn_weight_init=0)
180
+
181
+ points = list(itertools.product(range(resolution), range(resolution)))
182
+ len_points = len(points)
183
+ attention_offsets, indices = {}, []
184
+ for p1 in points:
185
+ for p2 in points:
186
+ offset = (abs(p1[0] - p2[0]), abs(p1[1] - p2[1]))
187
+ if offset not in attention_offsets:
188
+ attention_offsets[offset] = len(attention_offsets)
189
+ indices.append(attention_offsets[offset])
190
+
191
+ self.attention_bias_cache = {}
192
+ self.attention_biases = torch.nn.Parameter(torch.zeros(num_attention_heads, len(attention_offsets)))
193
+ self.register_buffer(
194
+ "attention_bias_idxs", torch.LongTensor(indices).view(len_points, len_points), persistent=False
195
+ )
196
+
197
+ @torch.no_grad()
198
+ def train(self, mode=True):
199
+ super().train(mode)
200
+ if mode and self.attention_bias_cache:
201
+ self.attention_bias_cache = {} # clear ab cache
202
+
203
+ def get_attention_biases(self, device):
204
+ if self.training:
205
+ return self.attention_biases[:, self.attention_bias_idxs]
206
+ else:
207
+ device_key = str(device)
208
+ if device_key not in self.attention_bias_cache:
209
+ self.attention_bias_cache[device_key] = self.attention_biases[:, self.attention_bias_idxs]
210
+ return self.attention_bias_cache[device_key]
211
+
212
+ def forward(self, hidden_state):
213
+ batch_size, seq_length, _ = hidden_state.shape
214
+ queries_keys_values = self.queries_keys_values(hidden_state)
215
+ query, key, value = queries_keys_values.view(batch_size, seq_length, self.num_attention_heads, -1).split(
216
+ [self.key_dim, self.key_dim, self.attention_ratio * self.key_dim], dim=3
217
+ )
218
+ query = query.permute(0, 2, 1, 3)
219
+ key = key.permute(0, 2, 1, 3)
220
+ value = value.permute(0, 2, 1, 3)
221
+
222
+ attention = query @ key.transpose(-2, -1) * self.scale + self.get_attention_biases(hidden_state.device)
223
+ attention = attention.softmax(dim=-1)
224
+ hidden_state = (attention @ value).transpose(1, 2).reshape(batch_size, seq_length, self.out_dim_projection)
225
+ hidden_state = self.projection(self.activation(hidden_state))
226
+ return hidden_state
227
+
228
+
229
+ class LevitAttentionSubsample(nn.Module):
230
+ def __init__(
231
+ self,
232
+ input_dim,
233
+ output_dim,
234
+ key_dim,
235
+ num_attention_heads,
236
+ attention_ratio,
237
+ stride,
238
+ resolution_in,
239
+ resolution_out,
240
+ ):
241
+ super().__init__()
242
+ self.num_attention_heads = num_attention_heads
243
+ self.scale = key_dim**-0.5
244
+ self.key_dim = key_dim
245
+ self.attention_ratio = attention_ratio
246
+ self.out_dim_keys_values = attention_ratio * key_dim * num_attention_heads + key_dim * num_attention_heads
247
+ self.out_dim_projection = attention_ratio * key_dim * num_attention_heads
248
+ self.resolution_out = resolution_out
249
+ # resolution_in is the intial resolution, resoloution_out is final resolution after downsampling
250
+ self.keys_values = MLPLayerWithBN(input_dim, self.out_dim_keys_values)
251
+ self.queries_subsample = LevitSubsample(stride, resolution_in)
252
+ self.queries = MLPLayerWithBN(input_dim, key_dim * num_attention_heads)
253
+ self.activation = nn.Hardswish()
254
+ self.projection = MLPLayerWithBN(self.out_dim_projection, output_dim)
255
+
256
+ self.attention_bias_cache = {}
257
+
258
+ points = list(itertools.product(range(resolution_in), range(resolution_in)))
259
+ points_ = list(itertools.product(range(resolution_out), range(resolution_out)))
260
+ len_points, len_points_ = len(points), len(points_)
261
+ attention_offsets, indices = {}, []
262
+ for p1 in points_:
263
+ for p2 in points:
264
+ size = 1
265
+ offset = (abs(p1[0] * stride - p2[0] + (size - 1) / 2), abs(p1[1] * stride - p2[1] + (size - 1) / 2))
266
+ if offset not in attention_offsets:
267
+ attention_offsets[offset] = len(attention_offsets)
268
+ indices.append(attention_offsets[offset])
269
+
270
+ self.attention_biases = torch.nn.Parameter(torch.zeros(num_attention_heads, len(attention_offsets)))
271
+ self.register_buffer(
272
+ "attention_bias_idxs", torch.LongTensor(indices).view(len_points_, len_points), persistent=False
273
+ )
274
+
275
+ @torch.no_grad()
276
+ def train(self, mode=True):
277
+ super().train(mode)
278
+ if mode and self.attention_bias_cache:
279
+ self.attention_bias_cache = {} # clear ab cache
280
+
281
+ def get_attention_biases(self, device):
282
+ if self.training:
283
+ return self.attention_biases[:, self.attention_bias_idxs]
284
+ else:
285
+ device_key = str(device)
286
+ if device_key not in self.attention_bias_cache:
287
+ self.attention_bias_cache[device_key] = self.attention_biases[:, self.attention_bias_idxs]
288
+ return self.attention_bias_cache[device_key]
289
+
290
+ def forward(self, hidden_state):
291
+ batch_size, seq_length, _ = hidden_state.shape
292
+ key, value = (
293
+ self.keys_values(hidden_state)
294
+ .view(batch_size, seq_length, self.num_attention_heads, -1)
295
+ .split([self.key_dim, self.attention_ratio * self.key_dim], dim=3)
296
+ )
297
+ key = key.permute(0, 2, 1, 3)
298
+ value = value.permute(0, 2, 1, 3)
299
+
300
+ query = self.queries(self.queries_subsample(hidden_state))
301
+ query = query.view(batch_size, self.resolution_out**2, self.num_attention_heads, self.key_dim).permute(
302
+ 0, 2, 1, 3
303
+ )
304
+
305
+ attention = query @ key.transpose(-2, -1) * self.scale + self.get_attention_biases(hidden_state.device)
306
+ attention = attention.softmax(dim=-1)
307
+ hidden_state = (attention @ value).transpose(1, 2).reshape(batch_size, -1, self.out_dim_projection)
308
+ hidden_state = self.projection(self.activation(hidden_state))
309
+ return hidden_state
310
+
311
+
312
+ class LevitMLPLayer(nn.Module):
313
+ """
314
+ MLP Layer with `2X` expansion in contrast to ViT with `4X`.
315
+ """
316
+
317
+ def __init__(self, input_dim, hidden_dim):
318
+ super().__init__()
319
+ self.linear_up = MLPLayerWithBN(input_dim, hidden_dim)
320
+ self.activation = nn.Hardswish()
321
+ self.linear_down = MLPLayerWithBN(hidden_dim, input_dim)
322
+
323
+ def forward(self, hidden_state):
324
+ hidden_state = self.linear_up(hidden_state)
325
+ hidden_state = self.activation(hidden_state)
326
+ hidden_state = self.linear_down(hidden_state)
327
+ return hidden_state
328
+
329
+
330
+ class LevitResidualLayer(nn.Module):
331
+ """
332
+ Residual Block for LeViT
333
+ """
334
+
335
+ def __init__(self, module, drop_rate):
336
+ super().__init__()
337
+ self.module = module
338
+ self.drop_rate = drop_rate
339
+
340
+ def forward(self, hidden_state):
341
+ if self.training and self.drop_rate > 0:
342
+ rnd = torch.rand(hidden_state.size(0), 1, 1, device=hidden_state.device)
343
+ rnd = rnd.ge_(self.drop_rate).div(1 - self.drop_rate).detach()
344
+ hidden_state = hidden_state + self.module(hidden_state) * rnd
345
+ return hidden_state
346
+ else:
347
+ hidden_state = hidden_state + self.module(hidden_state)
348
+ return hidden_state
349
+
350
+
351
+ class LevitStage(nn.Module):
352
+ """
353
+ LeViT Stage consisting of `LevitMLPLayer` and `LevitAttention` layers.
354
+ """
355
+
356
+ def __init__(
357
+ self,
358
+ config,
359
+ idx,
360
+ hidden_sizes,
361
+ key_dim,
362
+ depths,
363
+ num_attention_heads,
364
+ attention_ratio,
365
+ mlp_ratio,
366
+ down_ops,
367
+ resolution_in,
368
+ ):
369
+ super().__init__()
370
+ self.layers = []
371
+ self.config = config
372
+ self.resolution_in = resolution_in
373
+ # resolution_in is the intial resolution, resolution_out is final resolution after downsampling
374
+ for _ in range(depths):
375
+ self.layers.append(
376
+ LevitResidualLayer(
377
+ LevitAttention(hidden_sizes, key_dim, num_attention_heads, attention_ratio, resolution_in),
378
+ self.config.drop_path_rate,
379
+ )
380
+ )
381
+ if mlp_ratio > 0:
382
+ hidden_dim = hidden_sizes * mlp_ratio
383
+ self.layers.append(
384
+ LevitResidualLayer(LevitMLPLayer(hidden_sizes, hidden_dim), self.config.drop_path_rate)
385
+ )
386
+
387
+ if down_ops[0] == "Subsample":
388
+ self.resolution_out = (self.resolution_in - 1) // down_ops[5] + 1
389
+ self.layers.append(
390
+ LevitAttentionSubsample(
391
+ *self.config.hidden_sizes[idx : idx + 2],
392
+ key_dim=down_ops[1],
393
+ num_attention_heads=down_ops[2],
394
+ attention_ratio=down_ops[3],
395
+ stride=down_ops[5],
396
+ resolution_in=resolution_in,
397
+ resolution_out=self.resolution_out,
398
+ )
399
+ )
400
+ self.resolution_in = self.resolution_out
401
+ if down_ops[4] > 0:
402
+ hidden_dim = self.config.hidden_sizes[idx + 1] * down_ops[4]
403
+ self.layers.append(
404
+ LevitResidualLayer(
405
+ LevitMLPLayer(self.config.hidden_sizes[idx + 1], hidden_dim), self.config.drop_path_rate
406
+ )
407
+ )
408
+
409
+ self.layers = nn.ModuleList(self.layers)
410
+
411
+ def get_resolution(self):
412
+ return self.resolution_in
413
+
414
+ def forward(self, hidden_state):
415
+ for layer in self.layers:
416
+ hidden_state = layer(hidden_state)
417
+ return hidden_state
418
+
419
+
420
+ class LevitEncoder(nn.Module):
421
+ """
422
+ LeViT Encoder consisting of multiple `LevitStage` stages.
423
+ """
424
+
425
+ def __init__(self, config):
426
+ super().__init__()
427
+ self.config = config
428
+ resolution = self.config.image_size // self.config.patch_size
429
+ self.stages = []
430
+ self.config.down_ops.append([""])
431
+
432
+ for stage_idx in range(len(config.depths)):
433
+ stage = LevitStage(
434
+ config,
435
+ stage_idx,
436
+ config.hidden_sizes[stage_idx],
437
+ config.key_dim[stage_idx],
438
+ config.depths[stage_idx],
439
+ config.num_attention_heads[stage_idx],
440
+ config.attention_ratio[stage_idx],
441
+ config.mlp_ratio[stage_idx],
442
+ config.down_ops[stage_idx],
443
+ resolution,
444
+ )
445
+ resolution = stage.get_resolution()
446
+ self.stages.append(stage)
447
+
448
+ self.stages = nn.ModuleList(self.stages)
449
+
450
+ def forward(self, hidden_state, output_hidden_states=False, return_dict=True):
451
+ all_hidden_states = () if output_hidden_states else None
452
+
453
+ for stage in self.stages:
454
+ if output_hidden_states:
455
+ all_hidden_states = all_hidden_states + (hidden_state,)
456
+ hidden_state = stage(hidden_state)
457
+
458
+ if output_hidden_states:
459
+ all_hidden_states = all_hidden_states + (hidden_state,)
460
+ if not return_dict:
461
+ return tuple(v for v in [hidden_state, all_hidden_states] if v is not None)
462
+
463
+ return BaseModelOutputWithNoAttention(last_hidden_state=hidden_state, hidden_states=all_hidden_states)
464
+
465
+
466
+ class LevitClassificationLayer(nn.Module):
467
+ """
468
+ LeViT Classification Layer
469
+ """
470
+
471
+ def __init__(self, input_dim, output_dim):
472
+ super().__init__()
473
+ self.batch_norm = nn.BatchNorm1d(input_dim)
474
+ self.linear = nn.Linear(input_dim, output_dim)
475
+
476
+ def forward(self, hidden_state):
477
+ hidden_state = self.batch_norm(hidden_state)
478
+ logits = self.linear(hidden_state)
479
+ return logits
480
+
481
+
482
+ class LevitPreTrainedModel(PreTrainedModel):
483
+ """
484
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
485
+ models.
486
+ """
487
+
488
+ config_class = LevitConfig
489
+ base_model_prefix = "levit"
490
+ main_input_name = "pixel_values"
491
+ _no_split_modules = ["LevitResidualLayer"]
492
+
493
+ def _init_weights(self, module):
494
+ """Initialize the weights"""
495
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
496
+ # Slightly different from the TF version which uses truncated_normal for initialization
497
+ # cf https://github.com/pytorch/pytorch/pull/5617
498
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
499
+ if module.bias is not None:
500
+ module.bias.data.zero_()
501
+ elif isinstance(module, (nn.BatchNorm1d, nn.BatchNorm2d)):
502
+ module.bias.data.zero_()
503
+ module.weight.data.fill_(1.0)
504
+
505
+
506
+ LEVIT_START_DOCSTRING = r"""
507
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
508
+ as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
509
+ behavior.
510
+
511
+ Parameters:
512
+ config ([`LevitConfig`]): Model configuration class with all the parameters of the model.
513
+ Initializing with a config file does not load the weights associated with the model, only the
514
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
515
+ """
516
+
517
+ LEVIT_INPUTS_DOCSTRING = r"""
518
+ Args:
519
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
520
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
521
+ [`LevitImageProcessor.__call__`] for details.
522
+
523
+ output_hidden_states (`bool`, *optional*):
524
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
525
+ more detail.
526
+ return_dict (`bool`, *optional*):
527
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
528
+ """
529
+
530
+
531
+ @add_start_docstrings(
532
+ "The bare Levit model outputting raw features without any specific head on top.",
533
+ LEVIT_START_DOCSTRING,
534
+ )
535
+ class LevitModel(LevitPreTrainedModel):
536
+ def __init__(self, config):
537
+ super().__init__(config)
538
+ self.config = config
539
+ self.patch_embeddings = LevitPatchEmbeddings(config)
540
+ self.encoder = LevitEncoder(config)
541
+ # Initialize weights and apply final processing
542
+ self.post_init()
543
+
544
+ @add_start_docstrings_to_model_forward(LEVIT_INPUTS_DOCSTRING)
545
+ @add_code_sample_docstrings(
546
+ checkpoint=_CHECKPOINT_FOR_DOC,
547
+ output_type=BaseModelOutputWithPoolingAndNoAttention,
548
+ config_class=_CONFIG_FOR_DOC,
549
+ modality="vision",
550
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
551
+ )
552
+ def forward(
553
+ self,
554
+ pixel_values: torch.FloatTensor = None,
555
+ output_hidden_states: Optional[bool] = None,
556
+ return_dict: Optional[bool] = None,
557
+ ) -> Union[Tuple, BaseModelOutputWithPoolingAndNoAttention]:
558
+ output_hidden_states = (
559
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
560
+ )
561
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
562
+
563
+ if pixel_values is None:
564
+ raise ValueError("You have to specify pixel_values")
565
+
566
+ embeddings = self.patch_embeddings(pixel_values)
567
+ encoder_outputs = self.encoder(
568
+ embeddings,
569
+ output_hidden_states=output_hidden_states,
570
+ return_dict=return_dict,
571
+ )
572
+
573
+ last_hidden_state = encoder_outputs[0]
574
+
575
+ # global average pooling, (batch_size, seq_length, hidden_sizes) -> (batch_size, hidden_sizes)
576
+ pooled_output = last_hidden_state.mean(dim=1)
577
+
578
+ if not return_dict:
579
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
580
+
581
+ return BaseModelOutputWithPoolingAndNoAttention(
582
+ last_hidden_state=last_hidden_state,
583
+ pooler_output=pooled_output,
584
+ hidden_states=encoder_outputs.hidden_states,
585
+ )
586
+
587
+
588
+ @add_start_docstrings(
589
+ """
590
+ Levit Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
591
+ ImageNet.
592
+ """,
593
+ LEVIT_START_DOCSTRING,
594
+ )
595
+ class LevitForImageClassification(LevitPreTrainedModel):
596
+ def __init__(self, config):
597
+ super().__init__(config)
598
+ self.config = config
599
+ self.num_labels = config.num_labels
600
+ self.levit = LevitModel(config)
601
+
602
+ # Classifier head
603
+ self.classifier = (
604
+ LevitClassificationLayer(config.hidden_sizes[-1], config.num_labels)
605
+ if config.num_labels > 0
606
+ else torch.nn.Identity()
607
+ )
608
+
609
+ # Initialize weights and apply final processing
610
+ self.post_init()
611
+
612
+ @add_start_docstrings_to_model_forward(LEVIT_INPUTS_DOCSTRING)
613
+ @add_code_sample_docstrings(
614
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
615
+ output_type=ImageClassifierOutputWithNoAttention,
616
+ config_class=_CONFIG_FOR_DOC,
617
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
618
+ )
619
+ def forward(
620
+ self,
621
+ pixel_values: torch.FloatTensor = None,
622
+ labels: Optional[torch.LongTensor] = None,
623
+ output_hidden_states: Optional[bool] = None,
624
+ return_dict: Optional[bool] = None,
625
+ ) -> Union[Tuple, ImageClassifierOutputWithNoAttention]:
626
+ r"""
627
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
628
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
629
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
630
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
631
+ """
632
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
633
+
634
+ outputs = self.levit(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
635
+
636
+ sequence_output = outputs[0]
637
+ sequence_output = sequence_output.mean(1)
638
+ logits = self.classifier(sequence_output)
639
+
640
+ loss = None
641
+ if labels is not None:
642
+ if self.config.problem_type is None:
643
+ if self.num_labels == 1:
644
+ self.config.problem_type = "regression"
645
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
646
+ self.config.problem_type = "single_label_classification"
647
+ else:
648
+ self.config.problem_type = "multi_label_classification"
649
+
650
+ if self.config.problem_type == "regression":
651
+ loss_fct = MSELoss()
652
+ if self.num_labels == 1:
653
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
654
+ else:
655
+ loss = loss_fct(logits, labels)
656
+ elif self.config.problem_type == "single_label_classification":
657
+ loss_fct = CrossEntropyLoss()
658
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
659
+ elif self.config.problem_type == "multi_label_classification":
660
+ loss_fct = BCEWithLogitsLoss()
661
+ loss = loss_fct(logits, labels)
662
+ if not return_dict:
663
+ output = (logits,) + outputs[2:]
664
+ return ((loss,) + output) if loss is not None else output
665
+
666
+ return ImageClassifierOutputWithNoAttention(
667
+ loss=loss,
668
+ logits=logits,
669
+ hidden_states=outputs.hidden_states,
670
+ )
671
+
672
+
673
+ @add_start_docstrings(
674
+ """
675
+ LeViT Model transformer with image classification heads on top (a linear layer on top of the final hidden state and
676
+ a linear layer on top of the final hidden state of the distillation token) e.g. for ImageNet. .. warning::
677
+ This model supports inference-only. Fine-tuning with distillation (i.e. with a teacher) is not yet
678
+ supported.
679
+ """,
680
+ LEVIT_START_DOCSTRING,
681
+ )
682
+ class LevitForImageClassificationWithTeacher(LevitPreTrainedModel):
683
+ def __init__(self, config):
684
+ super().__init__(config)
685
+ self.config = config
686
+ self.num_labels = config.num_labels
687
+ self.levit = LevitModel(config)
688
+
689
+ # Classifier head
690
+ self.classifier = (
691
+ LevitClassificationLayer(config.hidden_sizes[-1], config.num_labels)
692
+ if config.num_labels > 0
693
+ else torch.nn.Identity()
694
+ )
695
+ self.classifier_distill = (
696
+ LevitClassificationLayer(config.hidden_sizes[-1], config.num_labels)
697
+ if config.num_labels > 0
698
+ else torch.nn.Identity()
699
+ )
700
+
701
+ # Initialize weights and apply final processing
702
+ self.post_init()
703
+
704
+ @add_start_docstrings_to_model_forward(LEVIT_INPUTS_DOCSTRING)
705
+ @add_code_sample_docstrings(
706
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
707
+ output_type=LevitForImageClassificationWithTeacherOutput,
708
+ config_class=_CONFIG_FOR_DOC,
709
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
710
+ )
711
+ def forward(
712
+ self,
713
+ pixel_values: torch.FloatTensor = None,
714
+ output_hidden_states: Optional[bool] = None,
715
+ return_dict: Optional[bool] = None,
716
+ ) -> Union[Tuple, LevitForImageClassificationWithTeacherOutput]:
717
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
718
+
719
+ outputs = self.levit(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
720
+
721
+ sequence_output = outputs[0]
722
+ sequence_output = sequence_output.mean(1)
723
+ cls_logits, distill_logits = self.classifier(sequence_output), self.classifier_distill(sequence_output)
724
+ logits = (cls_logits + distill_logits) / 2
725
+
726
+ if not return_dict:
727
+ output = (logits, cls_logits, distill_logits) + outputs[2:]
728
+ return output
729
+
730
+ return LevitForImageClassificationWithTeacherOutput(
731
+ logits=logits,
732
+ cls_logits=cls_logits,
733
+ distillation_logits=distill_logits,
734
+ hidden_states=outputs.hidden_states,
735
+ )
736
+
737
+
738
+ __all__ = [
739
+ "LevitForImageClassification",
740
+ "LevitForImageClassificationWithTeacher",
741
+ "LevitModel",
742
+ "LevitPreTrainedModel",
743
+ ]
vlmpy310/lib/python3.10/site-packages/transformers/models/olmoe/__pycache__/modeling_olmoe.cpython-310.pyc ADDED
Binary file (40 kB). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/olmoe/configuration_olmoe.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under the Apache License, Version 2.0 (the "License");
2
+ # you may not use this file except in compliance with the License.
3
+ # You may obtain a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS,
9
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ # See the License for the specific language governing permissions and
11
+ # limitations under the License.
12
+ """OLMoE model configuration"""
13
+
14
+ from ...configuration_utils import PretrainedConfig
15
+ from ...modeling_rope_utils import rope_config_validation
16
+
17
+
18
+ class OlmoeConfig(PretrainedConfig):
19
+ r"""
20
+ This is the configuration class to store the configuration of a [`OlmoeModel`]. It is used to instantiate an OLMoE
21
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
22
+ defaults will yield a similar configuration to that of the [allenai/OLMoE-1B-7B-0924](https://huggingface.co/allenai/OLMoE-1B-7B-0924).
23
+
24
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
25
+ documentation from [`PretrainedConfig`] for more information.
26
+
27
+
28
+ Args:
29
+ vocab_size (`int`, *optional*, defaults to 50304):
30
+ Vocabulary size of the OLMoE model. Defines the number of different tokens that can be represented by the
31
+ `inputs_ids` passed when calling [`OlmoeModel`]
32
+ hidden_size (`int`, *optional*, defaults to 2048):
33
+ Dimension of the hidden representations.
34
+ intermediate_size (`int`, *optional*, defaults to 2048):
35
+ Dimension of the MLP representations.
36
+ num_hidden_layers (`int`, *optional*, defaults to 16):
37
+ Number of hidden layers in the Transformer decoder.
38
+ num_attention_heads (`int`, *optional*, defaults to 16):
39
+ Number of attention heads for each attention layer in the Transformer decoder.
40
+ num_key_value_heads (`int`, *optional*):
41
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
42
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
43
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
44
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
45
+ by meanpooling all the original heads within that group. For more details checkout [this
46
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
47
+ `num_attention_heads`.
48
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
49
+ The non-linear activation function (function or string) in the decoder.
50
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
51
+ The maximum sequence length that this model might ever be used with.
52
+ initializer_range (`float`, *optional*, defaults to 0.02):
53
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
54
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
55
+ The epsilon used by the rms normalization layers.
56
+ use_cache (`bool`, *optional*, defaults to `True`):
57
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
58
+ relevant if `config.is_decoder=True`.
59
+ pad_token_id (`int`, *optional*, defaults to 1):
60
+ Padding token id.
61
+ bos_token_id (`int`, *optional*):
62
+ Beginning of stream token id.
63
+ eos_token_id (`int`, *optional*, defaults to 50279):
64
+ End of stream token id.
65
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
66
+ Whether to tie weight embeddings
67
+ rope_theta (`float`, *optional*, defaults to 10000.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/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
76
+ experimental feature, subject to breaking API changes in future versions.
77
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
78
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
79
+ attention_dropout (`float`, *optional*, defaults to 0.0):
80
+ The dropout ratio for the attention probabilities.
81
+ clip_qkv (`float`, *optional*):
82
+ If not `None`, elements of query, key and value attention states are clipped so that their
83
+ absolute value does not exceed this value.
84
+ num_experts_per_tok (`int`, *optional*, defaults to 8):
85
+ Number of selected experts.
86
+ num_experts (`int`, *optional*, defaults to 64):
87
+ Number of routed experts.
88
+ output_router_logits (`bool`, *optional*, defaults to `False`):
89
+ Whether or not the router logits should be returned by the model. Enabeling this will also
90
+ allow the model to output the auxiliary loss, including load balancing loss and router z-loss.
91
+ router_aux_loss_coef (`float`, *optional*, defaults to 0.01):
92
+ The aux loss factor for the total loss.
93
+ norm_topk_prob (`bool`, *optional*, defaults to `False`):
94
+ Whether to normalize the topk probabilities.
95
+
96
+ ```python
97
+ >>> from transformers import OlmoeModel, OlmoeConfig
98
+
99
+ >>> # Initializing a OLMoE 7B A1B style configuration
100
+ >>> configuration = OlmoeConfig()
101
+
102
+ >>> # Initializing a model from the OLMoE 7B A1B style configuration
103
+ >>> model = OlmoeModel(configuration)
104
+
105
+ >>> # Accessing the model configuration
106
+ >>> configuration = model.config
107
+ ```"""
108
+
109
+ model_type = "olmoe"
110
+ keys_to_ignore_at_inference = ["past_key_values"]
111
+
112
+ def __init__(
113
+ self,
114
+ vocab_size=50304,
115
+ hidden_size=2048,
116
+ intermediate_size=2048,
117
+ num_hidden_layers=16,
118
+ num_attention_heads=16,
119
+ num_key_value_heads=None,
120
+ hidden_act="silu",
121
+ max_position_embeddings=4096,
122
+ initializer_range=0.02,
123
+ rms_norm_eps=1e-05,
124
+ use_cache=True,
125
+ pad_token_id=1,
126
+ bos_token_id=None,
127
+ eos_token_id=50279,
128
+ tie_word_embeddings=False,
129
+ rope_theta=10000.0,
130
+ rope_scaling=None,
131
+ attention_bias=False,
132
+ attention_dropout=0.0,
133
+ clip_qkv=None,
134
+ num_experts_per_tok=8,
135
+ num_experts=64,
136
+ output_router_logits=False,
137
+ router_aux_loss_coef=0.01,
138
+ norm_topk_prob=False,
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
+
148
+ # for backward compatibility
149
+ if num_key_value_heads is None:
150
+ num_key_value_heads = num_attention_heads
151
+
152
+ self.num_key_value_heads = num_key_value_heads
153
+ self.hidden_act = hidden_act
154
+ self.initializer_range = initializer_range
155
+ self.rms_norm_eps = rms_norm_eps
156
+ self.use_cache = use_cache
157
+ self.rope_theta = rope_theta
158
+ self.rope_scaling = rope_scaling
159
+ self.attention_bias = attention_bias
160
+ self.attention_dropout = attention_dropout
161
+ self.clip_qkv = clip_qkv
162
+ self.num_experts_per_tok = num_experts_per_tok
163
+ self.num_experts = num_experts
164
+ self.output_router_logits = output_router_logits
165
+ self.router_aux_loss_coef = router_aux_loss_coef
166
+ self.norm_topk_prob = norm_topk_prob
167
+ # Validate the correctness of rotary position embeddings parameters
168
+ # BC: if there is a 'type' field, move it to 'rope_type'.
169
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
170
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
171
+ rope_config_validation(self)
172
+
173
+ super().__init__(
174
+ pad_token_id=pad_token_id,
175
+ bos_token_id=bos_token_id,
176
+ eos_token_id=eos_token_id,
177
+ tie_word_embeddings=tie_word_embeddings,
178
+ **kwargs,
179
+ )
180
+
181
+
182
+ __all__ = ["OlmoeConfig"]
vlmpy310/lib/python3.10/site-packages/transformers/models/rag/__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_rag import *
22
+ from .modeling_rag import *
23
+ from .modeling_tf_rag import *
24
+ from .retrieval_rag import *
25
+ from .tokenization_rag 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__)
vlmpy310/lib/python3.10/site-packages/transformers/models/rag/configuration_rag.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020, The RAG 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
+ """RAG model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import add_start_docstrings
19
+
20
+
21
+ RAG_CONFIG_DOC = r"""
22
+ [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and
23
+ can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
24
+
25
+ Args:
26
+ title_sep (`str`, *optional*, defaults to `" / "`):
27
+ Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`].
28
+ doc_sep (`str`, *optional*, defaults to `" // "`):
29
+ Separator inserted between the text of the retrieved document and the original input when calling
30
+ [`RagRetriever`].
31
+ n_docs (`int`, *optional*, defaults to 5):
32
+ Number of documents to retrieve.
33
+ max_combined_length (`int`, *optional*, defaults to 300):
34
+ Max length of contextualized input returned by [`~RagRetriever.__call__`].
35
+ retrieval_vector_size (`int`, *optional*, defaults to 768):
36
+ Dimensionality of the document embeddings indexed by [`RagRetriever`].
37
+ retrieval_batch_size (`int`, *optional*, defaults to 8):
38
+ Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated
39
+ [`RagRetriever`].
40
+ dataset (`str`, *optional*, defaults to `"wiki_dpr"`):
41
+ A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids
42
+ using `datasets.list_datasets()`).
43
+ dataset_split (`str`, *optional*, defaults to `"train"`)
44
+ Which split of the `dataset` to load.
45
+ index_name (`str`, *optional*, defaults to `"compressed"`)
46
+ The index name of the index associated with the `dataset`. One can choose between `"legacy"`, `"exact"` and
47
+ `"compressed"`.
48
+ index_path (`str`, *optional*)
49
+ The path to the serialized faiss index on disk.
50
+ passages_path (`str`, *optional*):
51
+ A path to text passages compatible with the faiss index. Required if using
52
+ [`~models.rag.retrieval_rag.LegacyIndex`]
53
+ use_dummy_dataset (`bool`, *optional*, defaults to `False`)
54
+ Whether to load a "dummy" variant of the dataset specified by `dataset`.
55
+ label_smoothing (`float`, *optional*, defaults to 0.0):
56
+ Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing
57
+ in the loss calculation. If set to 0, no label smoothing is performed.
58
+ do_marginalize (`bool`, *optional*, defaults to `False`):
59
+ If `True`, the logits are marginalized over all documents by making use of
60
+ `torch.nn.functional.log_softmax`.
61
+ reduce_loss (`bool`, *optional*, defaults to `False`):
62
+ Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation.
63
+ do_deduplication (`bool`, *optional*, defaults to `True`):
64
+ Whether or not to deduplicate the generations from different context documents for a given input. Has to be
65
+ set to `False` if used while training with distributed backend.
66
+ exclude_bos_score (`bool`, *optional*, defaults to `False`):
67
+ Whether or not to disregard the BOS token when computing the loss.
68
+ output_retrieved(`bool`, *optional*, defaults to `False`):
69
+ If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and
70
+ `context_attention_mask` are returned. See returned tensors for more detail.
71
+ use_cache (`bool`, *optional*, defaults to `True`):
72
+ Whether or not the model should return the last key/values attentions (not used by all models).
73
+ forced_eos_token_id (`int`, *optional*):
74
+ The id of the token to force as the last generated token when `max_length` is reached. Usually set to
75
+ `eos_token_id`.
76
+ """
77
+
78
+
79
+ @add_start_docstrings(RAG_CONFIG_DOC)
80
+ class RagConfig(PretrainedConfig):
81
+ model_type = "rag"
82
+ is_composition = True
83
+
84
+ def __init__(
85
+ self,
86
+ vocab_size=None,
87
+ is_encoder_decoder=True,
88
+ prefix=None,
89
+ bos_token_id=None,
90
+ pad_token_id=None,
91
+ eos_token_id=None,
92
+ decoder_start_token_id=None,
93
+ title_sep=" / ",
94
+ doc_sep=" // ",
95
+ n_docs=5,
96
+ max_combined_length=300,
97
+ retrieval_vector_size=768,
98
+ retrieval_batch_size=8,
99
+ dataset="wiki_dpr",
100
+ dataset_split="train",
101
+ index_name="compressed",
102
+ index_path=None,
103
+ passages_path=None,
104
+ use_dummy_dataset=False,
105
+ reduce_loss=False,
106
+ label_smoothing=0.0,
107
+ do_deduplication=True,
108
+ exclude_bos_score=False,
109
+ do_marginalize=False,
110
+ output_retrieved=False,
111
+ use_cache=True,
112
+ forced_eos_token_id=None,
113
+ dataset_revision=None,
114
+ **kwargs,
115
+ ):
116
+ super().__init__(
117
+ bos_token_id=bos_token_id,
118
+ pad_token_id=pad_token_id,
119
+ eos_token_id=eos_token_id,
120
+ decoder_start_token_id=decoder_start_token_id,
121
+ forced_eos_token_id=forced_eos_token_id,
122
+ is_encoder_decoder=is_encoder_decoder,
123
+ prefix=prefix,
124
+ vocab_size=vocab_size,
125
+ **kwargs,
126
+ )
127
+ if "question_encoder" not in kwargs or "generator" not in kwargs:
128
+ raise ValueError(
129
+ f"A configuraton of type {self.model_type} cannot be instantiated because "
130
+ f"both `question_encoder` and `generator` sub-configurations were not passed, only {kwargs}"
131
+ )
132
+ question_encoder_config = kwargs.pop("question_encoder")
133
+ question_encoder_model_type = question_encoder_config.pop("model_type")
134
+ decoder_config = kwargs.pop("generator")
135
+ decoder_model_type = decoder_config.pop("model_type")
136
+
137
+ from ..auto.configuration_auto import AutoConfig
138
+
139
+ self.question_encoder = AutoConfig.for_model(question_encoder_model_type, **question_encoder_config)
140
+ self.generator = AutoConfig.for_model(decoder_model_type, **decoder_config)
141
+
142
+ self.reduce_loss = reduce_loss
143
+ self.label_smoothing = label_smoothing
144
+ self.exclude_bos_score = exclude_bos_score
145
+ self.do_marginalize = do_marginalize
146
+
147
+ self.title_sep = title_sep
148
+ self.doc_sep = doc_sep
149
+ self.n_docs = n_docs
150
+ self.max_combined_length = max_combined_length
151
+
152
+ self.dataset = dataset
153
+ self.dataset_split = dataset_split
154
+ self.index_name = index_name
155
+
156
+ self.retrieval_vector_size = retrieval_vector_size
157
+ self.retrieval_batch_size = retrieval_batch_size
158
+ self.passages_path = passages_path
159
+ self.index_path = index_path
160
+ self.use_dummy_dataset = use_dummy_dataset
161
+ self.dataset_revision = dataset_revision
162
+
163
+ self.output_retrieved = output_retrieved
164
+
165
+ self.do_deduplication = do_deduplication
166
+
167
+ self.use_cache = use_cache
168
+
169
+ if self.forced_eos_token_id is None:
170
+ self.forced_eos_token_id = getattr(self.generator, "forced_eos_token_id", None)
171
+
172
+ @classmethod
173
+ def from_question_encoder_generator_configs(
174
+ cls, question_encoder_config: PretrainedConfig, generator_config: PretrainedConfig, **kwargs
175
+ ) -> PretrainedConfig:
176
+ r"""
177
+ Instantiate a [`EncoderDecoderConfig`] (or a derived class) from a pre-trained encoder model configuration and
178
+ decoder model configuration.
179
+
180
+ Returns:
181
+ [`EncoderDecoderConfig`]: An instance of a configuration object
182
+ """
183
+ return cls(question_encoder=question_encoder_config.to_dict(), generator=generator_config.to_dict(), **kwargs)
184
+
185
+
186
+ __all__ = ["RagConfig"]
vlmpy310/lib/python3.10/site-packages/transformers/models/rag/modeling_rag.py ADDED
@@ -0,0 +1,1644 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020, The RAG 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
+ """RAG model implementation."""
16
+
17
+ import copy
18
+ from dataclasses import dataclass
19
+ from typing import Callable, List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ from torch import nn
23
+
24
+ from ...configuration_utils import PretrainedConfig
25
+ from ...generation import BeamSearchScorer, GenerationConfig, LogitsProcessorList, StoppingCriteriaList
26
+ from ...modeling_outputs import ModelOutput
27
+ from ...modeling_utils import PreTrainedModel
28
+ from ...utils import add_start_docstrings_to_model_forward, logging, replace_return_docstrings
29
+ from .configuration_rag import RagConfig
30
+ from .retrieval_rag import RagRetriever
31
+
32
+
33
+ logger = logging.get_logger(__name__)
34
+
35
+ _CONFIG_FOR_DOC = "RagConfig"
36
+
37
+
38
+ @dataclass
39
+ class RetrievAugLMMarginOutput(ModelOutput):
40
+ """
41
+ Base class for retriever augmented marginalized models outputs.
42
+
43
+ Args:
44
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
45
+ Language modeling loss.
46
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
47
+ Prediction scores of the language modeling head. The score is possibly marginalized over all documents for
48
+ each vocabulary token.
49
+ doc_scores (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`):
50
+ Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
51
+ `question_encoder_last_hidden_state`.
52
+ past_key_values (`List[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
53
+ List of `torch.FloatTensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size,
54
+ num_heads, sequence_length, embed_size_per_head)`).
55
+
56
+ Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used
57
+ (see `past_key_values` input) to speed up sequential decoding.
58
+ retrieved_doc_embeds (`torch.FloatTensor` of shape `(batch_size, config.n_docs, hidden_size)`, *optional*, returned when *output_retrieved=True*):
59
+ Embedded documents retrieved by the retriever. Is used with `question_encoder_last_hidden_state` to compute
60
+ the `doc_scores`.
61
+ retrieved_doc_ids (`torch.LongTensor` of shape `(batch_size, config.n_docs)`, *optional*, returned when *output_retrieved=True*):
62
+ The indexes of the embedded documents retrieved by the retriever.
63
+ context_input_ids (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
64
+ Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.
65
+ context_attention_mask (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
66
+ Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
67
+ retriever.
68
+ question_encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
69
+ Sequence of hidden states at the output of the last layer of the question encoder pooled output of the
70
+ model.
71
+ question_enc_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
72
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
73
+ shape `(batch_size, sequence_length, hidden_size)`.
74
+
75
+ Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.
76
+ question_enc_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
77
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
78
+ sequence_length)`.
79
+
80
+ Attentions weights of the question encoder, after the attention softmax, used to compute the weighted
81
+ average in the self-attention heads.
82
+ generator_enc_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
83
+ Sequence of hidden-states at the output of the last layer of the generator encoder of the model.
84
+ generator_enc_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
85
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
86
+ shape `(batch_size, sequence_length, hidden_size)`.
87
+
88
+ Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.
89
+ generator_enc_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
90
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
91
+ sequence_length)`.
92
+
93
+ Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted
94
+ average in the self-attention heads.
95
+ generator_dec_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
96
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
97
+ shape `(batch_size, sequence_length, hidden_size)`.
98
+
99
+ Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.
100
+ generator_dec_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
101
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
102
+ sequence_length)`.
103
+
104
+ Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted
105
+ average in the self-attention heads.
106
+ generator_cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
107
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
108
+ sequence_length)`.
109
+
110
+ Cross-attentions weights of the generator decoder, after the attention softmax, used to compute the
111
+ weighted average in the cross-attention heads.
112
+ """
113
+
114
+ loss: Optional[torch.FloatTensor] = None
115
+ logits: torch.FloatTensor = None
116
+ doc_scores: torch.FloatTensor = None
117
+ past_key_values: Optional[List[torch.FloatTensor]] = None
118
+ retrieved_doc_embeds: Optional[torch.FloatTensor] = None
119
+ retrieved_doc_ids: Optional[torch.LongTensor] = None
120
+ context_input_ids: Optional[torch.LongTensor] = None
121
+ context_attention_mask: Optional[torch.LongTensor] = None
122
+ question_encoder_last_hidden_state: Optional[torch.FloatTensor] = None
123
+ question_enc_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
124
+ question_enc_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
125
+ generator_enc_last_hidden_state: Optional[torch.FloatTensor] = None
126
+ generator_enc_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
127
+ generator_enc_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
128
+ generator_dec_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
129
+ generator_dec_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
130
+ generator_cross_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
131
+
132
+
133
+ @dataclass
134
+ class RetrievAugLMOutput(ModelOutput):
135
+ """
136
+ Args:
137
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
138
+ Prediction scores of the language modeling head. The score is possibly marginalized over all documents for
139
+ each vocabulary token.
140
+ doc_scores (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`):
141
+ Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
142
+ `question_encoder_last_hidden_state`.
143
+ past_key_values (`List[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
144
+ List of `torch.FloatTensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size,
145
+ num_heads, sequence_length, embed_size_per_head)`).
146
+
147
+ Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used
148
+ (see `past_key_values` input) to speed up sequential decoding.
149
+ retrieved_doc_embeds (`torch.FloatTensor` of shape `(batch_size, config.n_docs, hidden_size)`, *optional*, returned when *output_retrieved=True*):
150
+ Embedded documents retrieved by the retriever. Is used with `question_encoder_last_hidden_state` to compute
151
+ the `doc_scores`.
152
+ retrieved_doc_ids (`torch.LongTensor` of shape `(batch_size, config.n_docs)`, *optional*, returned when *output_retrieved=True*):
153
+ The indexes of the embedded documents retrieved by the retriever.
154
+ context_input_ids (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
155
+ Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.
156
+ context_attention_mask (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
157
+ Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
158
+ retriever.
159
+ question_encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
160
+ Sequence of hidden states at the output of the last layer of the question encoder pooled output of the
161
+ model.
162
+ question_enc_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
163
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
164
+ shape `(batch_size, sequence_length, hidden_size)`.
165
+
166
+ Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.
167
+ question_enc_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
168
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
169
+ sequence_length)`.
170
+
171
+ Attentions weights of the question encoder, after the attention softmax, used to compute the weighted
172
+ average in the self-attention heads.
173
+ generator_enc_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
174
+ Sequence of hidden-states at the output of the last layer of the generator encoder of the model.
175
+ generator_enc_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
176
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
177
+ shape `(batch_size, sequence_length, hidden_size)`.
178
+
179
+ Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.
180
+ generator_enc_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
181
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
182
+ sequence_length)`.
183
+
184
+ Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted
185
+ average in the self-attention heads.
186
+ generator_dec_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
187
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
188
+ shape `(batch_size, sequence_length, hidden_size)`.
189
+
190
+ Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.
191
+ generator_dec_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
192
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
193
+ sequence_length)`.
194
+
195
+ Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted
196
+ average in the self-attention heads.
197
+ generator_cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
198
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
199
+ sequence_length)`.
200
+
201
+ Cross-attentions weights of the generator decoder, after the attention softmax, used to compute the
202
+ weighted average in the cross-attention heads.
203
+ """
204
+
205
+ logits: torch.FloatTensor = None
206
+ doc_scores: torch.FloatTensor = None
207
+ past_key_values: Optional[List[torch.FloatTensor]] = None
208
+ retrieved_doc_embeds: Optional[torch.FloatTensor] = None
209
+ retrieved_doc_ids: Optional[torch.LongTensor] = None
210
+ context_input_ids: Optional[torch.LongTensor] = None
211
+ context_attention_mask: Optional[torch.LongTensor] = None
212
+ question_encoder_last_hidden_state: Optional[torch.FloatTensor] = None
213
+ question_enc_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
214
+ question_enc_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
215
+ generator_enc_last_hidden_state: Optional[torch.FloatTensor] = None
216
+ generator_enc_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
217
+ generator_enc_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
218
+ generator_dec_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
219
+ generator_dec_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
220
+ generator_cross_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
221
+
222
+
223
+ class RagPreTrainedModel(PreTrainedModel):
224
+ r"""
225
+ RAG models were released with the paper [Retrieval-Augmented Generation for Knowledge-Intensive NLP
226
+ Tasks](https://arxiv.org/abs/2005.11401) by Patrick Lewis, Ethan Perez, Aleksandra Piktus et al.
227
+
228
+ RAG is a retriever augmented model and encapsulate three components: a question encoder, a dataset retriever and a
229
+ generator, the encoder and generator are trainable while the retriever is just an indexed dataset.
230
+
231
+ """
232
+
233
+ config_class = RagConfig
234
+ base_model_prefix = "rag"
235
+ _supports_flash_attn_2 = True
236
+ _supports_sdpa = True
237
+
238
+ @classmethod
239
+ def from_pretrained(cls, *args, **kwargs):
240
+ # At the moment fast initialization is not supported
241
+ # for composite models
242
+ kwargs["_fast_init"] = False
243
+ return super().from_pretrained(*args, **kwargs)
244
+
245
+ @classmethod
246
+ def from_pretrained_question_encoder_generator(
247
+ cls,
248
+ question_encoder_pretrained_model_name_or_path: str = None,
249
+ generator_pretrained_model_name_or_path: str = None,
250
+ retriever: RagRetriever = None,
251
+ **kwargs,
252
+ ) -> PreTrainedModel:
253
+ r"""
254
+ Instantiates an question encoder and a generator from one or two base classes of the library from pretrained
255
+ model checkpoints.
256
+
257
+ The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train
258
+ the model, you need to first set it back in training mode with `model.train()`.
259
+
260
+ Params:
261
+ question_encoder_pretrained_model_name_or_path (`str`, *optional*, defaults to `None`):
262
+ Information necessary to initiate the question encoder. Can be either:
263
+
264
+ - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
265
+ - A path to a *directory* containing model weights saved using
266
+ [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
267
+ - A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In
268
+ this case, `from_tf` should be set to `True` and a configuration object should be provided as
269
+ `config` argument. This loading path is slower than converting the TensorFlow checkpoint in a
270
+ PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
271
+
272
+ generator_pretrained_model_name_or_path (`str`, *optional*, defaults to `None`):
273
+ Information necessary to initiate the generator. Can be either:
274
+
275
+ - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
276
+ - A path to a *directory* containing model weights saved using
277
+ [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
278
+ - A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In
279
+ this case, `from_tf` should be set to `True` and a configuration object should be provided as
280
+ `config` argument. This loading path is slower than converting the TensorFlow checkpoint in a
281
+ PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
282
+
283
+ model_args (remaining positional arguments, *optional*):
284
+ All remaining positional arguments will be passed to the underlying model's `__init__` method.
285
+ retriever ([`RagRetriever`], *optional*):
286
+ The retriever to use.
287
+ kwwargs (remaining dictionary of keyword arguments, *optional*):
288
+ Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
289
+ `output_attentions=True`).
290
+
291
+ - To update the question_encoder configuration, use the prefix *question_encoder_* for each
292
+ configuration parameter.
293
+ - To update the generator configuration, use the prefix *generator_* for each configuration parameter.
294
+ - To update the parent model configuration, do not use a prefix for each configuration parameter.
295
+
296
+ Behaves differently depending on whether a `config` is provided or automatically loaded.
297
+
298
+ Example:
299
+
300
+ ```python
301
+ >>> from transformers import RagModel
302
+
303
+ >>> # initialize a RAG from two pretrained models.
304
+ >>> model = RagModel.from_pretrained_question_encoder_generator(
305
+ ... "facebook/dpr-question_encoder-single-nq-base", "google-t5/t5-small"
306
+ ... )
307
+ >>> # saving model after fine-tuning
308
+ >>> model.save_pretrained("./rag")
309
+ >>> # load fine-tuned model
310
+ >>> model = RagModel.from_pretrained("./rag")
311
+ ```"""
312
+
313
+ kwargs_question_encoder = {
314
+ argument[len("question_encoder_") :]: value
315
+ for argument, value in kwargs.items()
316
+ if argument.startswith("question_encoder_")
317
+ }
318
+
319
+ kwargs_generator = {
320
+ argument[len("generator_") :]: value
321
+ for argument, value in kwargs.items()
322
+ if argument.startswith("generator_")
323
+ }
324
+
325
+ # remove question_encoder, generator kwargs from kwargs
326
+ for key in kwargs_question_encoder.keys():
327
+ del kwargs["question_encoder_" + key]
328
+ for key in kwargs_generator.keys():
329
+ del kwargs["generator_" + key]
330
+
331
+ # Load and initialize the question_encoder and generator
332
+ # The distinction between question_encoder and generator at the model level is made
333
+ # by the value of the flag `is_generator` that we need to set correctly.
334
+ question_encoder = kwargs_question_encoder.pop("model", None)
335
+ if question_encoder is None:
336
+ assert question_encoder_pretrained_model_name_or_path is not None, (
337
+ "If `model` is not defined as an argument, a `question_encoder_pretrained_model_name_or_path` has to"
338
+ " be defined"
339
+ )
340
+ from ..auto.modeling_auto import AutoModel
341
+
342
+ if "config" not in kwargs_question_encoder:
343
+ from ..auto.configuration_auto import AutoConfig
344
+
345
+ question_encoder_config, kwargs_question_encoder = AutoConfig.from_pretrained(
346
+ question_encoder_pretrained_model_name_or_path,
347
+ **kwargs_question_encoder,
348
+ return_unused_kwargs=True,
349
+ )
350
+ kwargs_question_encoder["config"] = question_encoder_config
351
+
352
+ question_encoder = AutoModel.from_pretrained(
353
+ question_encoder_pretrained_model_name_or_path, **kwargs_question_encoder
354
+ )
355
+
356
+ generator = kwargs_generator.pop("model", None)
357
+ if generator is None:
358
+ assert generator_pretrained_model_name_or_path is not None, (
359
+ "If `generator_model` is not defined as an argument, a `generator_pretrained_model_name_or_path` has"
360
+ " to be defined"
361
+ )
362
+ from ..auto.modeling_auto import AutoModelForSeq2SeqLM
363
+
364
+ if "config" not in kwargs_generator:
365
+ from ..auto.configuration_auto import AutoConfig
366
+
367
+ generator_config, kwargs_generator = AutoConfig.from_pretrained(
368
+ generator_pretrained_model_name_or_path, **kwargs_generator, return_unused_kwargs=True
369
+ )
370
+
371
+ kwargs_generator["config"] = generator_config
372
+
373
+ generator = AutoModelForSeq2SeqLM.from_pretrained(
374
+ generator_pretrained_model_name_or_path, **kwargs_generator
375
+ )
376
+
377
+ # instantiate config with corresponding kwargs
378
+ config = kwargs.get("config", None)
379
+ if config is None:
380
+ config = RagConfig.from_question_encoder_generator_configs(
381
+ question_encoder.config, generator.config, **kwargs
382
+ )
383
+
384
+ return cls(question_encoder=question_encoder, generator=generator, config=config, retriever=retriever)
385
+
386
+
387
+ RAG_START_DOCSTRING = r"""
388
+
389
+ RAG is a seq2seq model which encapsulates two core components: a question encoder and a generator. During a forward
390
+ pass, we encode the input with the question encoder and pass it to the retriever to extract relevant context
391
+ documents. The documents are then prepended to the input. Such contextualized inputs is passed to the generator.
392
+
393
+ The question encoder can be any *autoencoding* model, preferably [`DPRQuestionEncoder`], and the generator can be
394
+ any *seq2seq* model, preferably [`BartForConditionalGeneration`].
395
+
396
+ The model can be initialized with a [`RagRetriever`] for end-to-end generation or used in combination with the
397
+ outputs of a retriever in multiple steps---see examples for more details. The model is compatible any
398
+ *autoencoding* model as the `question_encoder` and any *seq2seq* model with language model head as the `generator`.
399
+ It has been tested with [`DPRQuestionEncoder`] as the `question_encoder` and [`BartForConditionalGeneration`] or
400
+ [`T5ForConditionalGeneration`] as the `generator`.
401
+
402
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
403
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
404
+ etc.)
405
+
406
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
407
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
408
+ and behavior.
409
+
410
+
411
+ Args:
412
+ config ([`RagConfig`]):
413
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
414
+ load the weights associated with the model, only the configuration. Check out the
415
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
416
+ question_encoder ([`PreTrainedModel`]):
417
+ An encoder model compatible with the faiss index encapsulated by the `retriever`.
418
+ generator ([`PreTrainedModel`]):
419
+ A seq2seq model used as the generator in the RAG architecture.
420
+ retriever ([`RagRetriever`]):
421
+ A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.
422
+ """
423
+
424
+
425
+ RAG_FORWARD_INPUTS_DOCSTRING = r"""
426
+ Args:
427
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
428
+ Indices of input sequence tokens in the vocabulary. [`RagConfig`], used to initialize the model, specifies
429
+ which generator to use, it also specifies a compatible generator tokenizer. Use that tokenizer class to
430
+ obtain the indices.
431
+
432
+ [What are input IDs?](../glossary#input-ids)
433
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
434
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
435
+
436
+ - 1 for tokens that are **not masked**,
437
+ - 0 for tokens that are **masked**.
438
+
439
+ [What are attention masks?](../glossary#attention-mask)
440
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*)
441
+ Tuple consists of (`generator_enc_last_hidden_state`, *optional*: `generator_enc_hidden_states`,
442
+ *optional*: `generator_enc_attentions`). `generator_enc_last_hidden_state` of shape `(batch_size, n_docs *
443
+ sequence_length, hidden_size)` is a sequence of hidden-states at the output of the last layer of the
444
+ generator's encoder.
445
+
446
+ Used by the ([`RagModel`]) model during decoding.
447
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
448
+ Provide for generation tasks. `None` by default, construct as per instructions for the generator model
449
+ you're using with your RAG instance.
450
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
451
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
452
+ be used by default.
453
+ past_key_values (`tuple(tuple(torch.FloatTensor))`):
454
+ Tuple consists of two elements: `encoder_outputs` of the RAG model (see `encoder_outputs`) and
455
+ `past_key_values` of the underlying generator. Can be used to speed up decoding. `past_key_values` are used
456
+ in the ([`RagTokenForGeneration`]) model during decoding.
457
+ doc_scores (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`):
458
+ Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
459
+ `question_encoder_last_hidden_state`. If the model has is not initialized with a `retriever` `doc_scores`
460
+ has to be provided to the forward pass. `doc_scores` can be computed via
461
+ `question_encoder_last_hidden_state` and `retrieved_doc_embeds`, see examples for more information.
462
+ context_input_ids (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
463
+ Input IDs post-processed from the retrieved documents and the question encoder `input_ids` by the
464
+ retriever. If the model was not initialized with a `retriever` ``context_input_ids` has to be provided to
465
+ the forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`].
466
+ context_attention_mask (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`,*optional*, returned when *output_retrieved=True*):
467
+ Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
468
+ retriever. If the model has is not initialized with a `retriever` `context_attention_mask` has to be
469
+ provided to the forward pass. `context_attention_mask` are returned by [`~RagRetriever.__call__`].
470
+ use_cache (`bool`, *optional*, defaults to `True`):
471
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
472
+ `past_key_values`).
473
+ output_attentions (`bool`, *optional*):
474
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
475
+ tensors for more detail.
476
+ output_hidden_states (`bool`, *optional*):
477
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
478
+ more detail.
479
+ output_retrieved(`bool`, *optional*):
480
+ Whether or not to return the `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and
481
+ `context_attention_mask`. See returned tensors for more detail.
482
+ n_docs (`int`, *optional*, defaults to `config.n_docs``)
483
+ Number of documents to retrieve and/or number of documents for which to generate an answer.
484
+ """
485
+
486
+
487
+ @add_start_docstrings_to_model_forward(RAG_START_DOCSTRING)
488
+ class RagModel(RagPreTrainedModel):
489
+ def __init__(
490
+ self,
491
+ config: Optional[PretrainedConfig] = None,
492
+ question_encoder: Optional[PreTrainedModel] = None,
493
+ generator: Optional[PreTrainedModel] = None,
494
+ retriever: Optional[RagRetriever] = None, # or maybe just use a `set_retriever(...)` method
495
+ **kwargs,
496
+ ):
497
+ assert config is not None or (
498
+ question_encoder is not None and generator is not None
499
+ ), "Either a configuration or an question_encoder and a generator has to be provided."
500
+
501
+ if config is None:
502
+ config = RagConfig.from_question_encoder_generator_configs(
503
+ question_encoder.config, generator.config, **kwargs
504
+ )
505
+ else:
506
+ assert isinstance(config, self.config_class), f"config: {config} has to be of type {self.config_class}"
507
+ super().__init__(config)
508
+ if question_encoder is None:
509
+ from ..auto.modeling_auto import AutoModel
510
+
511
+ question_encoder = AutoModel.from_config(config.question_encoder)
512
+
513
+ if generator is None:
514
+ from ..auto.modeling_auto import AutoModelForSeq2SeqLM
515
+
516
+ generator = AutoModelForSeq2SeqLM.from_config(config.generator)
517
+
518
+ self.retriever = retriever
519
+ if self.retriever is not None:
520
+ assert isinstance(
521
+ retriever, RagRetriever
522
+ ), f"`self.retriever` is of type {type(self.retriever)}, but should be of type `RagRetriever`"
523
+ self.retriever = retriever
524
+
525
+ self.question_encoder = question_encoder
526
+ self.generator = generator
527
+
528
+ self.ctx_encoder = None
529
+ self.context_encoder_training = False
530
+
531
+ @add_start_docstrings_to_model_forward(RAG_FORWARD_INPUTS_DOCSTRING)
532
+ @replace_return_docstrings(output_type=RetrievAugLMOutput, config_class=_CONFIG_FOR_DOC)
533
+ def forward(
534
+ self,
535
+ input_ids: Optional[torch.LongTensor] = None,
536
+ attention_mask: Optional[torch.Tensor] = None,
537
+ encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
538
+ decoder_input_ids: Optional[torch.LongTensor] = None,
539
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
540
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
541
+ doc_scores: Optional[torch.FloatTensor] = None,
542
+ context_input_ids: Optional[torch.LongTensor] = None,
543
+ context_attention_mask: Optional[torch.LongTensor] = None,
544
+ use_cache: Optional[bool] = None,
545
+ output_attentions: Optional[bool] = None,
546
+ output_hidden_states: Optional[bool] = None,
547
+ output_retrieved: Optional[bool] = None,
548
+ n_docs: Optional[int] = None,
549
+ ) -> Union[Tuple[torch.Tensor], RetrievAugLMOutput]:
550
+ r"""
551
+ Returns:
552
+
553
+ Example:
554
+
555
+ ```python
556
+ >>> from transformers import AutoTokenizer, RagRetriever, RagModel
557
+ >>> import torch
558
+
559
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/rag-token-base")
560
+ >>> retriever = RagRetriever.from_pretrained(
561
+ ... "facebook/rag-token-base", index_name="exact", use_dummy_dataset=True
562
+ ... )
563
+ >>> # initialize with RagRetriever to do everything in one forward call
564
+ >>> model = RagModel.from_pretrained("facebook/rag-token-base", retriever=retriever)
565
+
566
+ >>> inputs = tokenizer("How many people live in Paris?", return_tensors="pt")
567
+ >>> outputs = model(input_ids=inputs["input_ids"])
568
+ ```"""
569
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
570
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
571
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
572
+ output_hidden_states = (
573
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
574
+ )
575
+ output_retrieved = output_retrieved if output_retrieved is not None else self.config.output_retrieved
576
+
577
+ # whether retriever has to be used
578
+ has_to_retrieve = (
579
+ self.retriever is not None
580
+ and (context_input_ids is None or context_attention_mask is None or doc_scores is None)
581
+ and encoder_outputs is None
582
+ )
583
+ # encoder_outputs are pre-computed during RAG-token generation
584
+ if encoder_outputs is None:
585
+ if has_to_retrieve:
586
+ question_enc_outputs = self.question_encoder(
587
+ input_ids, attention_mask=attention_mask, return_dict=True
588
+ )
589
+ question_encoder_last_hidden_state = question_enc_outputs[0] # hidden states of question encoder
590
+
591
+ retriever_outputs = self.retriever(
592
+ input_ids,
593
+ question_encoder_last_hidden_state.cpu().detach().to(torch.float32).numpy(),
594
+ prefix=self.generator.config.prefix,
595
+ n_docs=n_docs,
596
+ return_tensors="pt",
597
+ )
598
+ if self.context_encoder_training:
599
+ (
600
+ context_input_ids,
601
+ context_attention_mask,
602
+ retrieved_doc_embeds,
603
+ retrived_doc_input_ids,
604
+ retrived_doc_attention_mask,
605
+ retrieved_doc_ids,
606
+ ) = (
607
+ retriever_outputs["context_input_ids"],
608
+ retriever_outputs["context_attention_mask"],
609
+ retriever_outputs["retrieved_doc_embeds"],
610
+ retriever_outputs["tokenized_doc_ids"],
611
+ retriever_outputs["tokenized_doc_attention_mask"],
612
+ retriever_outputs["doc_ids"],
613
+ )
614
+
615
+ context_input_ids = context_input_ids.to(input_ids)
616
+ context_attention_mask = context_attention_mask.to(input_ids)
617
+
618
+ retrived_doc_input_ids = retrived_doc_input_ids.to(input_ids)
619
+ retrived_doc_attention_mask = retrived_doc_attention_mask.to(input_ids)
620
+ retrieved_doc_embeds = self.ctx_encoder(
621
+ retrived_doc_input_ids, attention_mask=retrived_doc_attention_mask, return_dict=True
622
+ ).pooler_output
623
+ retrieved_doc_embeds = retrieved_doc_embeds.view(
624
+ -1, n_docs, question_encoder_last_hidden_state.shape[1]
625
+ ) # reshaping
626
+
627
+ # compute doc_scores involving ctx_encoder
628
+ doc_scores = torch.bmm(
629
+ question_encoder_last_hidden_state.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)
630
+ ).squeeze(1)
631
+
632
+ else:
633
+ context_input_ids, context_attention_mask, retrieved_doc_embeds, retrieved_doc_ids = (
634
+ retriever_outputs["context_input_ids"],
635
+ retriever_outputs["context_attention_mask"],
636
+ retriever_outputs["retrieved_doc_embeds"],
637
+ retriever_outputs["doc_ids"],
638
+ )
639
+
640
+ # set to correct device
641
+ retrieved_doc_embeds = retrieved_doc_embeds.to(question_encoder_last_hidden_state)
642
+ context_input_ids = context_input_ids.to(input_ids)
643
+ context_attention_mask = context_attention_mask.to(input_ids)
644
+
645
+ # compute doc_scores
646
+ doc_scores = torch.bmm(
647
+ question_encoder_last_hidden_state.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)
648
+ ).squeeze(1)
649
+ else:
650
+ assert context_input_ids is not None, (
651
+ "Make sure that `context_input_ids` are passed, if no `retriever` is set. Alternatively, you can"
652
+ " set a retriever using the `set_retriever(...)` function."
653
+ )
654
+ assert context_attention_mask is not None, (
655
+ "Make sure that `context_attention_mask` are passed, if no `retriever` is set. Alternatively, you"
656
+ " can set a retriever using the `set_retriever(...)` function."
657
+ )
658
+ assert doc_scores is not None, (
659
+ "Make sure that `doc_scores` are passed, if no `retriever` is set. Alternatively, you can set a"
660
+ " retriever using the `set_retriever(...)` function."
661
+ )
662
+
663
+ assert (
664
+ doc_scores is not None
665
+ ), "Make sure that `doc_scores` are passed when passing `encoder_outputs` to the forward function."
666
+
667
+ assert (doc_scores.shape[1] % n_docs) == 0, (
668
+ f" The first dimension of `context_input_ids` should be a multiple of `n_docs`={n_docs}, but is"
669
+ f" {context_input_ids.shape[0]}."
670
+ )
671
+
672
+ # Decoder input without context documents
673
+ if decoder_input_ids is not None:
674
+ decoder_input_ids = decoder_input_ids.repeat_interleave(n_docs, dim=0)
675
+
676
+ if decoder_attention_mask is not None:
677
+ decoder_attention_mask = decoder_attention_mask.repeat_interleave(n_docs, dim=0)
678
+
679
+ gen_outputs = self.generator(
680
+ input_ids=context_input_ids,
681
+ attention_mask=context_attention_mask,
682
+ encoder_outputs=encoder_outputs,
683
+ decoder_input_ids=decoder_input_ids,
684
+ decoder_attention_mask=decoder_attention_mask,
685
+ past_key_values=past_key_values,
686
+ use_cache=use_cache,
687
+ output_attentions=output_attentions,
688
+ return_dict=True,
689
+ )
690
+
691
+ if not has_to_retrieve:
692
+ question_encoder_last_hidden_state = None
693
+ question_enc_hidden_states = None
694
+ question_enc_attentions = None
695
+ retrieved_doc_embeds = None
696
+ retrieved_doc_ids = None
697
+ else:
698
+ question_enc_hidden_states = question_enc_outputs.hidden_states
699
+ question_enc_attentions = question_enc_outputs.attentions
700
+
701
+ if not has_to_retrieve or not output_retrieved:
702
+ # don't output retrieved docs
703
+ context_input_ids = (None,)
704
+ context_attention_mask = None
705
+ retrieved_doc_embeds = None
706
+ retrieved_doc_ids = None
707
+
708
+ return RetrievAugLMOutput(
709
+ logits=gen_outputs.logits,
710
+ doc_scores=doc_scores,
711
+ past_key_values=gen_outputs.past_key_values,
712
+ context_input_ids=context_input_ids,
713
+ context_attention_mask=context_attention_mask,
714
+ retrieved_doc_embeds=retrieved_doc_embeds,
715
+ retrieved_doc_ids=retrieved_doc_ids,
716
+ question_encoder_last_hidden_state=question_encoder_last_hidden_state,
717
+ question_enc_hidden_states=question_enc_hidden_states,
718
+ question_enc_attentions=question_enc_attentions,
719
+ generator_enc_last_hidden_state=gen_outputs.encoder_last_hidden_state,
720
+ generator_enc_hidden_states=gen_outputs.encoder_hidden_states,
721
+ generator_enc_attentions=gen_outputs.encoder_attentions,
722
+ generator_dec_hidden_states=gen_outputs.decoder_hidden_states,
723
+ generator_dec_attentions=gen_outputs.decoder_attentions,
724
+ generator_cross_attentions=gen_outputs.cross_attentions,
725
+ )
726
+
727
+
728
+ @add_start_docstrings_to_model_forward(
729
+ """
730
+ A RAG-sequence model implementation. It performs RAG-sequence specific marginalization in the forward pass.
731
+ """,
732
+ RAG_START_DOCSTRING,
733
+ )
734
+ class RagSequenceForGeneration(RagPreTrainedModel):
735
+ def __init__(
736
+ self,
737
+ config: Optional[PretrainedConfig] = None,
738
+ question_encoder: Optional[PreTrainedModel] = None,
739
+ generator: Optional[PreTrainedModel] = None,
740
+ retriever: Optional[RagRetriever] = None,
741
+ **kwargs,
742
+ ):
743
+ assert config is not None or (
744
+ question_encoder is not None and generator is not None
745
+ ), "Either a configuration or an encoder and a generator has to be provided."
746
+
747
+ if config is None:
748
+ config = RagConfig.from_question_encoder_generator_configs(
749
+ question_encoder.config, generator.config, **kwargs
750
+ )
751
+ super().__init__(config)
752
+
753
+ # instantiate model
754
+ self.rag = RagModel(config=config, question_encoder=question_encoder, generator=generator, retriever=retriever)
755
+
756
+ def set_retriever(self, retriever: RagRetriever):
757
+ self.rag.retriever = retriever
758
+
759
+ def set_context_encoder_for_training(self, ctx_encoder: PreTrainedModel):
760
+ self.rag.context_encoder_training = True
761
+ self.rag.ctx_encoder = ctx_encoder
762
+
763
+ @add_start_docstrings_to_model_forward(RAG_FORWARD_INPUTS_DOCSTRING)
764
+ @replace_return_docstrings(output_type=RetrievAugLMMarginOutput, config_class=_CONFIG_FOR_DOC)
765
+ def forward(
766
+ self,
767
+ input_ids: Optional[torch.LongTensor] = None,
768
+ attention_mask: Optional[torch.Tensor] = None,
769
+ encoder_outputs: Optional[Tuple[Tuple[torch.Tensor]]] = None,
770
+ decoder_input_ids: Optional[torch.LongTensor] = None,
771
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
772
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
773
+ context_input_ids: Optional[torch.LongTensor] = None,
774
+ context_attention_mask: Optional[torch.LongTensor] = None,
775
+ doc_scores: Optional[torch.FloatTensor] = None,
776
+ use_cache: Optional[bool] = None,
777
+ output_attentions: Optional[bool] = None,
778
+ output_hidden_states: Optional[bool] = None,
779
+ output_retrieved: Optional[bool] = None,
780
+ exclude_bos_score: Optional[bool] = None,
781
+ reduce_loss: Optional[bool] = None,
782
+ labels: Optional[torch.LongTensor] = None,
783
+ n_docs: Optional[int] = None,
784
+ **kwargs, # needs kwargs for generation
785
+ ) -> RetrievAugLMMarginOutput:
786
+ r"""
787
+ exclude_bos_score (`bool`, *optional*):
788
+ Only relevant if `labels` is passed. If `True`, the score of the BOS token is disregarded when computing
789
+ the loss.
790
+ reduce_loss (`bool`, *optional*):
791
+ Only relevant if `labels` is passed. If `True`, the NLL loss is reduced using the `torch.Tensor.sum`
792
+ operation.
793
+ kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
794
+ Legacy dictionary, which is required so that model can use *generate()* function.
795
+
796
+ Returns:
797
+
798
+ Example:
799
+
800
+ ```python
801
+ >>> from transformers import AutoTokenizer, RagRetriever, RagSequenceForGeneration
802
+ >>> import torch
803
+
804
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/rag-sequence-nq")
805
+ >>> retriever = RagRetriever.from_pretrained(
806
+ ... "facebook/rag-sequence-nq", index_name="exact", use_dummy_dataset=True
807
+ ... )
808
+ >>> # initialize with RagRetriever to do everything in one forward call
809
+ >>> model = RagSequenceForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever)
810
+
811
+ >>> inputs = tokenizer("How many people live in Paris?", return_tensors="pt")
812
+ >>> targets = tokenizer(text_target="In Paris, there are 10 million people.", return_tensors="pt")
813
+ >>> input_ids = inputs["input_ids"]
814
+ >>> labels = targets["input_ids"]
815
+ >>> outputs = model(input_ids=input_ids, labels=labels)
816
+
817
+ >>> # or use retriever separately
818
+ >>> model = RagSequenceForGeneration.from_pretrained("facebook/rag-sequence-nq", use_dummy_dataset=True)
819
+ >>> # 1. Encode
820
+ >>> question_hidden_states = model.question_encoder(input_ids)[0]
821
+ >>> # 2. Retrieve
822
+ >>> docs_dict = retriever(input_ids.numpy(), question_hidden_states.detach().numpy(), return_tensors="pt")
823
+ >>> doc_scores = torch.bmm(
824
+ ... question_hidden_states.unsqueeze(1), docs_dict["retrieved_doc_embeds"].float().transpose(1, 2)
825
+ ... ).squeeze(1)
826
+ >>> # 3. Forward to generator
827
+ >>> outputs = model(
828
+ ... context_input_ids=docs_dict["context_input_ids"],
829
+ ... context_attention_mask=docs_dict["context_attention_mask"],
830
+ ... doc_scores=doc_scores,
831
+ ... decoder_input_ids=labels,
832
+ ... )
833
+ ```"""
834
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
835
+ exclude_bos_score = exclude_bos_score if exclude_bos_score is not None else self.config.exclude_bos_score
836
+ reduce_loss = reduce_loss if reduce_loss is not None else self.config.reduce_loss
837
+
838
+ if labels is not None:
839
+ if decoder_input_ids is None:
840
+ decoder_input_ids = labels
841
+ use_cache = False
842
+
843
+ outputs = self.rag(
844
+ input_ids=input_ids,
845
+ attention_mask=attention_mask,
846
+ encoder_outputs=encoder_outputs,
847
+ decoder_input_ids=decoder_input_ids,
848
+ decoder_attention_mask=decoder_attention_mask,
849
+ context_input_ids=context_input_ids,
850
+ context_attention_mask=context_attention_mask,
851
+ doc_scores=doc_scores,
852
+ past_key_values=past_key_values,
853
+ use_cache=use_cache,
854
+ output_attentions=output_attentions,
855
+ output_hidden_states=output_hidden_states,
856
+ output_retrieved=output_retrieved,
857
+ n_docs=n_docs,
858
+ )
859
+
860
+ loss = None
861
+ if labels is not None:
862
+ loss = self.get_nll(
863
+ outputs.logits,
864
+ outputs.doc_scores,
865
+ decoder_input_ids,
866
+ reduce_loss=reduce_loss,
867
+ epsilon=self.config.label_smoothing,
868
+ exclude_bos_score=exclude_bos_score,
869
+ n_docs=n_docs,
870
+ )
871
+
872
+ return RetrievAugLMMarginOutput(
873
+ loss=loss,
874
+ logits=outputs.logits,
875
+ doc_scores=outputs.doc_scores,
876
+ past_key_values=outputs.past_key_values,
877
+ context_input_ids=outputs.context_input_ids,
878
+ context_attention_mask=outputs.context_attention_mask,
879
+ retrieved_doc_embeds=outputs.retrieved_doc_embeds,
880
+ retrieved_doc_ids=outputs.retrieved_doc_ids,
881
+ question_encoder_last_hidden_state=outputs.question_encoder_last_hidden_state,
882
+ question_enc_hidden_states=outputs.question_enc_hidden_states,
883
+ question_enc_attentions=outputs.question_enc_attentions,
884
+ generator_enc_last_hidden_state=outputs.generator_enc_last_hidden_state,
885
+ generator_enc_hidden_states=outputs.generator_enc_hidden_states,
886
+ generator_enc_attentions=outputs.generator_enc_attentions,
887
+ generator_dec_hidden_states=outputs.generator_dec_hidden_states,
888
+ generator_dec_attentions=outputs.generator_dec_attentions,
889
+ generator_cross_attentions=outputs.generator_cross_attentions,
890
+ )
891
+
892
+ @property
893
+ def retriever(self):
894
+ return self.rag.retriever
895
+
896
+ @property
897
+ def generator(self):
898
+ return self.rag.generator
899
+
900
+ @property
901
+ def question_encoder(self):
902
+ return self.rag.question_encoder
903
+
904
+ @torch.no_grad()
905
+ def generate(
906
+ self,
907
+ input_ids: Optional[torch.LongTensor] = None,
908
+ attention_mask: Optional[torch.LongTensor] = None,
909
+ context_input_ids: Optional[torch.LongTensor] = None,
910
+ context_attention_mask: Optional[torch.LongTensor] = None,
911
+ doc_scores: Optional[torch.FloatTensor] = None,
912
+ do_deduplication: Optional[bool] = None, # defaults to True
913
+ num_return_sequences: Optional[int] = None, # defaults to 1
914
+ num_beams: Optional[int] = None, # defaults to 1
915
+ n_docs: Optional[int] = None,
916
+ **model_kwargs,
917
+ ) -> torch.LongTensor:
918
+ """
919
+ Implements RAG sequence "thorough" decoding. Read the [`~generation.GenerationMixin.generate`]` documentation
920
+ for more information on how to set other generate input parameters.
921
+
922
+ Args:
923
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
924
+ The sequence used as a prompt for the generation. If `input_ids` is not passed, then
925
+ `context_input_ids` has to be provided.
926
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
927
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
928
+
929
+ - 1 for tokens that are **not masked**,
930
+ - 0 for tokens that are **masked**.
931
+
932
+ [What are attention masks?](../glossary#attention-mask)
933
+ context_input_ids (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
934
+ Input IDs post-processed from the retrieved documents and the question encoder input_ids by the
935
+ retriever.
936
+ context_attention_mask (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
937
+ Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
938
+ retriever.
939
+
940
+ If the model is not initialized with a `retriever` or `input_ids` is not given, `context_input_ids` and
941
+ `context_attention_mask` have to be provided to the forward pass. They are returned by
942
+ [`~RagRetriever.__call__`].
943
+ doc_scores (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`):
944
+ Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
945
+ `question_encoder_last_hidden_state`.
946
+
947
+ If the model is not initialized with a `retriever` or `input_ids` is not given, `doc_scores` has to be
948
+ provided to the forward pass. `doc_scores` are returned by [`~RagRetriever.__call__`].
949
+ do_deduplication (`bool`, *optional*):
950
+ Whether or not to deduplicate the generations from different context documents for a given input. Has
951
+ to be set to `False` if used while training with distributed backend.
952
+ num_return_sequences(`int`, *optional*, defaults to 1):
953
+ The number of independently computed returned sequences for each element in the batch. Note that this
954
+ is not the value we pass to the `generator`'s `[`~generation.GenerationMixin.generate`]` function,
955
+ where we set `num_return_sequences` to `num_beams`.
956
+ num_beams (`int`, *optional*, defaults to 1):
957
+ Number of beams for beam search. 1 means no beam search.
958
+ n_docs (`int`, *optional*, defaults to `config.n_docs`)
959
+ Number of documents to retrieve and/or number of documents for which to generate an answer.
960
+ kwargs (`Dict[str, Any]`, *optional*):
961
+ Additional kwargs will be passed to [`~generation.GenerationMixin.generate`].
962
+
963
+ Return:
964
+ `torch.LongTensor` of shape `(batch_size * num_return_sequences, sequence_length)`: The generated
965
+ sequences. The second dimension (sequence length) is either equal to `max_length` or shorter if all batches
966
+ finished early due to the `eos_token_id`.
967
+ """
968
+
969
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
970
+ do_deduplication = do_deduplication if do_deduplication is not None else self.config.do_deduplication
971
+ num_doc_return_sequences = (
972
+ num_return_sequences if num_return_sequences is not None else self.config.num_return_sequences
973
+ )
974
+ num_beams = num_beams if num_beams is not None else self.config.num_beams
975
+
976
+ assert (
977
+ input_ids is not None or context_input_ids is not None
978
+ ), " At least one of input_ids or context_input_ids must be given"
979
+
980
+ if self.retriever is not None and context_input_ids is None:
981
+ question_hidden_states = self.question_encoder(input_ids, attention_mask=attention_mask)[0]
982
+ context_input_ids = self.retriever(
983
+ input_ids,
984
+ question_hidden_states.cpu().detach().to(torch.float32).numpy(),
985
+ prefix=self.generator.config.prefix,
986
+ n_docs=n_docs,
987
+ return_tensors="pt",
988
+ )["context_input_ids"]
989
+
990
+ # set to correct device
991
+ context_input_ids = context_input_ids.to(input_ids)
992
+
993
+ hypos = []
994
+ model_kwargs["num_beams"] = num_beams
995
+ model_kwargs["num_return_sequences"] = num_beams
996
+ model_kwargs["attention_mask"] = None
997
+
998
+ batch_size = input_ids.shape[0] if input_ids is not None else context_input_ids.shape[0] // n_docs
999
+
1000
+ for index in range(batch_size):
1001
+ # first, generate beams from documents:
1002
+ generator_input_ids = context_input_ids[index * n_docs : (index + 1) * n_docs] # (n_docs, max_len)
1003
+
1004
+ output_sequences = self.generator.generate(
1005
+ generator_input_ids,
1006
+ **model_kwargs,
1007
+ ) # n_docs * n_beam, tgt_len
1008
+ if do_deduplication:
1009
+ # do_deduplication, max_output_len
1010
+ output_sequences = torch.stack(list({str(k.tolist()): k for k in output_sequences}.values()))
1011
+
1012
+ num_candidates = output_sequences.shape[
1013
+ 0
1014
+ ] # after deduplication, this number can be less than n_docs*n_beam
1015
+
1016
+ # then, run model forwards to get nll scores:
1017
+ if input_ids is not None:
1018
+ new_input_ids = input_ids[index : index + 1].repeat(num_candidates, 1)
1019
+ outputs = self(new_input_ids, labels=output_sequences, exclude_bos_score=True)
1020
+ else: # input_ids is None, need context_input_ids/mask and doc_scores
1021
+ assert context_attention_mask is not None, (
1022
+ "Make sure that `context_attention_mask` are passed, if no `input_ids` is set. Alternatively, you"
1023
+ " can set a retriever using the `set_retriever(...)` function."
1024
+ )
1025
+ assert doc_scores is not None, (
1026
+ "Make sure that `doc_scores` are passed, if no `input_ids` is set. Alternatively, you can set a"
1027
+ " retriever using the `set_retriever(...)` function."
1028
+ )
1029
+
1030
+ individual_input_ids = generator_input_ids.repeat(
1031
+ num_candidates, 1
1032
+ ) # (num_candidates*n_docs, max_len)
1033
+
1034
+ individual_attention_mask = context_attention_mask[index * n_docs : (index + 1) * n_docs]
1035
+ individual_attention_mask = individual_attention_mask.repeat(num_candidates, 1)
1036
+
1037
+ individual_doc_scores = doc_scores[index : (index + 1), :] # doc_scores.shape = [batch, n_docs]
1038
+ individual_doc_scores = individual_doc_scores.repeat(num_candidates, 1) # [num_candidates, n_docs]
1039
+
1040
+ outputs = self(
1041
+ context_input_ids=individual_input_ids,
1042
+ context_attention_mask=individual_attention_mask,
1043
+ doc_scores=individual_doc_scores,
1044
+ labels=output_sequences,
1045
+ exclude_bos_score=True,
1046
+ )
1047
+
1048
+ top_cand_inds = (-outputs["loss"]).topk(num_doc_return_sequences)[1]
1049
+
1050
+ # add hypothesis
1051
+ hypos.append(output_sequences[top_cand_inds])
1052
+
1053
+ return self._cat_and_pad(hypos, pad_token_id=self.config.generator.pad_token_id)
1054
+
1055
+ def get_nll(
1056
+ self, seq_logits, doc_scores, target, reduce_loss=False, epsilon=0.0, exclude_bos_score=False, n_docs=None
1057
+ ):
1058
+ # shift tokens left
1059
+ target = torch.cat(
1060
+ [target[:, 1:], target.new(target.shape[0], 1).fill_(self.config.generator.pad_token_id)], 1
1061
+ )
1062
+
1063
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
1064
+
1065
+ # bos_token_id is None for T5
1066
+ bos_token_id = self.config.bos_token_id or self.config.generator.bos_token_id
1067
+ use_bos = bos_token_id is not None and target[:, 0].eq(bos_token_id).all()
1068
+
1069
+ def _mask_pads(ll, smooth_obj):
1070
+ pad_mask = target.eq(self.config.generator.pad_token_id)
1071
+ if pad_mask.any():
1072
+ ll.masked_fill_(pad_mask, 0.0)
1073
+ smooth_obj.masked_fill_(pad_mask, 0.0)
1074
+ return ll.squeeze(-1), smooth_obj.squeeze(-1)
1075
+
1076
+ # seq_logits dim = (batch*n_docs, tgt_len , #vocabs)
1077
+ seq_logprobs = nn.functional.log_softmax(seq_logits, dim=-1).view(
1078
+ seq_logits.shape[0] // n_docs, n_docs, -1, seq_logits.size(-1)
1079
+ ) # batch_size x n_docs x tgt_len x #vocab_size
1080
+ doc_logprobs = nn.functional.log_softmax(doc_scores, dim=1).unsqueeze(-1).unsqueeze(-1)
1081
+
1082
+ # RAG-sequence marginalization
1083
+ first_token_scores = seq_logprobs[:, :, :1, :]
1084
+ second_token_scores = seq_logprobs[:, :, 1:2, :]
1085
+ remainder = seq_logprobs[:, :, 2:, :]
1086
+ rag_logprobs = torch.cat([first_token_scores, second_token_scores + doc_logprobs, remainder], dim=2)
1087
+
1088
+ # calculate loss
1089
+ target = target.unsqueeze(1).unsqueeze(-1).repeat(1, n_docs, 1, 1)
1090
+ assert target.dim() == rag_logprobs.dim()
1091
+
1092
+ ll = rag_logprobs.gather(dim=-1, index=target)
1093
+ smooth_obj = rag_logprobs.sum(dim=-1, keepdim=True) # total sum of all (normalised) logits
1094
+
1095
+ ll, smooth_obj = _mask_pads(ll, smooth_obj)
1096
+
1097
+ # sum over tokens, exclude bos while scoring
1098
+ ll = ll[:, :, 1:].sum(2) if exclude_bos_score and use_bos else ll.sum(2)
1099
+ smooth_obj = smooth_obj.sum(2)
1100
+ ll = ll.logsumexp(1) # logsumexp over docs
1101
+ smooth_obj = smooth_obj.logsumexp(1)
1102
+
1103
+ nll_loss = -ll
1104
+ smooth_loss = -smooth_obj
1105
+
1106
+ if reduce_loss:
1107
+ nll_loss = nll_loss.sum()
1108
+ smooth_loss = smooth_loss.sum()
1109
+
1110
+ eps_i = epsilon / rag_logprobs.size(-1)
1111
+ loss = (1.0 - epsilon) * nll_loss + eps_i * smooth_loss
1112
+ return loss
1113
+
1114
+ @staticmethod
1115
+ def _cat_and_pad(tensors, pad_token_id):
1116
+ output = (
1117
+ tensors[0].new(sum([t.shape[0] for t in tensors]), max([t.shape[1] for t in tensors])).fill_(pad_token_id)
1118
+ )
1119
+ ind = 0
1120
+ for t in tensors:
1121
+ output[ind : ind + t.shape[0], : t.shape[1]] = t
1122
+ ind += t.shape[0]
1123
+ return output
1124
+
1125
+
1126
+ @add_start_docstrings_to_model_forward(
1127
+ """
1128
+ A RAG-token model implementation. It performs RAG-token specific marginalization in the forward pass.
1129
+ """,
1130
+ RAG_START_DOCSTRING,
1131
+ )
1132
+ class RagTokenForGeneration(RagPreTrainedModel):
1133
+ def __init__(
1134
+ self,
1135
+ config: Optional[PretrainedConfig] = None,
1136
+ question_encoder: Optional[PreTrainedModel] = None,
1137
+ generator: Optional[PreTrainedModel] = None,
1138
+ retriever: Optional[RagRetriever] = None,
1139
+ **kwargs,
1140
+ ):
1141
+ assert config is not None or (
1142
+ question_encoder is not None and generator is not None
1143
+ ), "Either a configuration or an encoder and a generator has to be provided."
1144
+
1145
+ if config is None:
1146
+ config = RagConfig.from_question_encoder_generator_configs(
1147
+ question_encoder.config, generator.config, **kwargs
1148
+ )
1149
+
1150
+ super().__init__(config)
1151
+
1152
+ # instantiate model
1153
+ self.rag = RagModel(config=config, question_encoder=question_encoder, generator=generator, retriever=retriever)
1154
+
1155
+ def set_retriever(self, retriever: RagRetriever):
1156
+ self.rag.retriever = retriever
1157
+
1158
+ def set_context_encoder_for_training(self, ctx_encoder: PreTrainedModel):
1159
+ self.rag.context_encoder_training = True
1160
+ self.rag.ctx_encoder = ctx_encoder
1161
+
1162
+ def prepare_inputs_for_generation(
1163
+ self,
1164
+ decoder_input_ids,
1165
+ past_key_values=None,
1166
+ attention_mask=None,
1167
+ use_cache=None,
1168
+ encoder_outputs=None,
1169
+ doc_scores=None,
1170
+ n_docs=None,
1171
+ **kwargs,
1172
+ ):
1173
+ # Overwritten -- `do_marginalize` is explicitly set in the output
1174
+
1175
+ if past_key_values is not None:
1176
+ # if past is defined use only last decoder_input_ids
1177
+ decoder_input_ids = decoder_input_ids[:, -1:]
1178
+
1179
+ return {
1180
+ "input_ids": None,
1181
+ "encoder_outputs": encoder_outputs,
1182
+ "doc_scores": doc_scores,
1183
+ "context_attention_mask": attention_mask,
1184
+ "decoder_input_ids": decoder_input_ids,
1185
+ "past_key_values": past_key_values,
1186
+ "use_cache": use_cache,
1187
+ "do_marginalize": True,
1188
+ "n_docs": n_docs,
1189
+ }
1190
+
1191
+ @property
1192
+ def retriever(self):
1193
+ return self.rag.retriever
1194
+
1195
+ @property
1196
+ def generator(self):
1197
+ return self.rag.generator
1198
+
1199
+ @property
1200
+ def question_encoder(self):
1201
+ return self.rag.question_encoder
1202
+
1203
+ @staticmethod
1204
+ def _reorder_cache(past_key_values, beam_idx):
1205
+ """Reorders cache for generation. BART-inspired but we need to take care of the extra dimension for docs"""
1206
+
1207
+ def _reorder_stacked(hidden_states, new_order):
1208
+ n_docs = hidden_states.shape[0] // new_order.shape[0]
1209
+ hidden_states = hidden_states.view(-1, n_docs, *hidden_states.shape[1:])
1210
+ hidden_states = hidden_states.index_select(0, new_order)
1211
+ result = hidden_states.view(-1, *hidden_states.shape[2:])
1212
+ return result
1213
+
1214
+ reordered_past = ()
1215
+ for layer_past in past_key_values:
1216
+ # get the correct batch idx from decoder layer's batch dim for cross and self-attn
1217
+ reordered_past += (
1218
+ tuple(_reorder_stacked(past_state, beam_idx.to(past_state.device)) for past_state in layer_past),
1219
+ )
1220
+
1221
+ return reordered_past
1222
+
1223
+ def marginalize(self, seq_logits, doc_scores, n_docs=None):
1224
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
1225
+
1226
+ # RAG-token marginalization
1227
+ seq_logprobs = nn.functional.log_softmax(seq_logits, dim=-1).view(
1228
+ seq_logits.shape[0] // n_docs, n_docs, -1, seq_logits.size(-1)
1229
+ )
1230
+ doc_logprobs = torch.log_softmax(doc_scores, dim=1)
1231
+ log_prob_sum = seq_logprobs + doc_logprobs.unsqueeze(-1).unsqueeze(-1)
1232
+ return torch.logsumexp(log_prob_sum, dim=1)
1233
+
1234
+ @add_start_docstrings_to_model_forward(RAG_FORWARD_INPUTS_DOCSTRING)
1235
+ @replace_return_docstrings(output_type=RetrievAugLMMarginOutput, config_class=_CONFIG_FOR_DOC)
1236
+ def forward(
1237
+ self,
1238
+ input_ids: Optional[torch.LongTensor] = None,
1239
+ attention_mask: Optional[torch.FloatTensor] = None,
1240
+ encoder_outputs: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1241
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1242
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
1243
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1244
+ context_input_ids: Optional[torch.LongTensor] = None,
1245
+ context_attention_mask: Optional[torch.LongTensor] = None,
1246
+ doc_scores: Optional[torch.FloatTensor] = None,
1247
+ use_cache: Optional[bool] = None,
1248
+ output_attentions: Optional[bool] = None,
1249
+ output_hidden_states: Optional[bool] = None,
1250
+ output_retrieved: Optional[bool] = None,
1251
+ do_marginalize: Optional[bool] = None,
1252
+ reduce_loss: Optional[bool] = None,
1253
+ labels: Optional[torch.LongTensor] = None,
1254
+ n_docs: Optional[int] = None,
1255
+ **kwargs, # needs kwargs for generation
1256
+ ) -> RetrievAugLMMarginOutput:
1257
+ r"""
1258
+ do_marginalize (`bool`, *optional*):
1259
+ If `True`, the logits are marginalized over all documents by making use of
1260
+ `torch.nn.functional.log_softmax`.
1261
+ reduce_loss (`bool`, *optional*):
1262
+ Only relevant if `labels` is passed. If `True`, the NLL loss is reduced using the `torch.Tensor.sum`
1263
+ operation.
1264
+ kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
1265
+ Legacy dictionary, which is required so that model can use *generate()* function.
1266
+
1267
+ Returns:
1268
+
1269
+ Example:
1270
+
1271
+ ```python
1272
+ >>> from transformers import AutoTokenizer, RagRetriever, RagTokenForGeneration
1273
+ >>> import torch
1274
+
1275
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/rag-token-nq")
1276
+ >>> retriever = RagRetriever.from_pretrained(
1277
+ ... "facebook/rag-token-nq", index_name="exact", use_dummy_dataset=True
1278
+ ... )
1279
+ >>> # initialize with RagRetriever to do everything in one forward call
1280
+ >>> model = RagTokenForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever)
1281
+
1282
+ >>> inputs = tokenizer("How many people live in Paris?", return_tensors="pt")
1283
+ >>> targets = tokenizer(text_target="In Paris, there are 10 million people.", return_tensors="pt")
1284
+ >>> input_ids = inputs["input_ids"]
1285
+ >>> labels = targets["input_ids"]
1286
+ >>> outputs = model(input_ids=input_ids, labels=labels)
1287
+
1288
+ >>> # or use retriever separately
1289
+ >>> model = RagTokenForGeneration.from_pretrained("facebook/rag-token-nq", use_dummy_dataset=True)
1290
+ >>> # 1. Encode
1291
+ >>> question_hidden_states = model.question_encoder(input_ids)[0]
1292
+ >>> # 2. Retrieve
1293
+ >>> docs_dict = retriever(input_ids.numpy(), question_hidden_states.detach().numpy(), return_tensors="pt")
1294
+ >>> doc_scores = torch.bmm(
1295
+ ... question_hidden_states.unsqueeze(1), docs_dict["retrieved_doc_embeds"].float().transpose(1, 2)
1296
+ ... ).squeeze(1)
1297
+ >>> # 3. Forward to generator
1298
+ >>> outputs = model(
1299
+ ... context_input_ids=docs_dict["context_input_ids"],
1300
+ ... context_attention_mask=docs_dict["context_attention_mask"],
1301
+ ... doc_scores=doc_scores,
1302
+ ... decoder_input_ids=labels,
1303
+ ... )
1304
+
1305
+ >>> # or directly generate
1306
+ >>> generated = model.generate(
1307
+ ... context_input_ids=docs_dict["context_input_ids"],
1308
+ ... context_attention_mask=docs_dict["context_attention_mask"],
1309
+ ... doc_scores=doc_scores,
1310
+ ... )
1311
+ >>> generated_string = tokenizer.batch_decode(generated, skip_special_tokens=True)
1312
+ ```"""
1313
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
1314
+ do_marginalize = do_marginalize if do_marginalize is not None else self.config.do_marginalize
1315
+ reduce_loss = reduce_loss if reduce_loss is not None else self.config.reduce_loss
1316
+
1317
+ if labels is not None:
1318
+ if decoder_input_ids is None:
1319
+ decoder_input_ids = labels
1320
+ use_cache = False
1321
+
1322
+ outputs = self.rag(
1323
+ input_ids=input_ids,
1324
+ attention_mask=attention_mask,
1325
+ encoder_outputs=encoder_outputs,
1326
+ decoder_input_ids=decoder_input_ids,
1327
+ decoder_attention_mask=decoder_attention_mask,
1328
+ context_input_ids=context_input_ids,
1329
+ context_attention_mask=context_attention_mask,
1330
+ doc_scores=doc_scores,
1331
+ past_key_values=past_key_values,
1332
+ use_cache=use_cache,
1333
+ output_attentions=output_attentions,
1334
+ output_hidden_states=output_hidden_states,
1335
+ output_retrieved=output_retrieved,
1336
+ n_docs=n_docs,
1337
+ )
1338
+
1339
+ loss = None
1340
+ logits = outputs.logits
1341
+ if labels is not None:
1342
+ assert decoder_input_ids is not None
1343
+ loss = self.get_nll(
1344
+ outputs.logits,
1345
+ outputs.doc_scores,
1346
+ labels,
1347
+ reduce_loss=reduce_loss,
1348
+ epsilon=self.config.label_smoothing,
1349
+ n_docs=n_docs,
1350
+ )
1351
+
1352
+ if do_marginalize:
1353
+ logits = self.marginalize(logits, outputs.doc_scores, n_docs)
1354
+
1355
+ return RetrievAugLMMarginOutput(
1356
+ loss=loss,
1357
+ logits=logits,
1358
+ doc_scores=outputs.doc_scores,
1359
+ past_key_values=outputs.past_key_values,
1360
+ context_input_ids=outputs.context_input_ids,
1361
+ context_attention_mask=outputs.context_attention_mask,
1362
+ retrieved_doc_embeds=outputs.retrieved_doc_embeds,
1363
+ retrieved_doc_ids=outputs.retrieved_doc_ids,
1364
+ question_encoder_last_hidden_state=outputs.question_encoder_last_hidden_state,
1365
+ question_enc_hidden_states=outputs.question_enc_hidden_states,
1366
+ question_enc_attentions=outputs.question_enc_attentions,
1367
+ generator_enc_last_hidden_state=outputs.generator_enc_last_hidden_state,
1368
+ generator_enc_hidden_states=outputs.generator_enc_hidden_states,
1369
+ generator_enc_attentions=outputs.generator_enc_attentions,
1370
+ generator_dec_hidden_states=outputs.generator_dec_hidden_states,
1371
+ generator_dec_attentions=outputs.generator_dec_attentions,
1372
+ generator_cross_attentions=outputs.generator_cross_attentions,
1373
+ )
1374
+
1375
+ @torch.no_grad()
1376
+ def generate(
1377
+ self,
1378
+ input_ids: Optional[torch.LongTensor] = None,
1379
+ attention_mask: Optional[torch.LongTensor] = None,
1380
+ context_input_ids: Optional[torch.LongTensor] = None,
1381
+ context_attention_mask: Optional[torch.LongTensor] = None,
1382
+ doc_scores: Optional[torch.FloatTensor] = None,
1383
+ n_docs: Optional[int] = None,
1384
+ generation_config: Optional[GenerationConfig] = None,
1385
+ prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], List[int]] = None,
1386
+ logits_processor: Optional[LogitsProcessorList] = LogitsProcessorList(),
1387
+ stopping_criteria: Optional[StoppingCriteriaList] = StoppingCriteriaList(),
1388
+ **kwargs,
1389
+ ) -> torch.LongTensor:
1390
+ """
1391
+ Implements RAG token decoding.
1392
+
1393
+ Args:
1394
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1395
+ The sequence used as a prompt for the generation. If `input_ids` is not passed, then
1396
+ `context_input_ids` has to be provided.
1397
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1398
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1399
+
1400
+ - 1 for tokens that are **not masked**,
1401
+ - 0 for tokens that are **masked**.
1402
+
1403
+ [What are attention masks?](../glossary#attention-mask)
1404
+ context_input_ids (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
1405
+ Input IDs post-processed from the retrieved documents and the question encoder `input_ids` by the
1406
+ retriever.
1407
+
1408
+ If the model has is not initialized with a `retriever`, `context_input_ids` has to be provided to the
1409
+ forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`].
1410
+ context_attention_mask (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
1411
+ Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
1412
+ retriever.
1413
+
1414
+ If the model has is not initialized with a `retriever`, `context_input_ids` has to be provided to the
1415
+ forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`].
1416
+ doc_scores (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`):
1417
+ Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
1418
+ `question_encoder_last_hidden_state`.
1419
+
1420
+ If the model has is not initialized with a `retriever`, `context_input_ids` has to be provided to the
1421
+ forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`].
1422
+ n_docs (`int`, *optional*, defaults to `config.n_docs`)
1423
+ Number of documents to retrieve and/or number of documents for which to generate an answer.
1424
+ generation_config (`~generation.GenerationConfig`, *optional*):
1425
+ The generation configuration to be used as base parametrization for the generation call. `**kwargs`
1426
+ passed to generate matching the attributes of `generation_config` will override them. If
1427
+ `generation_config` is not provided, the default will be used, which has the following loading
1428
+ priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
1429
+ configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
1430
+ default values, whose documentation should be checked to parameterize generation.
1431
+ prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`, *optional*):
1432
+ If provided, this function constraints the beam search to allowed tokens only at each step. If not
1433
+ provided no constraint is applied. This function takes 2 arguments `inputs_ids` and the batch ID
1434
+ `batch_id`. It has to return a list with the allowed tokens for the next generation step conditioned on
1435
+ the previously generated tokens `inputs_ids` and the batch ID `batch_id`. This argument is useful for
1436
+ constrained generation conditioned on the prefix, as described in [Autoregressive Entity
1437
+ Retrieval](https://arxiv.org/abs/2010.00904).
1438
+ logits_processor (`LogitsProcessorList`, *optional*):
1439
+ Custom logits processors that complement the default logits processors built from arguments and a
1440
+ model's config. If a logit processor is passed that is already created with the arguments or a model's
1441
+ config an error is thrown.
1442
+ stopping_criteria (`StoppingCriteriaList`, *optional*):
1443
+ Custom stopping criteria that complement the default stopping criteria built from arguments and a
1444
+ model's config. If a stopping criteria is passed that is already created with the arguments or a
1445
+ model's config an error is thrown.
1446
+ kwargs (`Dict[str, Any]`, *optional*):
1447
+ Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be
1448
+ forwarded to the `forward` function of the model.
1449
+
1450
+ Return:
1451
+ `torch.LongTensor` of shape `(batch_size * num_return_sequences, sequence_length)`: The generated
1452
+ sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter if all batches
1453
+ finished early due to the `eos_token_id`.
1454
+ """
1455
+ # Handle `generation_config` and kwargs that might update it
1456
+ if generation_config is None:
1457
+ generation_config = self.generation_config
1458
+ generation_config = copy.deepcopy(generation_config)
1459
+ model_kwargs = generation_config.update(**kwargs) # All unused kwargs must be model kwargs
1460
+
1461
+ kwargs_has_attention_mask = model_kwargs.get("attention_mask", None) is not None
1462
+ self._prepare_special_tokens(generation_config, kwargs_has_attention_mask)
1463
+
1464
+ # set default parameters
1465
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
1466
+
1467
+ # retrieve docs
1468
+ if self.retriever is not None and context_input_ids is None:
1469
+ question_hidden_states = self.question_encoder(input_ids, attention_mask=attention_mask)[0]
1470
+ out = self.retriever(
1471
+ input_ids,
1472
+ question_hidden_states.cpu().detach().to(torch.float32).numpy(),
1473
+ prefix=self.generator.config.prefix,
1474
+ n_docs=n_docs,
1475
+ return_tensors="pt",
1476
+ )
1477
+ context_input_ids, context_attention_mask, retrieved_doc_embeds = (
1478
+ out["context_input_ids"],
1479
+ out["context_attention_mask"],
1480
+ out["retrieved_doc_embeds"],
1481
+ )
1482
+
1483
+ # set to correct device
1484
+ retrieved_doc_embeds = retrieved_doc_embeds.to(question_hidden_states)
1485
+ context_input_ids = context_input_ids.to(input_ids)
1486
+ context_attention_mask = context_attention_mask.to(input_ids)
1487
+
1488
+ # compute doc_scores
1489
+ doc_scores = torch.bmm(question_hidden_states.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)).squeeze(
1490
+ 1
1491
+ )
1492
+
1493
+ assert (context_input_ids.shape[0] % n_docs) == 0, (
1494
+ f" The first dimension of `context_input_ids` should be a multiple of `n_docs`={n_docs}, but is"
1495
+ f" {context_input_ids.shape[0]}."
1496
+ )
1497
+
1498
+ # batch_size
1499
+ batch_size = context_input_ids.shape[0] // n_docs
1500
+
1501
+ encoder = self.rag.generator.get_encoder()
1502
+ encoder_outputs = encoder(input_ids=context_input_ids, attention_mask=context_attention_mask, return_dict=True)
1503
+
1504
+ input_ids = torch.full(
1505
+ (batch_size * generation_config.num_beams, 1),
1506
+ generation_config.decoder_start_token_id,
1507
+ dtype=torch.long,
1508
+ device=next(self.parameters()).device,
1509
+ )
1510
+ input_ids_seq_length = input_ids.shape[-1]
1511
+ last_hidden_state = encoder_outputs["last_hidden_state"]
1512
+
1513
+ def extend_enc_output(tensor, num_beams=None):
1514
+ # split into `batch_size`, `num_beams`, `num_docs`
1515
+ tensor = tensor[None, None, :].reshape((batch_size, 1, n_docs) + tensor.shape[1:])
1516
+ # repeat same last hidden states over `num_beams` dimension
1517
+ tensor = tensor.expand((batch_size, num_beams, n_docs) + tensor.shape[3:])
1518
+ # merge `batch_size`, `num_beams`, `num_docs` dims again
1519
+ return tensor.reshape((batch_size * num_beams * n_docs,) + tensor.shape[3:])
1520
+
1521
+ # correctly extend last_hidden_state and attention mask
1522
+ context_attention_mask = extend_enc_output(context_attention_mask, num_beams=generation_config.num_beams)
1523
+ encoder_outputs["last_hidden_state"] = extend_enc_output(
1524
+ last_hidden_state, num_beams=generation_config.num_beams
1525
+ )
1526
+
1527
+ doc_scores = doc_scores.repeat_interleave(generation_config.num_beams, dim=0)
1528
+
1529
+ # define start_len & additional parameters
1530
+ model_kwargs["doc_scores"] = doc_scores
1531
+ model_kwargs["encoder_outputs"] = encoder_outputs
1532
+ model_kwargs["attention_mask"] = context_attention_mask
1533
+ model_kwargs["n_docs"] = n_docs
1534
+
1535
+ pre_processor = self._get_logits_processor(
1536
+ generation_config=generation_config,
1537
+ input_ids_seq_length=input_ids_seq_length,
1538
+ encoder_input_ids=context_input_ids,
1539
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1540
+ logits_processor=logits_processor,
1541
+ device=input_ids.device,
1542
+ )
1543
+
1544
+ prepared_stopping_criteria = self._get_stopping_criteria(
1545
+ generation_config=generation_config, stopping_criteria=stopping_criteria
1546
+ )
1547
+
1548
+ if generation_config.num_beams == 1:
1549
+ if generation_config.num_return_sequences > 1:
1550
+ raise ValueError(
1551
+ f"num_return_sequences has to be 1, but is {generation_config.num_return_sequences} when doing"
1552
+ " greedy search."
1553
+ )
1554
+ return self._sample(
1555
+ input_ids,
1556
+ logits_processor=pre_processor,
1557
+ stopping_criteria=prepared_stopping_criteria,
1558
+ generation_config=generation_config,
1559
+ synced_gpus=False,
1560
+ streamer=None,
1561
+ **model_kwargs,
1562
+ )
1563
+ elif generation_config.num_beams > 1:
1564
+ if generation_config.num_return_sequences > generation_config.num_beams:
1565
+ raise ValueError("`num_return_sequences` has to be smaller or equal to `num_beams`.")
1566
+ beam_scorer = BeamSearchScorer(
1567
+ batch_size=batch_size,
1568
+ num_beams=generation_config.num_beams,
1569
+ device=self.device,
1570
+ length_penalty=generation_config.length_penalty,
1571
+ do_early_stopping=generation_config.early_stopping,
1572
+ num_beam_hyps_to_keep=generation_config.num_return_sequences,
1573
+ max_length=generation_config.max_length,
1574
+ )
1575
+ return self._beam_search(
1576
+ input_ids,
1577
+ beam_scorer,
1578
+ logits_processor=pre_processor,
1579
+ stopping_criteria=prepared_stopping_criteria,
1580
+ generation_config=generation_config,
1581
+ synced_gpus=False,
1582
+ **model_kwargs,
1583
+ )
1584
+ else:
1585
+ raise ValueError(
1586
+ f"`num_beams` has to be an integer strictly superior to 0 (≥ 1), but is {generation_config.num_beams}"
1587
+ )
1588
+
1589
+ def get_input_embeddings(self):
1590
+ return self.rag.generator.get_input_embeddings()
1591
+
1592
+ def get_output_embeddings(self):
1593
+ return self.rag.generator.get_output_embeddings()
1594
+
1595
+ def set_output_embeddings(self, new_embeddings):
1596
+ return self.rag.generator.set_output_embeddings(new_embeddings)
1597
+
1598
+ def shift_tokens_right(self, input_ids, start_token_id=None):
1599
+ """Shift input ids one token to the right, and pad with start_token_id"""
1600
+ if start_token_id is None:
1601
+ start_token_id = self.config.decoder_start_token_id
1602
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
1603
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
1604
+ shifted_input_ids[:, 0] = start_token_id
1605
+ return shifted_input_ids
1606
+
1607
+ def get_nll(self, seq_logits, doc_scores, target, reduce_loss=False, epsilon=0.0, n_docs=None):
1608
+ n_docs = n_docs if n_docs is not None else self.config.n_docs
1609
+ # shift tokens left
1610
+ target = torch.cat(
1611
+ [target[:, 1:], target.new(target.shape[0], 1).fill_(self.config.generator.pad_token_id)], 1
1612
+ )
1613
+
1614
+ def _mask_pads(ll, smooth_obj):
1615
+ pad_mask = target.eq(self.config.generator.pad_token_id)
1616
+ if pad_mask.any():
1617
+ ll.masked_fill_(pad_mask, 0.0)
1618
+ smooth_obj.masked_fill_(pad_mask, 0.0)
1619
+ return ll.squeeze(-1), smooth_obj.squeeze(-1)
1620
+
1621
+ rag_logprobs = self.marginalize(seq_logits, doc_scores, n_docs)
1622
+
1623
+ target = target.unsqueeze(-1)
1624
+ assert target.dim() == rag_logprobs.dim()
1625
+
1626
+ ll = rag_logprobs.gather(dim=-1, index=target)
1627
+ smooth_obj = rag_logprobs.sum(dim=-1, keepdim=True) # total sum of all (normalised) logits
1628
+ ll, smooth_obj = _mask_pads(ll, smooth_obj)
1629
+ ll = ll.sum(1) # sum over tokens
1630
+ smooth_obj = smooth_obj.sum(1)
1631
+
1632
+ nll_loss = -ll
1633
+ smooth_loss = -smooth_obj
1634
+
1635
+ if reduce_loss:
1636
+ nll_loss = nll_loss.sum()
1637
+ smooth_loss = smooth_loss.sum()
1638
+
1639
+ eps_i = epsilon / rag_logprobs.size(-1)
1640
+ loss = (1.0 - epsilon) * nll_loss + eps_i * smooth_loss
1641
+ return loss
1642
+
1643
+
1644
+ __all__ = ["RagModel", "RagPreTrainedModel", "RagSequenceForGeneration", "RagTokenForGeneration"]
vlmpy310/lib/python3.10/site-packages/transformers/models/rag/tokenization_rag.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020, The RAG Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for RAG."""
16
+
17
+ import os
18
+ import warnings
19
+ from typing import List, Optional
20
+
21
+ from ...tokenization_utils_base import BatchEncoding
22
+ from ...utils import logging
23
+ from .configuration_rag import RagConfig
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ class RagTokenizer:
30
+ def __init__(self, question_encoder, generator):
31
+ self.question_encoder = question_encoder
32
+ self.generator = generator
33
+ self.current_tokenizer = self.question_encoder
34
+
35
+ def save_pretrained(self, save_directory):
36
+ if os.path.isfile(save_directory):
37
+ raise ValueError(f"Provided path ({save_directory}) should be a directory, not a file")
38
+ os.makedirs(save_directory, exist_ok=True)
39
+ question_encoder_path = os.path.join(save_directory, "question_encoder_tokenizer")
40
+ generator_path = os.path.join(save_directory, "generator_tokenizer")
41
+ self.question_encoder.save_pretrained(question_encoder_path)
42
+ self.generator.save_pretrained(generator_path)
43
+
44
+ @classmethod
45
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
46
+ # dynamically import AutoTokenizer
47
+ from ..auto.tokenization_auto import AutoTokenizer
48
+
49
+ config = kwargs.pop("config", None)
50
+
51
+ if config is None:
52
+ config = RagConfig.from_pretrained(pretrained_model_name_or_path)
53
+
54
+ question_encoder = AutoTokenizer.from_pretrained(
55
+ pretrained_model_name_or_path, config=config.question_encoder, subfolder="question_encoder_tokenizer"
56
+ )
57
+ generator = AutoTokenizer.from_pretrained(
58
+ pretrained_model_name_or_path, config=config.generator, subfolder="generator_tokenizer"
59
+ )
60
+ return cls(question_encoder=question_encoder, generator=generator)
61
+
62
+ def __call__(self, *args, **kwargs):
63
+ return self.current_tokenizer(*args, **kwargs)
64
+
65
+ def batch_decode(self, *args, **kwargs):
66
+ return self.generator.batch_decode(*args, **kwargs)
67
+
68
+ def decode(self, *args, **kwargs):
69
+ return self.generator.decode(*args, **kwargs)
70
+
71
+ def _switch_to_input_mode(self):
72
+ self.current_tokenizer = self.question_encoder
73
+
74
+ def _switch_to_target_mode(self):
75
+ self.current_tokenizer = self.generator
76
+
77
+ def prepare_seq2seq_batch(
78
+ self,
79
+ src_texts: List[str],
80
+ tgt_texts: Optional[List[str]] = None,
81
+ max_length: Optional[int] = None,
82
+ max_target_length: Optional[int] = None,
83
+ padding: str = "longest",
84
+ return_tensors: str = None,
85
+ truncation: bool = True,
86
+ **kwargs,
87
+ ) -> BatchEncoding:
88
+ warnings.warn(
89
+ "`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the "
90
+ "regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` "
91
+ "context manager to prepare your targets. See the documentation of your specific tokenizer for more "
92
+ "details",
93
+ FutureWarning,
94
+ )
95
+ if max_length is None:
96
+ max_length = self.current_tokenizer.model_max_length
97
+ model_inputs = self(
98
+ src_texts,
99
+ add_special_tokens=True,
100
+ return_tensors=return_tensors,
101
+ max_length=max_length,
102
+ padding=padding,
103
+ truncation=truncation,
104
+ **kwargs,
105
+ )
106
+ if tgt_texts is None:
107
+ return model_inputs
108
+ # Process tgt_texts
109
+ if max_target_length is None:
110
+ max_target_length = self.current_tokenizer.model_max_length
111
+ labels = self(
112
+ text_target=tgt_texts,
113
+ add_special_tokens=True,
114
+ return_tensors=return_tensors,
115
+ padding=padding,
116
+ max_length=max_target_length,
117
+ truncation=truncation,
118
+ **kwargs,
119
+ )
120
+ model_inputs["labels"] = labels["input_ids"]
121
+ return model_inputs
122
+
123
+
124
+ __all__ = ["RagTokenizer"]
vlmpy310/lib/python3.10/site-packages/transformers/models/sam/__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_sam import *
22
+ from .image_processing_sam import *
23
+ from .modeling_sam import *
24
+ from .modeling_tf_sam import *
25
+ from .processing_sam 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__)
vlmpy310/lib/python3.10/site-packages/transformers/models/sam/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (616 Bytes). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/sam/__pycache__/convert_sam_to_hf.cpython-310.pyc ADDED
Binary file (5.94 kB). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/sam/__pycache__/image_processing_sam.cpython-310.pyc ADDED
Binary file (49.6 kB). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/sam/__pycache__/modeling_sam.cpython-310.pyc ADDED
Binary file (52.6 kB). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/sam/__pycache__/modeling_tf_sam.cpython-310.pyc ADDED
Binary file (54.4 kB). View file
 
vlmpy310/lib/python3.10/site-packages/transformers/models/sam/configuration_sam.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """SAM 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 SamPromptEncoderConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`SamPromptEncoder`]. The [`SamPromptEncoder`]
27
+ module is used to encode the input 2D points and bounding boxes. Instantiating a configuration defaults will yield
28
+ a similar configuration to that of the SAM-vit-h
29
+ [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+ Args:
35
+ hidden_size (`int`, *optional*, defaults to 256):
36
+ Dimensionality of the hidden states.
37
+ image_size (`int`, *optional*, defaults to 1024):
38
+ The expected output resolution of the image.
39
+ patch_size (`int`, *optional*, defaults to 16):
40
+ The size (resolution) of each patch.
41
+ mask_input_channels (`int`, *optional*, defaults to 16):
42
+ The number of channels to be fed to the `MaskDecoder` module.
43
+ num_point_embeddings (`int`, *optional*, defaults to 4):
44
+ The number of point embeddings to be used.
45
+ hidden_act (`str`, *optional*, defaults to `"gelu"`):
46
+ The non-linear activation function in the encoder and pooler.
47
+ """
48
+
49
+ base_config_key = "prompt_encoder_config"
50
+
51
+ def __init__(
52
+ self,
53
+ hidden_size=256,
54
+ image_size=1024,
55
+ patch_size=16,
56
+ mask_input_channels=16,
57
+ num_point_embeddings=4,
58
+ hidden_act="gelu",
59
+ layer_norm_eps=1e-6,
60
+ **kwargs,
61
+ ):
62
+ super().__init__(**kwargs)
63
+ self.hidden_size = hidden_size
64
+ self.image_size = image_size
65
+ self.patch_size = patch_size
66
+ self.image_embedding_size = image_size // patch_size
67
+ self.mask_input_channels = mask_input_channels
68
+ self.num_point_embeddings = num_point_embeddings
69
+ self.hidden_act = hidden_act
70
+ self.layer_norm_eps = layer_norm_eps
71
+
72
+
73
+ class SamMaskDecoderConfig(PretrainedConfig):
74
+ r"""
75
+ This is the configuration class to store the configuration of a [`SamMaskDecoder`]. It is used to instantiate a SAM
76
+ mask decoder to the specified arguments, defining the model architecture. Instantiating a configuration defaults
77
+ will yield a similar configuration to that of the SAM-vit-h
78
+ [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.
79
+
80
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
81
+ documentation from [`PretrainedConfig`] for more information.
82
+
83
+ Args:
84
+ hidden_size (`int`, *optional*, defaults to 256):
85
+ Dimensionality of the hidden states.
86
+ hidden_act (`str`, *optional*, defaults to `"relu"`):
87
+ The non-linear activation function used inside the `SamMaskDecoder` module.
88
+ mlp_dim (`int`, *optional*, defaults to 2048):
89
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
90
+ num_hidden_layers (`int`, *optional*, defaults to 2):
91
+ Number of hidden layers in the Transformer encoder.
92
+ num_attention_heads (`int`, *optional*, defaults to 8):
93
+ Number of attention heads for each attention layer in the Transformer encoder.
94
+ attention_downsample_rate (`int`, *optional*, defaults to 2):
95
+ The downsampling rate of the attention layer.
96
+ num_multimask_outputs (`int`, *optional*, defaults to 3):
97
+ The number of outputs from the `SamMaskDecoder` module. In the Segment Anything paper, this is set to 3.
98
+ iou_head_depth (`int`, *optional*, defaults to 3):
99
+ The number of layers in the IoU head module.
100
+ iou_head_hidden_dim (`int`, *optional*, defaults to 256):
101
+ The dimensionality of the hidden states in the IoU head module.
102
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
103
+ The epsilon used by the layer normalization layers.
104
+
105
+ """
106
+
107
+ base_config_key = "mask_decoder_config"
108
+
109
+ def __init__(
110
+ self,
111
+ hidden_size=256,
112
+ hidden_act="relu",
113
+ mlp_dim=2048,
114
+ num_hidden_layers=2,
115
+ num_attention_heads=8,
116
+ attention_downsample_rate=2,
117
+ num_multimask_outputs=3,
118
+ iou_head_depth=3,
119
+ iou_head_hidden_dim=256,
120
+ layer_norm_eps=1e-6,
121
+ **kwargs,
122
+ ):
123
+ super().__init__(**kwargs)
124
+ self.hidden_size = hidden_size
125
+ self.hidden_act = hidden_act
126
+ self.mlp_dim = mlp_dim
127
+ self.num_hidden_layers = num_hidden_layers
128
+ self.num_attention_heads = num_attention_heads
129
+ self.attention_downsample_rate = attention_downsample_rate
130
+ self.num_multimask_outputs = num_multimask_outputs
131
+ self.iou_head_depth = iou_head_depth
132
+ self.iou_head_hidden_dim = iou_head_hidden_dim
133
+ self.layer_norm_eps = layer_norm_eps
134
+
135
+
136
+ class SamVisionConfig(PretrainedConfig):
137
+ r"""
138
+ This is the configuration class to store the configuration of a [`SamVisionModel`]. It is used to instantiate a SAM
139
+ vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration
140
+ defaults will yield a similar configuration to that of the SAM ViT-h
141
+ [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.
142
+
143
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
144
+ documentation from [`PretrainedConfig`] for more information.
145
+
146
+ Args:
147
+ hidden_size (`int`, *optional*, defaults to 768):
148
+ Dimensionality of the encoder layers and the pooler layer.
149
+ output_channels (`int`, *optional*, defaults to 256):
150
+ Dimensionality of the output channels in the Patch Encoder.
151
+ num_hidden_layers (`int`, *optional*, defaults to 12):
152
+ Number of hidden layers in the Transformer encoder.
153
+ num_attention_heads (`int`, *optional*, defaults to 12):
154
+ Number of attention heads for each attention layer in the Transformer encoder.
155
+ num_channels (`int`, *optional*, defaults to 3):
156
+ Number of channels in the input image.
157
+ image_size (`int`, *optional*, defaults to 1024):
158
+ Expected resolution. Target size of the resized input image.
159
+ patch_size (`int`, *optional*, defaults to 16):
160
+ Size of the patches to be extracted from the input image.
161
+ hidden_act (`str`, *optional*, defaults to `"gelu"`):
162
+ The non-linear activation function (function or string)
163
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
164
+ The epsilon used by the layer normalization layers.
165
+ attention_dropout (`float`, *optional*, defaults to 0.0):
166
+ The dropout ratio for the attention probabilities.
167
+ initializer_range (`float`, *optional*, defaults to 1e-10):
168
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
169
+ qkv_bias (`bool`, *optional*, defaults to `True`):
170
+ Whether to add a bias to query, key, value projections.
171
+ mlp_ratio (`float`, *optional*, defaults to 4.0):
172
+ Ratio of mlp hidden dim to embedding dim.
173
+ use_abs_pos (`bool`, *optional*, defaults to `True`):
174
+ Whether to use absolute position embedding.
175
+ use_rel_pos (`bool`, *optional*, defaults to `True`):
176
+ Whether to use relative position embedding.
177
+ window_size (`int`, *optional*, defaults to 14):
178
+ Window size for relative position.
179
+ global_attn_indexes (`List[int]`, *optional*, defaults to `[2, 5, 8, 11]`):
180
+ The indexes of the global attention layers.
181
+ num_pos_feats (`int`, *optional*, defaults to 128):
182
+ The dimensionality of the position embedding.
183
+ mlp_dim (`int`, *optional*):
184
+ The dimensionality of the MLP layer in the Transformer encoder. If `None`, defaults to `mlp_ratio *
185
+ hidden_size`.
186
+ """
187
+
188
+ base_config_key = "vision_config"
189
+
190
+ def __init__(
191
+ self,
192
+ hidden_size=768,
193
+ output_channels=256,
194
+ num_hidden_layers=12,
195
+ num_attention_heads=12,
196
+ num_channels=3,
197
+ image_size=1024,
198
+ patch_size=16,
199
+ hidden_act="gelu",
200
+ layer_norm_eps=1e-06,
201
+ attention_dropout=0.0,
202
+ initializer_range=1e-10,
203
+ qkv_bias=True,
204
+ mlp_ratio=4.0,
205
+ use_abs_pos=True,
206
+ use_rel_pos=True,
207
+ window_size=14,
208
+ global_attn_indexes=[2, 5, 8, 11],
209
+ num_pos_feats=128,
210
+ mlp_dim=None,
211
+ **kwargs,
212
+ ):
213
+ super().__init__(**kwargs)
214
+
215
+ self.hidden_size = hidden_size
216
+ self.output_channels = output_channels
217
+ self.num_hidden_layers = num_hidden_layers
218
+ self.num_attention_heads = num_attention_heads
219
+ self.num_channels = num_channels
220
+ self.image_size = image_size
221
+ self.patch_size = patch_size
222
+ self.hidden_act = hidden_act
223
+ self.layer_norm_eps = layer_norm_eps
224
+ self.attention_dropout = attention_dropout
225
+ self.initializer_range = initializer_range
226
+ self.qkv_bias = qkv_bias
227
+ self.mlp_ratio = mlp_ratio
228
+ self.use_abs_pos = use_abs_pos
229
+ self.use_rel_pos = use_rel_pos
230
+ self.window_size = window_size
231
+ self.global_attn_indexes = global_attn_indexes
232
+ self.num_pos_feats = num_pos_feats
233
+ self.mlp_dim = int(hidden_size * mlp_ratio) if mlp_dim is None else mlp_dim
234
+
235
+
236
+ class SamConfig(PretrainedConfig):
237
+ r"""
238
+ [`SamConfig`] is the configuration class to store the configuration of a [`SamModel`]. It is used to instantiate a
239
+ SAM model according to the specified arguments, defining the vision model, prompt-encoder model and mask decoder
240
+ configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the
241
+ SAM-ViT-H [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.
242
+
243
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
244
+ documentation from [`PretrainedConfig`] for more information.
245
+
246
+ Args:
247
+ vision_config (Union[`dict`, `SamVisionConfig`], *optional*):
248
+ Dictionary of configuration options used to initialize [`SamVisionConfig`].
249
+ prompt_encoder_config (Union[`dict`, `SamPromptEncoderConfig`], *optional*):
250
+ Dictionary of configuration options used to initialize [`SamPromptEncoderConfig`].
251
+ mask_decoder_config (Union[`dict`, `SamMaskDecoderConfig`], *optional*):
252
+ Dictionary of configuration options used to initialize [`SamMaskDecoderConfig`].
253
+
254
+ kwargs (*optional*):
255
+ Dictionary of keyword arguments.
256
+
257
+ Example:
258
+
259
+ ```python
260
+ >>> from transformers import (
261
+ ... SamVisionConfig,
262
+ ... SamPromptEncoderConfig,
263
+ ... SamMaskDecoderConfig,
264
+ ... SamModel,
265
+ ... )
266
+
267
+ >>> # Initializing a SamConfig with `"facebook/sam-vit-huge"` style configuration
268
+ >>> configuration = SamConfig()
269
+
270
+ >>> # Initializing a SamModel (with random weights) from the `"facebook/sam-vit-huge"` style configuration
271
+ >>> model = SamModel(configuration)
272
+
273
+ >>> # Accessing the model configuration
274
+ >>> configuration = model.config
275
+
276
+ >>> # We can also initialize a SamConfig from a SamVisionConfig, SamPromptEncoderConfig, and SamMaskDecoderConfig
277
+
278
+ >>> # Initializing SAM vision, SAM Q-Former and language model configurations
279
+ >>> vision_config = SamVisionConfig()
280
+ >>> prompt_encoder_config = SamPromptEncoderConfig()
281
+ >>> mask_decoder_config = SamMaskDecoderConfig()
282
+
283
+ >>> config = SamConfig(vision_config, prompt_encoder_config, mask_decoder_config)
284
+ ```"""
285
+
286
+ model_type = "sam"
287
+ sub_configs = {
288
+ "prompt_encoder_config": SamPromptEncoderConfig,
289
+ "mask_decoder_config": SamMaskDecoderConfig,
290
+ "vision_config": SamVisionConfig,
291
+ }
292
+
293
+ def __init__(
294
+ self,
295
+ vision_config=None,
296
+ prompt_encoder_config=None,
297
+ mask_decoder_config=None,
298
+ initializer_range=0.02,
299
+ **kwargs,
300
+ ):
301
+ super().__init__(**kwargs)
302
+ vision_config = vision_config if vision_config is not None else {}
303
+ prompt_encoder_config = prompt_encoder_config if prompt_encoder_config is not None else {}
304
+ mask_decoder_config = mask_decoder_config if mask_decoder_config is not None else {}
305
+
306
+ if isinstance(vision_config, SamVisionConfig):
307
+ vision_config = vision_config.to_dict()
308
+ if isinstance(prompt_encoder_config, SamPromptEncoderConfig):
309
+ prompt_encoder_config = prompt_encoder_config.to_dict()
310
+ if isinstance(mask_decoder_config, SamMaskDecoderConfig):
311
+ mask_decoder_config = mask_decoder_config.to_dict()
312
+
313
+ self.vision_config = SamVisionConfig(**vision_config)
314
+ self.prompt_encoder_config = SamPromptEncoderConfig(**prompt_encoder_config)
315
+ self.mask_decoder_config = SamMaskDecoderConfig(**mask_decoder_config)
316
+ self.initializer_range = initializer_range
317
+
318
+
319
+ __all__ = ["SamConfig", "SamMaskDecoderConfig", "SamPromptEncoderConfig", "SamVisionConfig"]
vlmpy310/lib/python3.10/site-packages/transformers/models/sam/image_processing_sam.py ADDED
@@ -0,0 +1,1478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Image processor class for SAM."""
16
+
17
+ import math
18
+ from copy import deepcopy
19
+ from itertools import product
20
+ from typing import Any, Dict, List, Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+
24
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
25
+ from ...image_transforms import convert_to_rgb, pad, resize, to_channel_dimension_format
26
+ from ...image_utils import (
27
+ IMAGENET_DEFAULT_MEAN,
28
+ IMAGENET_DEFAULT_STD,
29
+ ChannelDimension,
30
+ ImageInput,
31
+ PILImageResampling,
32
+ get_image_size,
33
+ infer_channel_dimension_format,
34
+ is_scaled_image,
35
+ make_list_of_images,
36
+ to_numpy_array,
37
+ valid_images,
38
+ validate_preprocess_arguments,
39
+ )
40
+ from ...utils import (
41
+ TensorType,
42
+ filter_out_non_signature_kwargs,
43
+ is_tf_available,
44
+ is_torch_available,
45
+ is_torchvision_available,
46
+ logging,
47
+ requires_backends,
48
+ )
49
+
50
+
51
+ if is_torch_available():
52
+ import torch
53
+ import torch.nn.functional as F
54
+
55
+ if is_torchvision_available():
56
+ from torchvision.ops.boxes import batched_nms
57
+
58
+ if is_tf_available():
59
+ import tensorflow as tf
60
+ from tensorflow.experimental import numpy as tnp
61
+
62
+ from ...tf_utils import flatten, shape_list
63
+
64
+ logger = logging.get_logger(__name__)
65
+
66
+
67
+ class SamImageProcessor(BaseImageProcessor):
68
+ r"""
69
+ Constructs a SAM image processor.
70
+
71
+ Args:
72
+ do_resize (`bool`, *optional*, defaults to `True`):
73
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
74
+ `do_resize` parameter in the `preprocess` method.
75
+ size (`dict`, *optional*, defaults to `{"longest_edge": 1024}`):
76
+ Size of the output image after resizing. Resizes the longest edge of the image to match
77
+ `size["longest_edge"]` while maintaining the aspect ratio. Can be overridden by the `size` parameter in the
78
+ `preprocess` method.
79
+ mask_size (`dict`, *optional*, defaults to `{"longest_edge": 256}`):
80
+ Size of the output segmentation map after resizing. Resizes the longest edge of the image to match
81
+ `size["longest_edge"]` while maintaining the aspect ratio. Can be overridden by the `mask_size` parameter
82
+ in the `preprocess` method.
83
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
84
+ Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
85
+ `preprocess` method.
86
+ do_rescale (`bool`, *optional*, defaults to `True`):
87
+ Wwhether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
88
+ `do_rescale` parameter in the `preprocess` method.
89
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
90
+ Scale factor to use if rescaling the image. Only has an effect if `do_rescale` is set to `True`. Can be
91
+ overridden by the `rescale_factor` parameter in the `preprocess` method.
92
+ do_normalize (`bool`, *optional*, defaults to `True`):
93
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
94
+ method. Can be overridden by the `do_normalize` parameter in the `preprocess` method.
95
+ image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_MEAN`):
96
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
97
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be
98
+ overridden by the `image_mean` parameter in the `preprocess` method.
99
+ image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_STD`):
100
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
101
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
102
+ Can be overridden by the `image_std` parameter in the `preprocess` method.
103
+ do_pad (`bool`, *optional*, defaults to `True`):
104
+ Whether to pad the image to the specified `pad_size`. Can be overridden by the `do_pad` parameter in the
105
+ `preprocess` method.
106
+ pad_size (`dict`, *optional*, defaults to `{"height": 1024, "width": 1024}`):
107
+ Size of the output image after padding. Can be overridden by the `pad_size` parameter in the `preprocess`
108
+ method.
109
+ mask_pad_size (`dict`, *optional*, defaults to `{"height": 256, "width": 256}`):
110
+ Size of the output segmentation map after padding. Can be overridden by the `mask_pad_size` parameter in
111
+ the `preprocess` method.
112
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
113
+ Whether to convert the image to RGB.
114
+ """
115
+
116
+ model_input_names = ["pixel_values"]
117
+
118
+ def __init__(
119
+ self,
120
+ do_resize: bool = True,
121
+ size: Dict[str, int] = None,
122
+ mask_size: Dict[str, int] = None,
123
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
124
+ do_rescale: bool = True,
125
+ rescale_factor: Union[int, float] = 1 / 255,
126
+ do_normalize: bool = True,
127
+ image_mean: Optional[Union[float, List[float]]] = None,
128
+ image_std: Optional[Union[float, List[float]]] = None,
129
+ do_pad: bool = True,
130
+ pad_size: int = None,
131
+ mask_pad_size: int = None,
132
+ do_convert_rgb: bool = True,
133
+ **kwargs,
134
+ ) -> None:
135
+ super().__init__(**kwargs)
136
+ size = size if size is not None else {"longest_edge": 1024}
137
+ size = get_size_dict(max_size=size, default_to_square=False) if not isinstance(size, dict) else size
138
+
139
+ pad_size = pad_size if pad_size is not None else {"height": 1024, "width": 1024}
140
+ pad_size = get_size_dict(pad_size, default_to_square=True)
141
+
142
+ mask_size = mask_size if mask_size is not None else {"longest_edge": 256}
143
+ mask_size = (
144
+ get_size_dict(max_size=mask_size, default_to_square=False)
145
+ if not isinstance(mask_size, dict)
146
+ else mask_size
147
+ )
148
+
149
+ mask_pad_size = mask_pad_size if mask_pad_size is not None else {"height": 256, "width": 256}
150
+ mask_pad_size = get_size_dict(mask_pad_size, default_to_square=True)
151
+
152
+ self.do_resize = do_resize
153
+ self.size = size
154
+ self.mask_size = mask_size
155
+ self.resample = resample
156
+ self.do_rescale = do_rescale
157
+ self.rescale_factor = rescale_factor
158
+ self.do_normalize = do_normalize
159
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
160
+ self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
161
+ self.do_pad = do_pad
162
+ self.pad_size = pad_size
163
+ self.mask_pad_size = mask_pad_size
164
+ self.do_convert_rgb = do_convert_rgb
165
+
166
+ def pad_image(
167
+ self,
168
+ image: np.ndarray,
169
+ pad_size: Dict[str, int],
170
+ data_format: Optional[Union[str, ChannelDimension]] = None,
171
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
172
+ **kwargs,
173
+ ) -> np.ndarray:
174
+ """
175
+ Pad an image to `(pad_size["height"], pad_size["width"])` with zeros to the right and bottom.
176
+
177
+ Args:
178
+ image (`np.ndarray`):
179
+ Image to pad.
180
+ pad_size (`Dict[str, int]`):
181
+ Size of the output image after padding.
182
+ data_format (`str` or `ChannelDimension`, *optional*):
183
+ The data format of the image. Can be either "channels_first" or "channels_last". If `None`, the
184
+ `data_format` of the `image` will be used.
185
+ input_data_format (`str` or `ChannelDimension`, *optional*):
186
+ The channel dimension format of the input image. If not provided, it will be inferred.
187
+ """
188
+ output_height, output_width = pad_size["height"], pad_size["width"]
189
+ input_height, input_width = get_image_size(image, channel_dim=input_data_format)
190
+
191
+ pad_width = output_width - input_width
192
+ pad_height = output_height - input_height
193
+
194
+ padded_image = pad(
195
+ image,
196
+ ((0, pad_height), (0, pad_width)),
197
+ data_format=data_format,
198
+ input_data_format=input_data_format,
199
+ **kwargs,
200
+ )
201
+ return padded_image
202
+
203
+ def _get_preprocess_shape(self, old_shape: Tuple[int, int], longest_edge: int):
204
+ """
205
+ Compute the output size given input size and target long side length.
206
+ """
207
+ oldh, oldw = old_shape
208
+ scale = longest_edge * 1.0 / max(oldh, oldw)
209
+ newh, neww = oldh * scale, oldw * scale
210
+ newh = int(newh + 0.5)
211
+ neww = int(neww + 0.5)
212
+ return (newh, neww)
213
+
214
+ def resize(
215
+ self,
216
+ image: np.ndarray,
217
+ size: Dict[str, int],
218
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
219
+ data_format: Optional[Union[str, ChannelDimension]] = None,
220
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
221
+ **kwargs,
222
+ ) -> np.ndarray:
223
+ """
224
+ Resize an image to `(size["height"], size["width"])`.
225
+
226
+ Args:
227
+ image (`np.ndarray`):
228
+ Image to resize.
229
+ size (`Dict[str, int]`):
230
+ Dictionary in the format `{"longest_edge": int}` specifying the size of the output image. The longest
231
+ edge of the image will be resized to the specified size, while the other edge will be resized to
232
+ maintain the aspect ratio.
233
+ resample:
234
+ `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
235
+ data_format (`ChannelDimension` or `str`, *optional*):
236
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
237
+ image is used. Can be one of:
238
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
239
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
240
+ input_data_format (`ChannelDimension` or `str`, *optional*):
241
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
242
+ from the input image. Can be one of:
243
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
244
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
245
+
246
+ Returns:
247
+ `np.ndarray`: The resized image.
248
+ """
249
+ size = get_size_dict(size)
250
+ if "longest_edge" not in size:
251
+ raise ValueError(f"The `size` dictionary must contain the key `longest_edge`. Got {size.keys()}")
252
+ input_size = get_image_size(image, channel_dim=input_data_format)
253
+ output_height, output_width = self._get_preprocess_shape(input_size, size["longest_edge"])
254
+ return resize(
255
+ image,
256
+ size=(output_height, output_width),
257
+ resample=resample,
258
+ data_format=data_format,
259
+ input_data_format=input_data_format,
260
+ **kwargs,
261
+ )
262
+
263
+ def _preprocess(
264
+ self,
265
+ image: ImageInput,
266
+ do_resize: bool,
267
+ do_rescale: bool,
268
+ do_normalize: bool,
269
+ size: Optional[Dict[str, int]] = None,
270
+ resample: PILImageResampling = None,
271
+ rescale_factor: Optional[float] = None,
272
+ image_mean: Optional[Union[float, List[float]]] = None,
273
+ image_std: Optional[Union[float, List[float]]] = None,
274
+ do_pad: Optional[bool] = None,
275
+ pad_size: Optional[Dict[str, int]] = None,
276
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
277
+ ):
278
+ if do_resize:
279
+ image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
280
+ reshaped_input_size = get_image_size(image, channel_dim=input_data_format)
281
+
282
+ if do_rescale:
283
+ image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
284
+
285
+ if do_normalize:
286
+ image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
287
+
288
+ if do_pad:
289
+ image = self.pad_image(image=image, pad_size=pad_size, input_data_format=input_data_format)
290
+
291
+ return image, reshaped_input_size
292
+
293
+ def _preprocess_image(
294
+ self,
295
+ image: ImageInput,
296
+ do_resize: Optional[bool] = None,
297
+ size: Dict[str, int] = None,
298
+ resample: PILImageResampling = None,
299
+ do_rescale: bool = None,
300
+ rescale_factor: Optional[float] = None,
301
+ do_normalize: Optional[bool] = None,
302
+ image_mean: Optional[Union[float, List[float]]] = None,
303
+ image_std: Optional[Union[float, List[float]]] = None,
304
+ do_pad: Optional[bool] = None,
305
+ pad_size: Optional[Dict[str, int]] = None,
306
+ do_convert_rgb: Optional[bool] = None,
307
+ data_format: Optional[Union[str, ChannelDimension]] = None,
308
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
309
+ ) -> Tuple[np.ndarray, Tuple[int, int], Tuple[int, int]]:
310
+ image = to_numpy_array(image)
311
+
312
+ # PIL RGBA images are converted to RGB
313
+ if do_convert_rgb:
314
+ image = convert_to_rgb(image)
315
+
316
+ # All transformations expect numpy arrays.
317
+ image = to_numpy_array(image)
318
+
319
+ if do_rescale and is_scaled_image(image):
320
+ logger.warning_once(
321
+ "It looks like you are trying to rescale already rescaled images. If the input"
322
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
323
+ )
324
+
325
+ if input_data_format is None:
326
+ input_data_format = infer_channel_dimension_format(image)
327
+
328
+ original_size = get_image_size(image, channel_dim=input_data_format)
329
+
330
+ image, reshaped_input_size = self._preprocess(
331
+ image=image,
332
+ do_resize=do_resize,
333
+ size=size,
334
+ resample=resample,
335
+ do_rescale=do_rescale,
336
+ rescale_factor=rescale_factor,
337
+ do_normalize=do_normalize,
338
+ image_mean=image_mean,
339
+ image_std=image_std,
340
+ do_pad=do_pad,
341
+ pad_size=pad_size,
342
+ input_data_format=input_data_format,
343
+ )
344
+
345
+ if data_format is not None:
346
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
347
+
348
+ return image, original_size, reshaped_input_size
349
+
350
+ def _preprocess_mask(
351
+ self,
352
+ segmentation_map: ImageInput,
353
+ do_resize: Optional[bool] = None,
354
+ mask_size: Dict[str, int] = None,
355
+ do_pad: Optional[bool] = None,
356
+ mask_pad_size: Optional[Dict[str, int]] = None,
357
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
358
+ ) -> np.ndarray:
359
+ segmentation_map = to_numpy_array(segmentation_map)
360
+
361
+ # Add channel dimension if missing - needed for certain transformations
362
+ if segmentation_map.ndim == 2:
363
+ added_channel_dim = True
364
+ segmentation_map = segmentation_map[None, ...]
365
+ input_data_format = ChannelDimension.FIRST
366
+ else:
367
+ added_channel_dim = False
368
+ if input_data_format is None:
369
+ input_data_format = infer_channel_dimension_format(segmentation_map, num_channels=1)
370
+
371
+ original_size = get_image_size(segmentation_map, channel_dim=input_data_format)
372
+
373
+ segmentation_map, _ = self._preprocess(
374
+ image=segmentation_map,
375
+ do_resize=do_resize,
376
+ size=mask_size,
377
+ resample=PILImageResampling.NEAREST,
378
+ do_rescale=False,
379
+ do_normalize=False,
380
+ do_pad=do_pad,
381
+ pad_size=mask_pad_size,
382
+ input_data_format=input_data_format,
383
+ )
384
+
385
+ # Remove extra channel dimension if added for processing
386
+ if added_channel_dim:
387
+ segmentation_map = segmentation_map.squeeze(0)
388
+ segmentation_map = segmentation_map.astype(np.int64)
389
+
390
+ return segmentation_map, original_size
391
+
392
+ @filter_out_non_signature_kwargs()
393
+ def preprocess(
394
+ self,
395
+ images: ImageInput,
396
+ segmentation_maps: Optional[ImageInput] = None,
397
+ do_resize: Optional[bool] = None,
398
+ size: Optional[Dict[str, int]] = None,
399
+ mask_size: Optional[Dict[str, int]] = None,
400
+ resample: Optional["PILImageResampling"] = None,
401
+ do_rescale: Optional[bool] = None,
402
+ rescale_factor: Optional[Union[int, float]] = None,
403
+ do_normalize: Optional[bool] = None,
404
+ image_mean: Optional[Union[float, List[float]]] = None,
405
+ image_std: Optional[Union[float, List[float]]] = None,
406
+ do_pad: Optional[bool] = None,
407
+ pad_size: Optional[Dict[str, int]] = None,
408
+ mask_pad_size: Optional[Dict[str, int]] = None,
409
+ do_convert_rgb: Optional[bool] = None,
410
+ return_tensors: Optional[Union[str, TensorType]] = None,
411
+ data_format: ChannelDimension = ChannelDimension.FIRST,
412
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
413
+ ):
414
+ """
415
+ Preprocess an image or batch of images.
416
+
417
+ Args:
418
+ images (`ImageInput`):
419
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
420
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
421
+ segmentation_maps (`ImageInput`, *optional*):
422
+ Segmentation map to preprocess.
423
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
424
+ Whether to resize the image.
425
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
426
+ Controls the size of the image after `resize`. The longest edge of the image is resized to
427
+ `size["longest_edge"]` whilst preserving the aspect ratio.
428
+ mask_size (`Dict[str, int]`, *optional*, defaults to `self.mask_size`):
429
+ Controls the size of the segmentation map after `resize`. The longest edge of the image is resized to
430
+ `size["longest_edge"]` whilst preserving the aspect ratio.
431
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
432
+ `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
433
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
434
+ Whether to rescale the image pixel values by rescaling factor.
435
+ rescale_factor (`int` or `float`, *optional*, defaults to `self.rescale_factor`):
436
+ Rescale factor to apply to the image pixel values.
437
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
438
+ Whether to normalize the image.
439
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
440
+ Image mean to normalize the image by if `do_normalize` is set to `True`.
441
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
442
+ Image standard deviation to normalize the image by if `do_normalize` is set to `True`.
443
+ do_pad (`bool`, *optional*, defaults to `self.do_pad`):
444
+ Whether to pad the image.
445
+ pad_size (`Dict[str, int]`, *optional*, defaults to `self.pad_size`):
446
+ Controls the size of the padding applied to the image. The image is padded to `pad_size["height"]` and
447
+ `pad_size["width"]` if `do_pad` is set to `True`.
448
+ mask_pad_size (`Dict[str, int]`, *optional*, defaults to `self.mask_pad_size`):
449
+ Controls the size of the padding applied to the segmentation map. The image is padded to
450
+ `mask_pad_size["height"]` and `mask_pad_size["width"]` if `do_pad` is set to `True`.
451
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
452
+ Whether to convert the image to RGB.
453
+ return_tensors (`str` or `TensorType`, *optional*):
454
+ The type of tensors to return. Can be one of:
455
+ - Unset: Return a list of `np.ndarray`.
456
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
457
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
458
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
459
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
460
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
461
+ The channel dimension format for the output image. Can be one of:
462
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
463
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
464
+ - Unset: Use the channel dimension format of the input image.
465
+ input_data_format (`ChannelDimension` or `str`, *optional*):
466
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
467
+ from the input image. Can be one of:
468
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
469
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
470
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
471
+ """
472
+ do_resize = do_resize if do_resize is not None else self.do_resize
473
+ size = size if size is not None else self.size
474
+ size = get_size_dict(max_size=size, default_to_square=False) if not isinstance(size, dict) else size
475
+ mask_size = mask_size if mask_size is not None else self.mask_size
476
+ mask_size = (
477
+ get_size_dict(max_size=mask_size, default_to_square=False)
478
+ if not isinstance(mask_size, dict)
479
+ else mask_size
480
+ )
481
+ resample = resample if resample is not None else self.resample
482
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
483
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
484
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
485
+ image_mean = image_mean if image_mean is not None else self.image_mean
486
+ image_std = image_std if image_std is not None else self.image_std
487
+ do_pad = do_pad if do_pad is not None else self.do_pad
488
+ pad_size = pad_size if pad_size is not None else self.pad_size
489
+ pad_size = get_size_dict(pad_size, default_to_square=True)
490
+ mask_pad_size = mask_pad_size if mask_pad_size is not None else self.mask_pad_size
491
+ mask_pad_size = get_size_dict(mask_pad_size, default_to_square=True)
492
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
493
+
494
+ images = make_list_of_images(images)
495
+
496
+ if not valid_images(images):
497
+ raise ValueError(
498
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
499
+ "torch.Tensor, tf.Tensor or jax.ndarray."
500
+ )
501
+
502
+ if segmentation_maps is not None:
503
+ segmentation_maps = make_list_of_images(segmentation_maps, expected_ndims=2)
504
+
505
+ if not valid_images(segmentation_maps):
506
+ raise ValueError(
507
+ "Invalid segmentation map type. Must be of type PIL.Image.Image, numpy.ndarray, "
508
+ "torch.Tensor, tf.Tensor or jax.ndarray."
509
+ )
510
+ validate_preprocess_arguments(
511
+ do_rescale=do_rescale,
512
+ rescale_factor=rescale_factor,
513
+ do_normalize=do_normalize,
514
+ image_mean=image_mean,
515
+ image_std=image_std,
516
+ do_pad=do_pad,
517
+ size_divisibility=pad_size, # Here _preprocess needs do_pad and pad_size.
518
+ do_resize=do_resize,
519
+ size=size,
520
+ resample=resample,
521
+ )
522
+
523
+ images, original_sizes, reshaped_input_sizes = zip(
524
+ *(
525
+ self._preprocess_image(
526
+ image=img,
527
+ do_resize=do_resize,
528
+ size=size,
529
+ resample=resample,
530
+ do_rescale=do_rescale,
531
+ rescale_factor=rescale_factor,
532
+ do_normalize=do_normalize,
533
+ image_mean=image_mean,
534
+ image_std=image_std,
535
+ do_pad=do_pad,
536
+ pad_size=pad_size,
537
+ do_convert_rgb=do_convert_rgb,
538
+ data_format=data_format,
539
+ input_data_format=input_data_format,
540
+ )
541
+ for img in images
542
+ )
543
+ )
544
+
545
+ data = {
546
+ "pixel_values": images,
547
+ "original_sizes": original_sizes,
548
+ "reshaped_input_sizes": reshaped_input_sizes,
549
+ }
550
+
551
+ if segmentation_maps is not None:
552
+ segmentation_maps, original_mask_sizes = zip(
553
+ *(
554
+ self._preprocess_mask(
555
+ segmentation_map=mask,
556
+ do_resize=do_resize,
557
+ mask_size=mask_size,
558
+ do_pad=do_pad,
559
+ mask_pad_size=mask_pad_size,
560
+ input_data_format=input_data_format,
561
+ )
562
+ for mask in segmentation_maps
563
+ )
564
+ )
565
+
566
+ # masks should start out the same size as input images
567
+ assert all(
568
+ original_im_size == original_mask_size
569
+ for original_im_size, original_mask_size in zip(original_sizes, original_mask_sizes)
570
+ ), "Segmentation maps should be the same size as input images."
571
+
572
+ data["labels"] = segmentation_maps
573
+
574
+ return BatchFeature(data=data, tensor_type=return_tensors)
575
+
576
+ def post_process_masks(
577
+ self,
578
+ masks,
579
+ original_sizes,
580
+ reshaped_input_sizes,
581
+ mask_threshold=0.0,
582
+ binarize=True,
583
+ pad_size=None,
584
+ return_tensors="pt",
585
+ ):
586
+ """
587
+ Remove padding and upscale masks to the original image size.
588
+
589
+ Args:
590
+ masks (`Union[List[torch.Tensor], List[np.ndarray], List[tf.Tensor]]`):
591
+ Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
592
+ original_sizes (`Union[torch.Tensor, tf.Tensor, List[Tuple[int,int]]]`):
593
+ The original sizes of each image before it was resized to the model's expected input shape, in (height,
594
+ width) format.
595
+ reshaped_input_sizes (`Union[torch.Tensor, tf.Tensor, List[Tuple[int,int]]]`):
596
+ The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
597
+ mask_threshold (`float`, *optional*, defaults to 0.0):
598
+ The threshold to use for binarizing the masks.
599
+ binarize (`bool`, *optional*, defaults to `True`):
600
+ Whether to binarize the masks.
601
+ pad_size (`int`, *optional*, defaults to `self.pad_size`):
602
+ The target size the images were padded to before being passed to the model. If None, the target size is
603
+ assumed to be the processor's `pad_size`.
604
+ return_tensors (`str`, *optional*, defaults to `"pt"`):
605
+ If `"pt"`, return PyTorch tensors. If `"tf"`, return TensorFlow tensors.
606
+ Returns:
607
+ (`Union[torch.Tensor, tf.Tensor]`): Batched masks in batch_size, num_channels, height, width) format, where
608
+ (height, width) is given by original_size.
609
+ """
610
+ if return_tensors == "pt":
611
+ return self._post_process_masks_pt(
612
+ masks=masks,
613
+ original_sizes=original_sizes,
614
+ reshaped_input_sizes=reshaped_input_sizes,
615
+ mask_threshold=mask_threshold,
616
+ binarize=binarize,
617
+ pad_size=pad_size,
618
+ )
619
+ elif return_tensors == "tf":
620
+ return self._post_process_masks_tf(
621
+ masks=masks,
622
+ original_sizes=original_sizes,
623
+ reshaped_input_sizes=reshaped_input_sizes,
624
+ mask_threshold=mask_threshold,
625
+ binarize=binarize,
626
+ pad_size=pad_size,
627
+ )
628
+ else:
629
+ raise ValueError("return_tensors must be either 'pt' or 'tf'")
630
+
631
+ def _post_process_masks_pt(
632
+ self, masks, original_sizes, reshaped_input_sizes, mask_threshold=0.0, binarize=True, pad_size=None
633
+ ):
634
+ """
635
+ Remove padding and upscale masks to the original image size.
636
+
637
+ Args:
638
+ masks (`Union[List[torch.Tensor], List[np.ndarray]]`):
639
+ Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
640
+ original_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`):
641
+ The original sizes of each image before it was resized to the model's expected input shape, in (height,
642
+ width) format.
643
+ reshaped_input_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`):
644
+ The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
645
+ mask_threshold (`float`, *optional*, defaults to 0.0):
646
+ The threshold to use for binarizing the masks.
647
+ binarize (`bool`, *optional*, defaults to `True`):
648
+ Whether to binarize the masks.
649
+ pad_size (`int`, *optional*, defaults to `self.pad_size`):
650
+ The target size the images were padded to before being passed to the model. If None, the target size is
651
+ assumed to be the processor's `pad_size`.
652
+ Returns:
653
+ (`torch.Tensor`): Batched masks in batch_size, num_channels, height, width) format, where (height, width)
654
+ is given by original_size.
655
+ """
656
+ requires_backends(self, ["torch"])
657
+ pad_size = self.pad_size if pad_size is None else pad_size
658
+ target_image_size = (pad_size["height"], pad_size["width"])
659
+ if isinstance(original_sizes, (torch.Tensor, np.ndarray)):
660
+ original_sizes = original_sizes.tolist()
661
+ if isinstance(reshaped_input_sizes, (torch.Tensor, np.ndarray)):
662
+ reshaped_input_sizes = reshaped_input_sizes.tolist()
663
+ output_masks = []
664
+ for i, original_size in enumerate(original_sizes):
665
+ if isinstance(masks[i], np.ndarray):
666
+ masks[i] = torch.from_numpy(masks[i])
667
+ elif not isinstance(masks[i], torch.Tensor):
668
+ raise ValueError("Input masks should be a list of `torch.tensors` or a list of `np.ndarray`")
669
+ interpolated_mask = F.interpolate(masks[i], target_image_size, mode="bilinear", align_corners=False)
670
+ interpolated_mask = interpolated_mask[..., : reshaped_input_sizes[i][0], : reshaped_input_sizes[i][1]]
671
+ interpolated_mask = F.interpolate(interpolated_mask, original_size, mode="bilinear", align_corners=False)
672
+ if binarize:
673
+ interpolated_mask = interpolated_mask > mask_threshold
674
+ output_masks.append(interpolated_mask)
675
+
676
+ return output_masks
677
+
678
+ def _post_process_masks_tf(
679
+ self, masks, original_sizes, reshaped_input_sizes, mask_threshold=0.0, binarize=True, pad_size=None
680
+ ):
681
+ """
682
+ Remove padding and upscale masks to the original image size.
683
+
684
+ Args:
685
+ masks (`tf.Tensor`):
686
+ Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
687
+ original_sizes (`tf.Tensor`):
688
+ The original size of the images before resizing for input to the model, in (height, width) format.
689
+ reshaped_input_sizes (`tf.Tensor`):
690
+ The size of the image input to the model, in (height, width) format. Used to remove padding.
691
+ mask_threshold (`float`, *optional*, defaults to 0.0):
692
+ The threshold to use for binarizing the masks.
693
+ binarize (`bool`, *optional*, defaults to `True`):
694
+ Whether to binarize the masks.
695
+ pad_size (`int`, *optional*, defaults to `self.pad_size`):
696
+ The target size the images were padded to before being passed to the model. If None, the target size is
697
+ assumed to be the processor's `pad_size`.
698
+ Returns:
699
+ (`tf.Tensor`): Batched masks in batch_size, num_channels, height, width) format, where (height, width) is
700
+ given by original_size.
701
+ """
702
+ requires_backends(self, ["tf"])
703
+ pad_size = self.pad_size if pad_size is None else pad_size
704
+ target_image_size = (pad_size["height"], pad_size["width"])
705
+
706
+ output_masks = []
707
+ for i, original_size in enumerate(original_sizes):
708
+ # tf.image expects NHWC, we transpose the NCHW inputs for it
709
+ mask = tf.transpose(masks[i], perm=[0, 2, 3, 1])
710
+ interpolated_mask = tf.image.resize(mask, target_image_size, method="bilinear")
711
+ interpolated_mask = interpolated_mask[:, : reshaped_input_sizes[i][0], : reshaped_input_sizes[i][1], :]
712
+ interpolated_mask = tf.image.resize(interpolated_mask, original_size, method="bilinear")
713
+ if binarize:
714
+ interpolated_mask = interpolated_mask > mask_threshold
715
+ # And then we transpose them back at the end
716
+ output_masks.append(tf.transpose(interpolated_mask, perm=[0, 3, 1, 2]))
717
+
718
+ return output_masks
719
+
720
+ def post_process_for_mask_generation(
721
+ self, all_masks, all_scores, all_boxes, crops_nms_thresh, return_tensors="pt"
722
+ ):
723
+ """
724
+ Post processes mask that are generated by calling the Non Maximum Suppression algorithm on the predicted masks.
725
+
726
+ Args:
727
+ all_masks (`Union[List[torch.Tensor], List[tf.Tensor]]`):
728
+ List of all predicted segmentation masks
729
+ all_scores (`Union[List[torch.Tensor], List[tf.Tensor]]`):
730
+ List of all predicted iou scores
731
+ all_boxes (`Union[List[torch.Tensor], List[tf.Tensor]]`):
732
+ List of all bounding boxes of the predicted masks
733
+ crops_nms_thresh (`float`):
734
+ Threshold for NMS (Non Maximum Suppression) algorithm.
735
+ return_tensors (`str`, *optional*, defaults to `pt`):
736
+ If `pt`, returns `torch.Tensor`. If `tf`, returns `tf.Tensor`.
737
+ """
738
+ if return_tensors == "pt":
739
+ return _postprocess_for_mg(all_masks, all_scores, all_boxes, crops_nms_thresh)
740
+ elif return_tensors == "tf":
741
+ return _postprocess_for_mg_tf(all_masks, all_scores, all_boxes, crops_nms_thresh)
742
+
743
+ def generate_crop_boxes(
744
+ self,
745
+ image,
746
+ target_size,
747
+ crop_n_layers: int = 0,
748
+ overlap_ratio: float = 512 / 1500,
749
+ points_per_crop: Optional[int] = 32,
750
+ crop_n_points_downscale_factor: Optional[List[int]] = 1,
751
+ device: Optional["torch.device"] = None,
752
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
753
+ return_tensors: str = "pt",
754
+ ):
755
+ """
756
+ Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.
757
+
758
+ Args:
759
+ image (`np.array`):
760
+ Input original image
761
+ target_size (`int`):
762
+ Target size of the resized image
763
+ crop_n_layers (`int`, *optional*, defaults to 0):
764
+ If >0, mask prediction will be run again on crops of the image. Sets the number of layers to run, where
765
+ each layer has 2**i_layer number of image crops.
766
+ overlap_ratio (`float`, *optional*, defaults to 512/1500):
767
+ Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of
768
+ the image length. Later layers with more crops scale down this overlap.
769
+ points_per_crop (`int`, *optional*, defaults to 32):
770
+ Number of points to sample from each crop.
771
+ crop_n_points_downscale_factor (`List[int]`, *optional*, defaults to 1):
772
+ The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
773
+ device (`torch.device`, *optional*, defaults to None):
774
+ Device to use for the computation. If None, cpu will be used.
775
+ input_data_format (`str` or `ChannelDimension`, *optional*):
776
+ The channel dimension format of the input image. If not provided, it will be inferred.
777
+ return_tensors (`str`, *optional*, defaults to `pt`):
778
+ If `pt`, returns `torch.Tensor`. If `tf`, returns `tf.Tensor`.
779
+ """
780
+ crop_boxes, points_per_crop, cropped_images, input_labels = _generate_crop_boxes(
781
+ image,
782
+ target_size,
783
+ crop_n_layers,
784
+ overlap_ratio,
785
+ points_per_crop,
786
+ crop_n_points_downscale_factor,
787
+ input_data_format,
788
+ )
789
+ if return_tensors == "pt":
790
+ if device is None:
791
+ device = torch.device("cpu")
792
+ crop_boxes = torch.tensor(crop_boxes, device=device)
793
+ points_per_crop = torch.tensor(points_per_crop, device=device)
794
+ # cropped_images stays as np
795
+ input_labels = torch.tensor(input_labels, device=device)
796
+
797
+ elif return_tensors == "tf":
798
+ if device is not None:
799
+ raise ValueError("device is not a supported argument when return_tensors is tf!")
800
+ crop_boxes = tf.convert_to_tensor(crop_boxes)
801
+ points_per_crop = tf.convert_to_tensor(points_per_crop)
802
+ # cropped_images stays as np
803
+ input_labels = tf.convert_to_tensor(input_labels)
804
+ else:
805
+ raise ValueError("return_tensors must be either 'pt' or 'tf'.")
806
+ return crop_boxes, points_per_crop, cropped_images, input_labels
807
+
808
+ def filter_masks(
809
+ self,
810
+ masks,
811
+ iou_scores,
812
+ original_size,
813
+ cropped_box_image,
814
+ pred_iou_thresh=0.88,
815
+ stability_score_thresh=0.95,
816
+ mask_threshold=0,
817
+ stability_score_offset=1,
818
+ return_tensors="pt",
819
+ ):
820
+ """
821
+ Filters the predicted masks by selecting only the ones that meets several criteria. The first criterion being
822
+ that the iou scores needs to be greater than `pred_iou_thresh`. The second criterion is that the stability
823
+ score needs to be greater than `stability_score_thresh`. The method also converts the predicted masks to
824
+ bounding boxes and pad the predicted masks if necessary.
825
+
826
+ Args:
827
+ masks (`Union[torch.Tensor, tf.Tensor]`):
828
+ Input masks.
829
+ iou_scores (`Union[torch.Tensor, tf.Tensor]`):
830
+ List of IoU scores.
831
+ original_size (`Tuple[int,int]`):
832
+ Size of the orginal image.
833
+ cropped_box_image (`np.array`):
834
+ The cropped image.
835
+ pred_iou_thresh (`float`, *optional*, defaults to 0.88):
836
+ The threshold for the iou scores.
837
+ stability_score_thresh (`float`, *optional*, defaults to 0.95):
838
+ The threshold for the stability score.
839
+ mask_threshold (`float`, *optional*, defaults to 0):
840
+ The threshold for the predicted masks.
841
+ stability_score_offset (`float`, *optional*, defaults to 1):
842
+ The offset for the stability score used in the `_compute_stability_score` method.
843
+ return_tensors (`str`, *optional*, defaults to `pt`):
844
+ If `pt`, returns `torch.Tensor`. If `tf`, returns `tf.Tensor`.
845
+ """
846
+ if return_tensors == "pt":
847
+ return self._filter_masks_pt(
848
+ masks=masks,
849
+ iou_scores=iou_scores,
850
+ original_size=original_size,
851
+ cropped_box_image=cropped_box_image,
852
+ pred_iou_thresh=pred_iou_thresh,
853
+ stability_score_thresh=stability_score_thresh,
854
+ mask_threshold=mask_threshold,
855
+ stability_score_offset=stability_score_offset,
856
+ )
857
+ elif return_tensors == "tf":
858
+ return self._filter_masks_tf(
859
+ masks=masks,
860
+ iou_scores=iou_scores,
861
+ original_size=original_size,
862
+ cropped_box_image=cropped_box_image,
863
+ pred_iou_thresh=pred_iou_thresh,
864
+ stability_score_thresh=stability_score_thresh,
865
+ mask_threshold=mask_threshold,
866
+ stability_score_offset=stability_score_offset,
867
+ )
868
+
869
+ def _filter_masks_pt(
870
+ self,
871
+ masks,
872
+ iou_scores,
873
+ original_size,
874
+ cropped_box_image,
875
+ pred_iou_thresh=0.88,
876
+ stability_score_thresh=0.95,
877
+ mask_threshold=0,
878
+ stability_score_offset=1,
879
+ ):
880
+ """
881
+ Filters the predicted masks by selecting only the ones that meets several criteria. The first criterion being
882
+ that the iou scores needs to be greater than `pred_iou_thresh`. The second criterion is that the stability
883
+ score needs to be greater than `stability_score_thresh`. The method also converts the predicted masks to
884
+ bounding boxes and pad the predicted masks if necessary.
885
+
886
+ Args:
887
+ masks (`torch.Tensor`):
888
+ Input masks.
889
+ iou_scores (`torch.Tensor`):
890
+ List of IoU scores.
891
+ original_size (`Tuple[int,int]`):
892
+ Size of the orginal image.
893
+ cropped_box_image (`np.array`):
894
+ The cropped image.
895
+ pred_iou_thresh (`float`, *optional*, defaults to 0.88):
896
+ The threshold for the iou scores.
897
+ stability_score_thresh (`float`, *optional*, defaults to 0.95):
898
+ The threshold for the stability score.
899
+ mask_threshold (`float`, *optional*, defaults to 0):
900
+ The threshold for the predicted masks.
901
+ stability_score_offset (`float`, *optional*, defaults to 1):
902
+ The offset for the stability score used in the `_compute_stability_score` method.
903
+
904
+ """
905
+ requires_backends(self, ["torch"])
906
+ original_height, original_width = original_size
907
+ iou_scores = iou_scores.flatten(0, 1)
908
+ masks = masks.flatten(0, 1)
909
+
910
+ if masks.shape[0] != iou_scores.shape[0]:
911
+ raise ValueError("masks and iou_scores must have the same batch size.")
912
+
913
+ if masks.device != iou_scores.device:
914
+ iou_scores = iou_scores.to(masks.device)
915
+
916
+ batch_size = masks.shape[0]
917
+
918
+ keep_mask = torch.ones(batch_size, dtype=torch.bool, device=masks.device)
919
+
920
+ if pred_iou_thresh > 0.0:
921
+ keep_mask = keep_mask & (iou_scores > pred_iou_thresh)
922
+
923
+ # compute stability score
924
+ if stability_score_thresh > 0.0:
925
+ stability_scores = _compute_stability_score_pt(masks, mask_threshold, stability_score_offset)
926
+ keep_mask = keep_mask & (stability_scores > stability_score_thresh)
927
+
928
+ scores = iou_scores[keep_mask]
929
+ masks = masks[keep_mask]
930
+
931
+ # binarize masks
932
+ masks = masks > mask_threshold
933
+ converted_boxes = _batched_mask_to_box(masks)
934
+
935
+ keep_mask = ~_is_box_near_crop_edge(
936
+ converted_boxes, cropped_box_image, [0, 0, original_width, original_height]
937
+ )
938
+
939
+ scores = scores[keep_mask]
940
+ masks = masks[keep_mask]
941
+ converted_boxes = converted_boxes[keep_mask]
942
+
943
+ masks = _pad_masks(masks, cropped_box_image, original_height, original_width)
944
+ # conversion to rle is necessary to run non-maximum suppresion
945
+ masks = _mask_to_rle_pytorch(masks)
946
+
947
+ return masks, scores, converted_boxes
948
+
949
+ def _filter_masks_tf(
950
+ self,
951
+ masks,
952
+ iou_scores,
953
+ original_size,
954
+ cropped_box_image,
955
+ pred_iou_thresh=0.88,
956
+ stability_score_thresh=0.95,
957
+ mask_threshold=0,
958
+ stability_score_offset=1,
959
+ ):
960
+ """
961
+ Filters the predicted masks by selecting only the ones that meets several criteria. The first criterion being
962
+ that the iou scores needs to be greater than `pred_iou_thresh`. The second criterion is that the stability
963
+ score needs to be greater than `stability_score_thresh`. The method also converts the predicted masks to
964
+ bounding boxes and pad the predicted masks if necessary.
965
+
966
+ Args:
967
+ masks (`tf.Tensor`):
968
+ Input masks.
969
+ iou_scores (`tf.Tensor`):
970
+ List of IoU scores.
971
+ original_size (`Tuple[int,int]`):
972
+ Size of the orginal image.
973
+ cropped_box_image (`np.array`):
974
+ The cropped image.
975
+ pred_iou_thresh (`float`, *optional*, defaults to 0.88):
976
+ The threshold for the iou scores.
977
+ stability_score_thresh (`float`, *optional*, defaults to 0.95):
978
+ The threshold for the stability score.
979
+ mask_threshold (`float`, *optional*, defaults to 0):
980
+ The threshold for the predicted masks.
981
+ stability_score_offset (`float`, *optional*, defaults to 1):
982
+ The offset for the stability score used in the `_compute_stability_score` method.
983
+
984
+ """
985
+ requires_backends(self, ["tf"])
986
+ original_height, original_width = original_size
987
+ iou_scores = tf.reshape(iou_scores, [iou_scores.shape[0] * iou_scores.shape[1], iou_scores.shape[2:]])
988
+ masks = tf.reshape(masks, [masks.shape[0] * masks.shape[1], masks.shape[2:]])
989
+
990
+ if masks.shape[0] != iou_scores.shape[0]:
991
+ raise ValueError("masks and iou_scores must have the same batch size.")
992
+
993
+ batch_size = masks.shape[0]
994
+
995
+ keep_mask = tf.ones(batch_size, dtype=tf.bool)
996
+
997
+ if pred_iou_thresh > 0.0:
998
+ keep_mask = keep_mask & (iou_scores > pred_iou_thresh)
999
+
1000
+ # compute stability score
1001
+ if stability_score_thresh > 0.0:
1002
+ stability_scores = _compute_stability_score_tf(masks, mask_threshold, stability_score_offset)
1003
+ keep_mask = keep_mask & (stability_scores > stability_score_thresh)
1004
+
1005
+ scores = iou_scores[keep_mask]
1006
+ masks = masks[keep_mask]
1007
+
1008
+ # binarize masks
1009
+ masks = masks > mask_threshold
1010
+ converted_boxes = _batched_mask_to_box_tf(masks)
1011
+
1012
+ keep_mask = ~_is_box_near_crop_edge_tf(
1013
+ converted_boxes, cropped_box_image, [0, 0, original_width, original_height]
1014
+ )
1015
+
1016
+ scores = scores[keep_mask]
1017
+ masks = masks[keep_mask]
1018
+ converted_boxes = converted_boxes[keep_mask]
1019
+
1020
+ masks = _pad_masks_tf(masks, cropped_box_image, original_height, original_width)
1021
+ # conversion to rle is necessary to run non-maximum suppresion
1022
+ masks = _mask_to_rle_tf(masks)
1023
+
1024
+ return masks, scores, converted_boxes
1025
+
1026
+
1027
+ def _compute_stability_score_pt(masks: "torch.Tensor", mask_threshold: float, stability_score_offset: int):
1028
+ # One mask is always contained inside the other.
1029
+ # Save memory by preventing unnecesary cast to torch.int64
1030
+ intersections = (
1031
+ (masks > (mask_threshold + stability_score_offset)).sum(-1, dtype=torch.int16).sum(-1, dtype=torch.int32)
1032
+ )
1033
+ unions = (masks > (mask_threshold - stability_score_offset)).sum(-1, dtype=torch.int16).sum(-1, dtype=torch.int32)
1034
+ stability_scores = intersections / unions
1035
+ return stability_scores
1036
+
1037
+
1038
+ def _compute_stability_score_tf(masks: "tf.Tensor", mask_threshold: float, stability_score_offset: int):
1039
+ # Torch does Py3-style division but TF does floor division with ints. We cast to float32 in TF to make sure
1040
+ # we get the right division results.
1041
+ intersections = tf.count_nonzero(
1042
+ masks > (mask_threshold + stability_score_offset), axis=[-1, -2], dtype=tf.float32
1043
+ )
1044
+ unions = tf.count_nonzero(masks > (mask_threshold - stability_score_offset), axis=[-1, -2], dtype=tf.float32)
1045
+ stability_scores = intersections / unions
1046
+ return stability_scores
1047
+
1048
+
1049
+ def _build_point_grid(n_per_side: int) -> np.ndarray:
1050
+ """Generates a 2D grid of points evenly spaced in [0,1]x[0,1]."""
1051
+ offset = 1 / (2 * n_per_side)
1052
+ points_one_side = np.linspace(offset, 1 - offset, n_per_side)
1053
+ points_x = np.tile(points_one_side[None, :], (n_per_side, 1))
1054
+ points_y = np.tile(points_one_side[:, None], (1, n_per_side))
1055
+ points = np.stack([points_x, points_y], axis=-1).reshape(-1, 2)
1056
+ return points
1057
+
1058
+
1059
+ def _normalize_coordinates(
1060
+ target_size: int, coords: np.ndarray, original_size: Tuple[int, int], is_bounding_box=False
1061
+ ) -> np.ndarray:
1062
+ """
1063
+ Expects a numpy array of length 2 in the final dimension. Requires the original image size in (height, width)
1064
+ format.
1065
+ """
1066
+ old_height, old_width = original_size
1067
+
1068
+ scale = target_size * 1.0 / max(old_height, old_width)
1069
+ new_height, new_width = old_height * scale, old_width * scale
1070
+ new_width = int(new_width + 0.5)
1071
+ new_height = int(new_height + 0.5)
1072
+
1073
+ coords = deepcopy(coords).astype(float)
1074
+
1075
+ if is_bounding_box:
1076
+ coords = coords.reshape(-1, 2, 2)
1077
+
1078
+ coords[..., 0] = coords[..., 0] * (new_width / old_width)
1079
+ coords[..., 1] = coords[..., 1] * (new_height / old_height)
1080
+
1081
+ if is_bounding_box:
1082
+ coords = coords.reshape(-1, 4)
1083
+
1084
+ return coords
1085
+
1086
+
1087
+ def _generate_crop_boxes(
1088
+ image,
1089
+ target_size: int, # Is it tuple here?
1090
+ crop_n_layers: int = 0,
1091
+ overlap_ratio: float = 512 / 1500,
1092
+ points_per_crop: Optional[int] = 32,
1093
+ crop_n_points_downscale_factor: Optional[List[int]] = 1,
1094
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
1095
+ ) -> Tuple[List[List[int]], List[int]]:
1096
+ """
1097
+ Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.
1098
+
1099
+ Args:
1100
+ image (Union[`numpy.ndarray`, `PIL.Image`, `torch.Tensor`]):
1101
+ Image to generate crops for.
1102
+ target_size (`int`):
1103
+ Size of the smallest crop.
1104
+ crop_n_layers (`int`, *optional*):
1105
+ If `crops_n_layers>0`, mask prediction will be run again on crops of the image. Sets the number of layers
1106
+ to run, where each layer has 2**i_layer number of image crops.
1107
+ overlap_ratio (`int`, *optional*):
1108
+ Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the
1109
+ image length. Later layers with more crops scale down this overlap.
1110
+ points_per_crop (`int`, *optional*):
1111
+ Number of points to sample per crop.
1112
+ crop_n_points_downscale_factor (`int`, *optional*):
1113
+ The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
1114
+ input_data_format (`str` or `ChannelDimension`, *optional*):
1115
+ The channel dimension format of the input image. If not provided, it will be inferred.
1116
+ """
1117
+
1118
+ if isinstance(image, list):
1119
+ raise ValueError("Only one image is allowed for crop generation.")
1120
+ image = to_numpy_array(image)
1121
+ original_size = get_image_size(image, input_data_format)
1122
+
1123
+ points_grid = []
1124
+ for i in range(crop_n_layers + 1):
1125
+ n_points = int(points_per_crop / (crop_n_points_downscale_factor**i))
1126
+ points_grid.append(_build_point_grid(n_points))
1127
+
1128
+ crop_boxes, layer_idxs = _generate_per_layer_crops(crop_n_layers, overlap_ratio, original_size)
1129
+
1130
+ cropped_images, point_grid_per_crop = _generate_crop_images(
1131
+ crop_boxes, image, points_grid, layer_idxs, target_size, original_size, input_data_format
1132
+ )
1133
+ crop_boxes = np.array(crop_boxes)
1134
+ crop_boxes = crop_boxes.astype(np.float32)
1135
+ points_per_crop = np.array([point_grid_per_crop])
1136
+ points_per_crop = np.transpose(points_per_crop, axes=(0, 2, 1, 3))
1137
+
1138
+ input_labels = np.ones_like(points_per_crop[:, :, :, 0], dtype=np.int64)
1139
+
1140
+ return crop_boxes, points_per_crop, cropped_images, input_labels
1141
+
1142
+
1143
+ def _generate_per_layer_crops(crop_n_layers, overlap_ratio, original_size):
1144
+ """
1145
+ Generates 2 ** (layers idx + 1) crops for each crop_n_layers. Crops are in the XYWH format : The XYWH format
1146
+ consists of the following required indices:
1147
+ - X: X coordinate of the top left of the bounding box
1148
+ - Y: Y coordinate of the top left of the bounding box
1149
+ - W: width of the bounding box
1150
+ - H: height of the bounding box
1151
+ """
1152
+ crop_boxes, layer_idxs = [], []
1153
+ im_height, im_width = original_size
1154
+ short_side = min(im_height, im_width)
1155
+
1156
+ # Original image
1157
+ crop_boxes.append([0, 0, im_width, im_height])
1158
+ layer_idxs.append(0)
1159
+ for i_layer in range(crop_n_layers):
1160
+ n_crops_per_side = 2 ** (i_layer + 1)
1161
+ overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side))
1162
+
1163
+ crop_width = int(math.ceil((overlap * (n_crops_per_side - 1) + im_width) / n_crops_per_side))
1164
+ crop_height = int(math.ceil((overlap * (n_crops_per_side - 1) + im_height) / n_crops_per_side))
1165
+
1166
+ crop_box_x0 = [int((crop_width - overlap) * i) for i in range(n_crops_per_side)]
1167
+ crop_box_y0 = [int((crop_height - overlap) * i) for i in range(n_crops_per_side)]
1168
+
1169
+ for left, top in product(crop_box_x0, crop_box_y0):
1170
+ box = [left, top, min(left + crop_width, im_width), min(top + crop_height, im_height)]
1171
+ crop_boxes.append(box)
1172
+ layer_idxs.append(i_layer + 1)
1173
+
1174
+ return crop_boxes, layer_idxs
1175
+
1176
+
1177
+ def _generate_crop_images(
1178
+ crop_boxes, image, points_grid, layer_idxs, target_size, original_size, input_data_format=None
1179
+ ):
1180
+ """
1181
+ Takes as an input bounding boxes that are used to crop the image. Based in the crops, the corresponding points are
1182
+ also passed.
1183
+ """
1184
+ cropped_images = []
1185
+ total_points_per_crop = []
1186
+ for i, crop_box in enumerate(crop_boxes):
1187
+ left, top, right, bottom = crop_box
1188
+
1189
+ channel_dim = infer_channel_dimension_format(image, input_data_format)
1190
+ if channel_dim == ChannelDimension.LAST:
1191
+ cropped_im = image[top:bottom, left:right, :]
1192
+ else:
1193
+ cropped_im = image[:, top:bottom, left:right]
1194
+
1195
+ cropped_images.append(cropped_im)
1196
+
1197
+ cropped_im_size = get_image_size(cropped_im, channel_dim)
1198
+ points_scale = np.array(cropped_im_size)[None, ::-1]
1199
+
1200
+ points = points_grid[layer_idxs[i]] * points_scale
1201
+ normalized_points = _normalize_coordinates(target_size, points, original_size)
1202
+ total_points_per_crop.append(normalized_points)
1203
+
1204
+ return cropped_images, total_points_per_crop
1205
+
1206
+
1207
+ def _pad_masks(masks, crop_box: List[int], orig_height: int, orig_width: int):
1208
+ left, top, right, bottom = crop_box
1209
+ if left == 0 and top == 0 and right == orig_width and bottom == orig_height:
1210
+ return masks
1211
+ # Coordinate transform masks
1212
+ pad_x, pad_y = orig_width - (right - left), orig_height - (bottom - top)
1213
+ pad = (left, pad_x - left, top, pad_y - top)
1214
+ return torch.nn.functional.pad(masks, pad, value=0)
1215
+
1216
+
1217
+ def _pad_masks_tf(masks, crop_box: List[int], orig_height: int, orig_width: int):
1218
+ left, top, right, bottom = crop_box
1219
+ if left == 0 and top == 0 and right == orig_width and bottom == orig_height:
1220
+ return masks
1221
+ # Coordinate transform masks
1222
+ pad_x, pad_y = orig_width - (right - left), orig_height - (bottom - top)
1223
+ pad = (left, pad_x - left, top, pad_y - top)
1224
+ return tf.pad(masks, pad, constant_values=0)
1225
+
1226
+
1227
+ def _is_box_near_crop_edge(boxes, crop_box, orig_box, atol=20.0):
1228
+ """Filter masks at the edge of a crop, but not at the edge of the original image."""
1229
+ crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device)
1230
+ orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device)
1231
+
1232
+ left, top, _, _ = crop_box
1233
+ offset = torch.tensor([[left, top, left, top]], device=boxes.device)
1234
+ # Check if boxes has a channel dimension
1235
+ if len(boxes.shape) == 3:
1236
+ offset = offset.unsqueeze(1)
1237
+ boxes = (boxes + offset).float()
1238
+
1239
+ near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0)
1240
+ near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0)
1241
+ near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge)
1242
+ return torch.any(near_crop_edge, dim=1)
1243
+
1244
+
1245
+ def _is_box_near_crop_edge_tf(boxes, crop_box, orig_box, atol=20.0):
1246
+ """Filter masks at the edge of a crop, but not at the edge of the original image."""
1247
+ crop_box_tf = tf.convert_to_tensor(crop_box, dtype=tf.float32)
1248
+ orig_box_tf = tf.convert_to_tensor(orig_box, dtype=tf.float32)
1249
+
1250
+ left, top, _, _ = crop_box
1251
+ offset = tf.convert_to_tensor([[left, top, left, top]])
1252
+ # Check if boxes has a channel dimension
1253
+ if len(boxes.shape) == 3:
1254
+ offset = tf.expand_dims(offset, 1)
1255
+ boxes = tf.cast(boxes + offset, tf.float32)
1256
+
1257
+ near_crop_edge = tnp.isclose(boxes, crop_box_tf[None, :], atol=atol, rtol=0)
1258
+ near_image_edge = tnp.isclose(boxes, orig_box_tf[None, :], atol=atol, rtol=0)
1259
+ near_crop_edge = tf.math.logical_and(near_crop_edge, ~near_image_edge)
1260
+ return tf.reduce_any(near_crop_edge, axis=1)
1261
+
1262
+
1263
+ def _batched_mask_to_box(masks: "torch.Tensor"):
1264
+ """
1265
+ Computes the bounding boxes around the given input masks. The bounding boxes are in the XYXY format which
1266
+ corresponds the following required indices:
1267
+ - LEFT: left hand side of the bounding box
1268
+ - TOP: top of the bounding box
1269
+ - RIGHT: right of the bounding box
1270
+ - BOTTOM: bottom of the bounding box
1271
+
1272
+ Return [0,0,0,0] for an empty mask. For input shape channel_1 x channel_2 x ... x height x width, the output shape
1273
+ is channel_1 x channel_2 x ... x 4.
1274
+
1275
+ Args:
1276
+ - masks (`torch.Tensor` of shape `(batch, nb_mask, height, width)`)
1277
+ """
1278
+ # torch.max below raises an error on empty inputs, just skip in this case
1279
+
1280
+ if torch.numel(masks) == 0:
1281
+ return torch.zeros(*masks.shape[:-2], 4, device=masks.device)
1282
+
1283
+ # Normalize shape to Cxheightxwidth
1284
+ shape = masks.shape
1285
+ height, width = shape[-2:]
1286
+
1287
+ # Get top and bottom edges
1288
+ in_height, _ = torch.max(masks, dim=-1)
1289
+ in_height_coords = in_height * torch.arange(height, device=in_height.device)[None, :]
1290
+ bottom_edges, _ = torch.max(in_height_coords, dim=-1)
1291
+ in_height_coords = in_height_coords + height * (~in_height)
1292
+ top_edges, _ = torch.min(in_height_coords, dim=-1)
1293
+
1294
+ # Get left and right edges
1295
+ in_width, _ = torch.max(masks, dim=-2)
1296
+ in_width_coords = in_width * torch.arange(width, device=in_width.device)[None, :]
1297
+ right_edges, _ = torch.max(in_width_coords, dim=-1)
1298
+ in_width_coords = in_width_coords + width * (~in_width)
1299
+ left_edges, _ = torch.min(in_width_coords, dim=-1)
1300
+
1301
+ # If the mask is empty the right edge will be to the left of the left edge.
1302
+ # Replace these boxes with [0, 0, 0, 0]
1303
+ empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges)
1304
+ out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1)
1305
+ out = out * (~empty_filter).unsqueeze(-1)
1306
+
1307
+ # Return to original shape
1308
+ out = out.reshape(*shape[:-2], 4)
1309
+ return out
1310
+
1311
+
1312
+ def _batched_mask_to_box_tf(masks: "tf.Tensor"):
1313
+ """
1314
+ Computes the bounding boxes around the given input masks. The bounding boxes are in the XYXY format which
1315
+ corresponds the following required indices:
1316
+ - LEFT: left hand side of the bounding box
1317
+ - TOP: top of the bounding box
1318
+ - RIGHT: right of the bounding box
1319
+ - BOTTOM: bottom of the bounding box
1320
+
1321
+ Return [0,0,0,0] for an empty mask. For input shape channel_1 x channel_2 x ... x height x width, the output shape
1322
+ is channel_1 x channel_2 x ... x 4.
1323
+
1324
+ Args:
1325
+ - masks (`tf.Tensor` of shape `(batch, nb_mask, height, width)`)
1326
+ """
1327
+
1328
+ if tf.size(masks) == 0:
1329
+ return tf.zeros([*masks.shape[:-2], 4])
1330
+
1331
+ # Normalize shape to Cxheightxwidth
1332
+ shape = shape_list(masks)
1333
+ height, width = shape[-2:]
1334
+
1335
+ # Get top and bottom edges
1336
+ in_height = tf.reduce_max(masks, axis=-1)
1337
+ in_height_coords = in_height * tf.range(height)[None, :]
1338
+ bottom_edges = tf.reduce_max(in_height_coords, axis=-1)
1339
+ in_height_coords = in_height_coords + height * (~in_height)
1340
+ top_edges = tf.reduce_min(in_height_coords, axis=-1)
1341
+
1342
+ # Get left and right edges
1343
+ in_width, _ = tf.reduce_max(masks, axis=-2)
1344
+ in_width_coords = in_width * tf.range(width)[None, :]
1345
+ right_edges, _ = tf.reduce_max(in_width_coords, axis=-1)
1346
+ in_width_coords = in_width_coords + width * (~in_width)
1347
+ left_edges, _ = tf.reduce_min(in_width_coords, axis=-1)
1348
+
1349
+ # If the mask is empty the right edge will be to the left of the left edge.
1350
+ # Replace these boxes with [0, 0, 0, 0]
1351
+ empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges)
1352
+ out = tf.stack([left_edges, top_edges, right_edges, bottom_edges], axis=-1)
1353
+ out = out * tf.expand_dims(~empty_filter, -1)
1354
+
1355
+ # Return to original shape
1356
+ out = tf.reshape(out, *shape[:-2], 4)
1357
+ return out
1358
+
1359
+
1360
+ def _mask_to_rle_pytorch(input_mask: "torch.Tensor"):
1361
+ """
1362
+ Encodes masks the run-length encoding (RLE), in the format expected by pycoco tools.
1363
+ """
1364
+ # Put in fortran order and flatten height and width
1365
+ batch_size, height, width = input_mask.shape
1366
+ input_mask = input_mask.permute(0, 2, 1).flatten(1)
1367
+
1368
+ # Compute change indices
1369
+ diff = input_mask[:, 1:] ^ input_mask[:, :-1]
1370
+ change_indices = diff.nonzero()
1371
+
1372
+ # Encode run length
1373
+ out = []
1374
+ for i in range(batch_size):
1375
+ cur_idxs = change_indices[change_indices[:, 0] == i, 1] + 1
1376
+ btw_idxs = cur_idxs[1:] - cur_idxs[:-1]
1377
+ counts = [] if input_mask[i, 0] == 0 else [0]
1378
+ counts += [cur_idxs[0].item()] + btw_idxs.tolist() + [height * width - cur_idxs[-1]]
1379
+ out.append({"size": [height, width], "counts": counts})
1380
+ return out
1381
+
1382
+
1383
+ def _mask_to_rle_tf(input_mask: "tf.Tensor"):
1384
+ """
1385
+ Encodes masks the run-length encoding (RLE), in the format expected by pycoco tools.
1386
+ """
1387
+ # Put in fortran order and flatten height and width
1388
+ batch_size, height, width = input_mask.shape
1389
+ input_mask = flatten(tf.transpose(input_mask, perm=(0, 2, 1)), 1)
1390
+
1391
+ # Compute change indices
1392
+ diff = input_mask[:, 1:] ^ input_mask[:, :-1]
1393
+ change_indices = tf.where(diff)
1394
+
1395
+ # Encode run length
1396
+ out = []
1397
+ for i in range(batch_size):
1398
+ cur_idxs = change_indices[change_indices[:, 0] == i, 1] + 1
1399
+ btw_idxs = cur_idxs[1:] - cur_idxs[:-1]
1400
+ counts = [] if input_mask[i, 0] == 0 else [0]
1401
+ counts += [cur_idxs[0].item()] + btw_idxs.tolist() + [height * width - cur_idxs[-1]]
1402
+ out.append({"size": [height, width], "counts": counts})
1403
+ return out
1404
+
1405
+
1406
+ def _rle_to_mask(rle: Dict[str, Any]) -> np.ndarray:
1407
+ """Compute a binary mask from an uncompressed RLE."""
1408
+ height, width = rle["size"]
1409
+ mask = np.empty(height * width, dtype=bool)
1410
+ idx = 0
1411
+ parity = False
1412
+ for count in rle["counts"]:
1413
+ mask[idx : idx + count] = parity
1414
+ idx += count
1415
+ parity = not parity
1416
+ mask = mask.reshape(width, height)
1417
+ return mask.transpose() # Reshape to original shape
1418
+
1419
+
1420
+ def _postprocess_for_mg(rle_masks, iou_scores, mask_boxes, amg_crops_nms_thresh=0.7):
1421
+ """
1422
+ Perform NMS (Non Maximum Suppression) on the outputs.
1423
+
1424
+ Args:
1425
+ rle_masks (`torch.Tensor`):
1426
+ binary masks in the RLE format
1427
+ iou_scores (`torch.Tensor` of shape (nb_masks, 1)):
1428
+ iou_scores predicted by the model
1429
+ mask_boxes (`torch.Tensor`):
1430
+ The bounding boxes corresponding to segmentation masks
1431
+ amg_crops_nms_thresh (`float`, *optional*, defaults to 0.7):
1432
+ NMS threshold.
1433
+ """
1434
+ keep_by_nms = batched_nms(
1435
+ boxes=mask_boxes.float(),
1436
+ scores=iou_scores,
1437
+ idxs=torch.zeros(mask_boxes.shape[0]),
1438
+ iou_threshold=amg_crops_nms_thresh,
1439
+ )
1440
+
1441
+ iou_scores = iou_scores[keep_by_nms]
1442
+ rle_masks = [rle_masks[i] for i in keep_by_nms]
1443
+ mask_boxes = mask_boxes[keep_by_nms]
1444
+ masks = [_rle_to_mask(rle) for rle in rle_masks]
1445
+
1446
+ return masks, iou_scores, rle_masks, mask_boxes
1447
+
1448
+
1449
+ def _postprocess_for_mg_tf(rle_masks, iou_scores, mask_boxes, amg_crops_nms_thresh=0.7):
1450
+ """
1451
+ Perform NMS (Non Maximum Suppression) on the outputs.
1452
+
1453
+ Args:
1454
+ rle_masks (`tf.Tensor`):
1455
+ binary masks in the RLE format
1456
+ iou_scores (`tf.Tensor` of shape (nb_masks, 1)):
1457
+ iou_scores predicted by the model
1458
+ mask_boxes (`tf.Tensor`):
1459
+ The bounding boxes corresponding to segmentation masks
1460
+ amg_crops_nms_thresh (`float`, *optional*, defaults to 0.7):
1461
+ NMS threshold.
1462
+ """
1463
+ keep_by_nms = tf.image.combined_non_max_suppression(
1464
+ boxes=mask_boxes.float(),
1465
+ scores=iou_scores,
1466
+ idxs=torch.zeros(mask_boxes.shape[0]),
1467
+ iou_threshold=amg_crops_nms_thresh,
1468
+ )
1469
+
1470
+ iou_scores = iou_scores[keep_by_nms]
1471
+ rle_masks = [rle_masks[i] for i in keep_by_nms]
1472
+ mask_boxes = mask_boxes[keep_by_nms]
1473
+ masks = [_rle_to_mask(rle) for rle in rle_masks]
1474
+
1475
+ return masks, iou_scores, rle_masks, mask_boxes
1476
+
1477
+
1478
+ __all__ = ["SamImageProcessor"]