Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- llava_next/lib/python3.10/site-packages/rich/__pycache__/_emoji_codes.cpython-310.pyc +3 -0
- llava_next/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/configuration_bloom.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/modeling_bloom.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/modeling_flax_bloom.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/tokenization_bloom_fast.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/transformers/models/bloom/configuration_bloom.py +242 -0
- llava_next/lib/python3.10/site-packages/transformers/models/bloom/convert_bloom_original_checkpoint_to_pytorch.py +255 -0
- llava_next/lib/python3.10/site-packages/transformers/models/bloom/tokenization_bloom_fast.py +177 -0
- llava_next/lib/python3.10/site-packages/transformers/models/cpmant/__init__.py +64 -0
- llava_next/lib/python3.10/site-packages/transformers/models/cpmant/__pycache__/configuration_cpmant.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/transformers/models/cpmant/__pycache__/modeling_cpmant.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/transformers/models/cpmant/__pycache__/tokenization_cpmant.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/transformers/models/cpmant/tokenization_cpmant.py +278 -0
- llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/__init__.py +75 -0
- llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/convert_deformable_detr_to_pytorch.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/feature_extraction_deformable_detr.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/image_processing_deformable_detr.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/configuration_deformable_detr.py +263 -0
- llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/feature_extraction_deformable_detr.py +43 -0
- llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/image_processing_deformable_detr.py +1429 -0
- llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/load_custom.py +49 -0
- llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/modeling_deformable_detr.py +0 -0
- llava_next/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/__init__.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/configuration_mobilenet_v2.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/convert_original_tf_checkpoint_to_pytorch.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/transformers/models/mobilenet_v2/feature_extraction_mobilenet_v2.py +33 -0
- llava_next/lib/python3.10/site-packages/transformers/models/rembert/__pycache__/modeling_rembert.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/transformers/models/xglm/__init__.py +138 -0
- llava_next/lib/python3.10/site-packages/transformers/models/xglm/configuration_xglm.py +141 -0
- llava_next/lib/python3.10/site-packages/transformers/models/xglm/convert_xglm_original_ckpt_to_trfms.py +68 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/cpm/__pycache__/__init__.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/cpm/tokenization_cpm.py +348 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/cpm/tokenization_cpm_fast.py +241 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/__init__.py +28 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/__pycache__/__init__.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/__pycache__/configuration_longt5.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/__pycache__/convert_longt5x_checkpoint_to_flax.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/__pycache__/modeling_flax_longt5.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/__pycache__/modeling_longt5.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/configuration_longt5.py +180 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/convert_longt5x_checkpoint_to_flax.py +215 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/modeling_flax_longt5.py +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/modeling_longt5.py +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/mt5/__init__.py +30 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/mt5/__pycache__/__init__.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/mt5/__pycache__/configuration_mt5.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/mt5/__pycache__/modeling_flax_mt5.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/mt5/__pycache__/modeling_mt5.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/mt5/__pycache__/modeling_tf_mt5.cpython-310.pyc +0 -0
.gitattributes
CHANGED
|
@@ -1162,3 +1162,4 @@ vlmpy310/lib/python3.10/site-packages/tokenizers/tokenizers.abi3.so filter=lfs d
|
|
| 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
|
|
|
|
|
|
| 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
|
| 1165 |
+
llava_next/lib/python3.10/site-packages/rich/__pycache__/_emoji_codes.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
llava_next/lib/python3.10/site-packages/rich/__pycache__/_emoji_codes.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:16bd89a08208feb8b84a13c0b42807214b18e854b07ae0350b47170185b22d87
|
| 3 |
+
size 360026
|
llava_next/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/configuration_bloom.cpython-310.pyc
ADDED
|
Binary file (9.29 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/modeling_bloom.cpython-310.pyc
ADDED
|
Binary file (35.5 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/modeling_flax_bloom.cpython-310.pyc
ADDED
|
Binary file (21.2 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/tokenization_bloom_fast.cpython-310.pyc
ADDED
|
Binary file (6.44 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/transformers/models/bloom/configuration_bloom.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 the Big Science Workshop and 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 |
+
""" Bloom configuration"""
|
| 16 |
+
from collections import OrderedDict
|
| 17 |
+
from typing import TYPE_CHECKING, Any, List, Mapping, Optional
|
| 18 |
+
|
| 19 |
+
from packaging import version
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from ... import PreTrainedTokenizer, TensorType
|
| 24 |
+
|
| 25 |
+
from ...configuration_utils import PretrainedConfig
|
| 26 |
+
from ...onnx import OnnxConfigWithPast, PatchingSpec
|
| 27 |
+
from ...utils import is_torch_available, logging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
| 33 |
+
"bigscience/bloom": "https://huggingface.co/bigscience/bloom/resolve/main/config.json",
|
| 34 |
+
"bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/config.json",
|
| 35 |
+
"bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json",
|
| 36 |
+
"bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json",
|
| 37 |
+
"bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/config.json",
|
| 38 |
+
"bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json",
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class BloomConfig(PretrainedConfig):
|
| 43 |
+
"""
|
| 44 |
+
This is the configuration class to store the configuration of a [`BloomModel`]. It is used to instantiate a Bloom
|
| 45 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 46 |
+
defaults will yield a similar configuration to the Bloom architecture
|
| 47 |
+
[bigscience/bloom](https://huggingface.co/bigscience/bloom).
|
| 48 |
+
|
| 49 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 50 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
vocab_size (`int`, *optional*, defaults to 250880):
|
| 55 |
+
Vocabulary size of the Bloom model. Defines the maximum number of different tokens that can be represented
|
| 56 |
+
by the `inputs_ids` passed when calling [`BloomModel`]. Check [this
|
| 57 |
+
discussion](https://huggingface.co/bigscience/bloom/discussions/120#633d28389addb8530b406c2a) on how the
|
| 58 |
+
`vocab_size` has been defined.
|
| 59 |
+
hidden_size (`int`, *optional*, defaults to 64):
|
| 60 |
+
Dimensionality of the embeddings and hidden states.
|
| 61 |
+
n_layer (`int`, *optional*, defaults to 2):
|
| 62 |
+
Number of hidden layers in the Transformer encoder.
|
| 63 |
+
n_head (`int`, *optional*, defaults to 8):
|
| 64 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 65 |
+
layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
|
| 66 |
+
The epsilon to use in the layer normalization layers.
|
| 67 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 68 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 69 |
+
apply_residual_connection_post_layernorm (`bool`, *optional*, defaults to `False`):
|
| 70 |
+
If enabled, use the layer norm of the hidden states as the residual in the transformer blocks
|
| 71 |
+
hidden_dropout (`float`, *optional*, defaults to 0.1):
|
| 72 |
+
Dropout rate of the dropout function on the bias dropout.
|
| 73 |
+
attention_dropout (`float`, *optional*, defaults to 0.1):
|
| 74 |
+
Dropout rate applied to the attention probs
|
| 75 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 76 |
+
Whether or not the model should return the last key/values attentions (not used by all models).
|
| 77 |
+
pretraining_tp (`int`, *optional*, defaults to `1`):
|
| 78 |
+
Experimental feature. Tensor parallelism rank used during pretraining with Megatron. Please refer to [this
|
| 79 |
+
document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
|
| 80 |
+
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
| 81 |
+
issue](https://github.com/pytorch/pytorch/issues/76232). Note also that this is enabled only when
|
| 82 |
+
`slow_but_exact=True`.
|
| 83 |
+
slow_but_exact (`bool`, *optional*, defaults to `False`):
|
| 84 |
+
Experimental feature. Whether to use slow but exact implementation of the attention mechanism. While
|
| 85 |
+
merging the TP rank tensors, due to slicing operations the results may be slightly different between the
|
| 86 |
+
model trained on Megatron and our model. Please refer to [this
|
| 87 |
+
issue](https://github.com/pytorch/pytorch/issues/76232). A solution to obtain more accurate results is to
|
| 88 |
+
enable this feature. Enabling this will hurt the computational time of the inference. Will be probably
|
| 89 |
+
resolved in the future once the main model has been fine-tuned with TP_rank=1.
|
| 90 |
+
|
| 91 |
+
Example:
|
| 92 |
+
|
| 93 |
+
```python
|
| 94 |
+
>>> from transformers import BloomConfig, BloomModel
|
| 95 |
+
|
| 96 |
+
>>> # Initializing a Bloom configuration
|
| 97 |
+
>>> configuration = BloomConfig()
|
| 98 |
+
|
| 99 |
+
>>> # Initializing a model (with random weights) from the configuration
|
| 100 |
+
>>> model = BloomModel(configuration)
|
| 101 |
+
|
| 102 |
+
>>> # Accessing the model configuration
|
| 103 |
+
>>> configuration = model.config
|
| 104 |
+
```"""
|
| 105 |
+
|
| 106 |
+
model_type = "bloom"
|
| 107 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 108 |
+
attribute_map = {
|
| 109 |
+
"num_hidden_layers": "n_layer",
|
| 110 |
+
"num_attention_heads": "n_head",
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
def __init__(
|
| 114 |
+
self,
|
| 115 |
+
vocab_size=250880,
|
| 116 |
+
hidden_size=64,
|
| 117 |
+
n_layer=2,
|
| 118 |
+
n_head=8,
|
| 119 |
+
layer_norm_epsilon=1e-5,
|
| 120 |
+
initializer_range=0.02,
|
| 121 |
+
use_cache=True,
|
| 122 |
+
bos_token_id=1,
|
| 123 |
+
eos_token_id=2,
|
| 124 |
+
apply_residual_connection_post_layernorm=False,
|
| 125 |
+
hidden_dropout=0.0,
|
| 126 |
+
attention_dropout=0.0,
|
| 127 |
+
pretraining_tp=1, # TP rank used when training with megatron
|
| 128 |
+
slow_but_exact=False,
|
| 129 |
+
**kwargs,
|
| 130 |
+
):
|
| 131 |
+
self.vocab_size = vocab_size
|
| 132 |
+
# Backward compatibility with n_embed kwarg
|
| 133 |
+
n_embed = kwargs.pop("n_embed", None)
|
| 134 |
+
self.hidden_size = hidden_size if n_embed is None else n_embed
|
| 135 |
+
self.n_layer = n_layer
|
| 136 |
+
self.n_head = n_head
|
| 137 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
| 138 |
+
self.initializer_range = initializer_range
|
| 139 |
+
self.use_cache = use_cache
|
| 140 |
+
self.pretraining_tp = pretraining_tp
|
| 141 |
+
self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
|
| 142 |
+
self.hidden_dropout = hidden_dropout
|
| 143 |
+
self.attention_dropout = attention_dropout
|
| 144 |
+
|
| 145 |
+
self.bos_token_id = bos_token_id
|
| 146 |
+
self.eos_token_id = eos_token_id
|
| 147 |
+
self.slow_but_exact = slow_but_exact
|
| 148 |
+
|
| 149 |
+
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class BloomOnnxConfig(OnnxConfigWithPast):
|
| 153 |
+
torch_onnx_minimum_version = version.parse("1.12")
|
| 154 |
+
|
| 155 |
+
def __init__(
|
| 156 |
+
self,
|
| 157 |
+
config: PretrainedConfig,
|
| 158 |
+
task: str = "default",
|
| 159 |
+
patching_specs: List[PatchingSpec] = None,
|
| 160 |
+
use_past: bool = False,
|
| 161 |
+
):
|
| 162 |
+
super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)
|
| 163 |
+
if not getattr(self._config, "pad_token_id", None):
|
| 164 |
+
# TODO: how to do that better?
|
| 165 |
+
self._config.pad_token_id = 0
|
| 166 |
+
|
| 167 |
+
@property
|
| 168 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 169 |
+
common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
|
| 170 |
+
if self.use_past:
|
| 171 |
+
# BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
|
| 172 |
+
self.fill_with_past_key_values_(common_inputs, direction="inputs", inverted_values_shape=True)
|
| 173 |
+
common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
|
| 174 |
+
else:
|
| 175 |
+
common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}
|
| 176 |
+
|
| 177 |
+
return common_inputs
|
| 178 |
+
|
| 179 |
+
@property
|
| 180 |
+
def num_layers(self) -> int:
|
| 181 |
+
return self._config.n_layer
|
| 182 |
+
|
| 183 |
+
@property
|
| 184 |
+
def num_attention_heads(self) -> int:
|
| 185 |
+
return self._config.n_head
|
| 186 |
+
|
| 187 |
+
@property
|
| 188 |
+
def atol_for_validation(self) -> float:
|
| 189 |
+
return 1e-3
|
| 190 |
+
|
| 191 |
+
def generate_dummy_inputs(
|
| 192 |
+
self,
|
| 193 |
+
tokenizer: "PreTrainedTokenizer",
|
| 194 |
+
batch_size: int = -1,
|
| 195 |
+
seq_length: int = -1,
|
| 196 |
+
is_pair: bool = False,
|
| 197 |
+
framework: Optional["TensorType"] = None,
|
| 198 |
+
) -> Mapping[str, Any]:
|
| 199 |
+
common_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs(
|
| 200 |
+
tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
# We need to order the input in the way they appears in the forward()
|
| 204 |
+
ordered_inputs = OrderedDict({"input_ids": common_inputs["input_ids"]})
|
| 205 |
+
|
| 206 |
+
# Need to add the past_keys
|
| 207 |
+
if self.use_past:
|
| 208 |
+
if not is_torch_available():
|
| 209 |
+
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
|
| 210 |
+
else:
|
| 211 |
+
import torch
|
| 212 |
+
|
| 213 |
+
batch, seqlen = common_inputs["input_ids"].shape
|
| 214 |
+
# Not using the same length for past_key_values
|
| 215 |
+
past_key_values_length = seqlen + 2
|
| 216 |
+
head_dim = self._config.hidden_size // self.num_attention_heads
|
| 217 |
+
past_key_shape = (
|
| 218 |
+
batch * self.num_attention_heads,
|
| 219 |
+
head_dim,
|
| 220 |
+
past_key_values_length,
|
| 221 |
+
)
|
| 222 |
+
past_value_shape = (
|
| 223 |
+
batch * self.num_attention_heads,
|
| 224 |
+
past_key_values_length,
|
| 225 |
+
head_dim,
|
| 226 |
+
)
|
| 227 |
+
ordered_inputs["past_key_values"] = [
|
| 228 |
+
(torch.zeros(past_key_shape), torch.zeros(past_value_shape)) for _ in range(self.num_layers)
|
| 229 |
+
]
|
| 230 |
+
|
| 231 |
+
ordered_inputs["attention_mask"] = common_inputs["attention_mask"]
|
| 232 |
+
if self.use_past:
|
| 233 |
+
mask_dtype = ordered_inputs["attention_mask"].dtype
|
| 234 |
+
ordered_inputs["attention_mask"] = torch.cat(
|
| 235 |
+
[ordered_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
return ordered_inputs
|
| 239 |
+
|
| 240 |
+
@property
|
| 241 |
+
def default_onnx_opset(self) -> int:
|
| 242 |
+
return 13
|
llava_next/lib/python3.10/site-packages/transformers/models/bloom/convert_bloom_original_checkpoint_to_pytorch.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 BigScience BLOOM checkpoint."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
import re
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
|
| 25 |
+
from transformers import BloomConfig, BloomModel
|
| 26 |
+
from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME
|
| 27 |
+
from transformers.utils import logging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logging.set_verbosity_info()
|
| 31 |
+
|
| 32 |
+
WEIGHTS_TO_AVERAGE_ENDSWITH = [
|
| 33 |
+
"word_embeddings_layernorm.weight",
|
| 34 |
+
"word_embeddings_layernorm.bias",
|
| 35 |
+
"input_layernorm.weight",
|
| 36 |
+
"input_layernorm.bias",
|
| 37 |
+
"post_attention_layernorm.weight",
|
| 38 |
+
"post_attention_layernorm.bias",
|
| 39 |
+
"self_attention.dense.bias",
|
| 40 |
+
"mlp.dense_4h_to_h.bias",
|
| 41 |
+
"ln_f.weight",
|
| 42 |
+
"ln_f.bias",
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN = [
|
| 46 |
+
"mlp.dense_4h_to_h.weight",
|
| 47 |
+
"self_attention.dense.weight",
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def layer_name_mapping(key, file):
|
| 52 |
+
"""Convert Megatron-DeepSpeed TP/PP weights mapping in transformers PP only"""
|
| 53 |
+
# Handle first and last layers
|
| 54 |
+
layer_rename_map = {
|
| 55 |
+
"word_embeddings.weight": "word_embeddings.weight",
|
| 56 |
+
"word_embeddings.norm.weight": "word_embeddings_layernorm.weight",
|
| 57 |
+
"word_embeddings.norm.bias": "word_embeddings_layernorm.bias",
|
| 58 |
+
"weight": "ln_f.weight",
|
| 59 |
+
"bias": "ln_f.bias",
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
if key in layer_rename_map:
|
| 63 |
+
return layer_rename_map[key]
|
| 64 |
+
|
| 65 |
+
# Handle transformer blocks
|
| 66 |
+
layer_number = int(re.match(r".*layer_(\d*).*", file)[1])
|
| 67 |
+
layer_number -= 3
|
| 68 |
+
return f"h.{layer_number}." + key
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def get_dtype_size(dtype):
|
| 72 |
+
if dtype == torch.bool:
|
| 73 |
+
return 1 / 8
|
| 74 |
+
bit_search = re.search(r"[^\d](\d+)$", str(dtype))
|
| 75 |
+
if bit_search is None:
|
| 76 |
+
raise ValueError(f"`dtype` is not a valid dtype: {dtype}.")
|
| 77 |
+
bit_size = int(bit_search.groups()[0])
|
| 78 |
+
return bit_size // 8
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def convert_bloom_checkpoint_to_pytorch(
|
| 82 |
+
bloom_checkpoint_path, bloom_config_file, pytorch_dump_folder_path, shard_model, pretraining_tp
|
| 83 |
+
):
|
| 84 |
+
# Construct model
|
| 85 |
+
if bloom_config_file == "":
|
| 86 |
+
config = BloomConfig()
|
| 87 |
+
else:
|
| 88 |
+
config = BloomConfig.from_json_file(bloom_config_file)
|
| 89 |
+
|
| 90 |
+
if shard_model:
|
| 91 |
+
file_names = os.listdir(bloom_checkpoint_path)
|
| 92 |
+
file_names = sorted(filter(lambda s: s.startswith("layer") and "model_00" in s, file_names))
|
| 93 |
+
|
| 94 |
+
index_dict = {"weight_map": {}, "metadata": {}}
|
| 95 |
+
total_size = 0
|
| 96 |
+
|
| 97 |
+
missing_keys = None
|
| 98 |
+
|
| 99 |
+
config = BloomConfig()
|
| 100 |
+
|
| 101 |
+
for j, file in enumerate(file_names):
|
| 102 |
+
print("Processing file: {}".format(file))
|
| 103 |
+
tensors = None
|
| 104 |
+
|
| 105 |
+
for i in range(pretraining_tp):
|
| 106 |
+
# load all TP files
|
| 107 |
+
f_name = file.replace("model_00", f"model_0{i}")
|
| 108 |
+
temp = torch.load(os.path.join(bloom_checkpoint_path, f_name), map_location="cpu")
|
| 109 |
+
|
| 110 |
+
# Rename keys in the transformers names
|
| 111 |
+
keys = list(temp.keys())
|
| 112 |
+
for key in keys:
|
| 113 |
+
temp[layer_name_mapping(key, file)] = temp.pop(key)
|
| 114 |
+
|
| 115 |
+
if tensors is None:
|
| 116 |
+
tensors = temp
|
| 117 |
+
else:
|
| 118 |
+
for key in tensors.keys():
|
| 119 |
+
if any(key.endswith(end) for end in WEIGHTS_TO_AVERAGE_ENDSWITH):
|
| 120 |
+
# We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425)
|
| 121 |
+
tensors[key] += temp[key]
|
| 122 |
+
else:
|
| 123 |
+
# Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel
|
| 124 |
+
cat_dim = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN) else 0
|
| 125 |
+
# We concatenate these weights accross TP ranks
|
| 126 |
+
tensors[key] = torch.cat([tensors[key], temp[key]], dim=cat_dim)
|
| 127 |
+
|
| 128 |
+
# Divide by the number of TP the weights we want to average
|
| 129 |
+
for key in tensors.keys():
|
| 130 |
+
if any(key.endswith(end) for end in WEIGHTS_TO_AVERAGE_ENDSWITH):
|
| 131 |
+
tensors[key] = tensors[key] / pretraining_tp
|
| 132 |
+
torch.save(
|
| 133 |
+
tensors,
|
| 134 |
+
os.path.join(
|
| 135 |
+
pytorch_dump_folder_path,
|
| 136 |
+
"pytorch_model_{}-of-{}.bin".format(str(j + 1).zfill(5), str(len(file_names)).zfill(5)),
|
| 137 |
+
),
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
for key in tensors.keys():
|
| 141 |
+
value = tensors[key]
|
| 142 |
+
total_size += value.numel() * get_dtype_size(value.dtype)
|
| 143 |
+
if key not in index_dict["weight_map"]:
|
| 144 |
+
index_dict["weight_map"][key] = "pytorch_model_{}-of-{}.bin".format(
|
| 145 |
+
str(j + 1).zfill(5), str(len(file_names)).zfill(5)
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
config = BloomConfig()
|
| 149 |
+
pytorch_config_dump_path = pytorch_dump_folder_path + "/" + CONFIG_NAME
|
| 150 |
+
index_dict["metadata"]["total_size"] = total_size
|
| 151 |
+
with open(pytorch_config_dump_path, "w", encoding="utf-8") as f:
|
| 152 |
+
f.write(config.to_json_string())
|
| 153 |
+
with open(os.path.join(pytorch_dump_folder_path, WEIGHTS_NAME + ".index.json"), "w", encoding="utf-8") as f:
|
| 154 |
+
json_config = json.dumps(index_dict, indent=2, sort_keys=True) + "\n"
|
| 155 |
+
f.write(json_config)
|
| 156 |
+
else:
|
| 157 |
+
model = BloomModel(config)
|
| 158 |
+
|
| 159 |
+
file_names = os.listdir(bloom_checkpoint_path)
|
| 160 |
+
file_names = sorted(filter(lambda s: s.startswith("layer") and "model_00" in s, file_names))
|
| 161 |
+
|
| 162 |
+
missing_keys = None
|
| 163 |
+
for i, file in enumerate(file_names):
|
| 164 |
+
tensors = None
|
| 165 |
+
for i in range(pretraining_tp):
|
| 166 |
+
# load all TP files
|
| 167 |
+
f_name = file.replace("model_00", f"model_0{i}")
|
| 168 |
+
temp = torch.load(os.path.join(bloom_checkpoint_path, f_name), map_location="cpu")
|
| 169 |
+
|
| 170 |
+
# Rename keys in the transformers names
|
| 171 |
+
keys = list(temp.keys())
|
| 172 |
+
for key in keys:
|
| 173 |
+
temp[layer_name_mapping(key, file)] = temp.pop(key)
|
| 174 |
+
|
| 175 |
+
if tensors is None:
|
| 176 |
+
tensors = temp
|
| 177 |
+
else:
|
| 178 |
+
for key in tensors.keys():
|
| 179 |
+
# We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425)
|
| 180 |
+
if any(key.endswith(end) for end in WEIGHTS_TO_AVERAGE_ENDSWITH):
|
| 181 |
+
tensors[key] += temp[key]
|
| 182 |
+
else:
|
| 183 |
+
# Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel
|
| 184 |
+
cat_dim = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN) else 0
|
| 185 |
+
# We concatenate these weights accross TP ranks
|
| 186 |
+
tensors[key] = torch.cat([tensors[key], temp[key]], dim=cat_dim)
|
| 187 |
+
|
| 188 |
+
# Divide by the number of TP the weights we want to average
|
| 189 |
+
for key in tensors.keys():
|
| 190 |
+
if any(key.endswith(end) for end in WEIGHTS_TO_AVERAGE_ENDSWITH):
|
| 191 |
+
tensors[key] = tensors[key] / pretraining_tp
|
| 192 |
+
|
| 193 |
+
other_keys = model.load_state_dict(tensors, strict=False)
|
| 194 |
+
assert not other_keys.unexpected_keys, f"The keys {other_keys.unexpected_keys} are unexpected"
|
| 195 |
+
if missing_keys is None:
|
| 196 |
+
missing_keys = set(other_keys.missing_keys)
|
| 197 |
+
else:
|
| 198 |
+
missing_keys = missing_keys.intersection(set(other_keys.missing_keys))
|
| 199 |
+
|
| 200 |
+
assert not missing_keys, f"The keys {missing_keys} are missing"
|
| 201 |
+
|
| 202 |
+
# Save pytorch-model
|
| 203 |
+
os.makedirs(pytorch_dump_folder_path, exist_ok=True)
|
| 204 |
+
pytorch_weights_dump_path = pytorch_dump_folder_path + "/" + WEIGHTS_NAME
|
| 205 |
+
pytorch_config_dump_path = pytorch_dump_folder_path + "/" + CONFIG_NAME
|
| 206 |
+
print(f"Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}")
|
| 207 |
+
if config.torch_dtype is not None:
|
| 208 |
+
model = model.to(config.torch_dtype)
|
| 209 |
+
torch.save(model.state_dict(), pytorch_weights_dump_path)
|
| 210 |
+
print(f"Save configuration file to {pytorch_config_dump_path}")
|
| 211 |
+
with open(pytorch_config_dump_path, "w", encoding="utf-8") as f:
|
| 212 |
+
f.write(config.to_json_string())
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
if __name__ == "__main__":
|
| 216 |
+
parser = argparse.ArgumentParser()
|
| 217 |
+
# Required parameters
|
| 218 |
+
parser.add_argument(
|
| 219 |
+
"--bloom_checkpoint_path",
|
| 220 |
+
default=None,
|
| 221 |
+
type=str,
|
| 222 |
+
required=True,
|
| 223 |
+
help="Path to the Megatron-LM checkpoint path.",
|
| 224 |
+
)
|
| 225 |
+
parser.add_argument(
|
| 226 |
+
"--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
|
| 227 |
+
)
|
| 228 |
+
parser.add_argument(
|
| 229 |
+
"--bloom_config_file",
|
| 230 |
+
default="",
|
| 231 |
+
type=str,
|
| 232 |
+
help=(
|
| 233 |
+
"An optional config json file corresponding to the pre-trained model. \n"
|
| 234 |
+
"This specifies the model architecture."
|
| 235 |
+
),
|
| 236 |
+
)
|
| 237 |
+
parser.add_argument(
|
| 238 |
+
"--shard_model",
|
| 239 |
+
action="store_true",
|
| 240 |
+
help="An optional setting to shard the output model \nThis enables sharding the converted checkpoint",
|
| 241 |
+
)
|
| 242 |
+
parser.add_argument(
|
| 243 |
+
"--pretraining_tp",
|
| 244 |
+
default=4,
|
| 245 |
+
type=int,
|
| 246 |
+
help="Pretraining TP rank that has been used when training the model in Megatron-LM \n",
|
| 247 |
+
)
|
| 248 |
+
args = parser.parse_args()
|
| 249 |
+
convert_bloom_checkpoint_to_pytorch(
|
| 250 |
+
args.bloom_checkpoint_path,
|
| 251 |
+
args.bloom_config_file,
|
| 252 |
+
args.pytorch_dump_folder_path,
|
| 253 |
+
args.shard_model,
|
| 254 |
+
args.pretraining_tp,
|
| 255 |
+
)
|
llava_next/lib/python3.10/site-packages/transformers/models/bloom/tokenization_bloom_fast.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Tokenization classes for Bloom."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import pickle
|
| 19 |
+
from typing import Optional, Tuple
|
| 20 |
+
|
| 21 |
+
from ...tokenization_utils_base import BatchEncoding
|
| 22 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
| 23 |
+
from ...utils import logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
VOCAB_FILES_NAMES = {"tokenizer_file": "tokenizer.json"}
|
| 29 |
+
|
| 30 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
| 31 |
+
"tokenizer_file": {
|
| 32 |
+
"bigscience/tokenizer": "https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json",
|
| 33 |
+
"bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json",
|
| 34 |
+
"bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json",
|
| 35 |
+
"bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json",
|
| 36 |
+
"bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json",
|
| 37 |
+
"bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json",
|
| 38 |
+
"bigscience/bloom": "https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json",
|
| 39 |
+
},
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class BloomTokenizerFast(PreTrainedTokenizerFast):
|
| 44 |
+
"""
|
| 45 |
+
Construct a "fast" Bloom tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
|
| 46 |
+
Byte-Pair-Encoding.
|
| 47 |
+
|
| 48 |
+
This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
|
| 49 |
+
be encoded differently whether it is at the beginning of the sentence (without space) or not:
|
| 50 |
+
|
| 51 |
+
```python
|
| 52 |
+
>>> from transformers import BloomTokenizerFast
|
| 53 |
+
|
| 54 |
+
>>> tokenizer = BloomTokenizerFast.from_pretrained("bigscience/bloom")
|
| 55 |
+
>>> tokenizer("Hello world")["input_ids"]
|
| 56 |
+
[59414, 8876]
|
| 57 |
+
|
| 58 |
+
>>> tokenizer(" Hello world")["input_ids"]
|
| 59 |
+
[86153, 8876]
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since
|
| 63 |
+
the model was not pretrained this way, it might yield a decrease in performance.
|
| 64 |
+
|
| 65 |
+
<Tip>
|
| 66 |
+
|
| 67 |
+
When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
|
| 68 |
+
|
| 69 |
+
</Tip>
|
| 70 |
+
|
| 71 |
+
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
|
| 72 |
+
refer to this superclass for more information regarding those methods.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
vocab_file (`str`):
|
| 76 |
+
Path to the vocabulary file.
|
| 77 |
+
merges_file (`str`):
|
| 78 |
+
Path to the merges file.
|
| 79 |
+
errors (`str`, *optional*, defaults to `"replace"`):
|
| 80 |
+
Paradigm to follow when decoding bytes to UTF-8. See
|
| 81 |
+
[bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
|
| 82 |
+
unk_token (`str`, *optional*, defaults to `<|endoftext|>`):
|
| 83 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 84 |
+
token instead.
|
| 85 |
+
bos_token (`str`, *optional*, defaults to `<|endoftext|>`):
|
| 86 |
+
The beginning of sequence token.
|
| 87 |
+
eos_token (`str`, *optional*, defaults to `<|endoftext|>`):
|
| 88 |
+
The end of sequence token.
|
| 89 |
+
add_prefix_space (`bool`, *optional*, defaults to `False`):
|
| 90 |
+
Whether or not to add an initial space to the input. This allows to treat the leading word just as any
|
| 91 |
+
other word. (Bloom tokenizer detect beginning of words by the preceding space).
|
| 92 |
+
trim_offsets (`bool`, *optional*, defaults to `True`):
|
| 93 |
+
Whether or not the post-processing step should trim offsets to avoid including whitespaces.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 97 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
| 98 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 99 |
+
slow_tokenizer_class = None
|
| 100 |
+
# No `max_model_input_sizes` as BLOOM uses ALiBi positional embeddings
|
| 101 |
+
|
| 102 |
+
def __init__(
|
| 103 |
+
self,
|
| 104 |
+
vocab_file=None,
|
| 105 |
+
merges_file=None,
|
| 106 |
+
tokenizer_file=None,
|
| 107 |
+
unk_token="<unk>",
|
| 108 |
+
bos_token="<s>",
|
| 109 |
+
eos_token="</s>",
|
| 110 |
+
pad_token="<pad>",
|
| 111 |
+
add_prefix_space=False,
|
| 112 |
+
clean_up_tokenization_spaces=False,
|
| 113 |
+
**kwargs,
|
| 114 |
+
):
|
| 115 |
+
super().__init__(
|
| 116 |
+
vocab_file,
|
| 117 |
+
merges_file,
|
| 118 |
+
tokenizer_file=tokenizer_file,
|
| 119 |
+
unk_token=unk_token,
|
| 120 |
+
bos_token=bos_token,
|
| 121 |
+
eos_token=eos_token,
|
| 122 |
+
pad_token=pad_token,
|
| 123 |
+
add_prefix_space=add_prefix_space,
|
| 124 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 125 |
+
**kwargs,
|
| 126 |
+
)
|
| 127 |
+
# TODO @ArthurZucker this can only work one way for now, to update later-on. Tests should also properly
|
| 128 |
+
# check this as they were green before.
|
| 129 |
+
pre_tok_state = pickle.dumps(self.backend_tokenizer.pre_tokenizer)
|
| 130 |
+
decoder_state = pickle.dumps(self.backend_tokenizer.decoder)
|
| 131 |
+
|
| 132 |
+
if add_prefix_space:
|
| 133 |
+
pre_tok_state = pre_tok_state.replace(b'"add_prefix_space":false', b'"add_prefix_space": true')
|
| 134 |
+
decoder_state = decoder_state.replace(b'"add_prefix_space":false', b'"add_prefix_space": true')
|
| 135 |
+
self.backend_tokenizer.pre_tokenizer = pickle.loads(pre_tok_state)
|
| 136 |
+
self.backend_tokenizer.decoder = pickle.loads(decoder_state)
|
| 137 |
+
|
| 138 |
+
self.add_prefix_space = add_prefix_space
|
| 139 |
+
|
| 140 |
+
def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
|
| 141 |
+
is_split_into_words = kwargs.get("is_split_into_words", False)
|
| 142 |
+
if not (self.add_prefix_space or not is_split_into_words):
|
| 143 |
+
raise Exception(
|
| 144 |
+
f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with"
|
| 145 |
+
" pretokenized inputs."
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
return super()._batch_encode_plus(*args, **kwargs)
|
| 149 |
+
|
| 150 |
+
def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
|
| 151 |
+
is_split_into_words = kwargs.get("is_split_into_words", False)
|
| 152 |
+
|
| 153 |
+
if not (self.add_prefix_space or not is_split_into_words):
|
| 154 |
+
raise Exception(
|
| 155 |
+
f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with"
|
| 156 |
+
" pretokenized inputs."
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
return super()._encode_plus(*args, **kwargs)
|
| 160 |
+
|
| 161 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 162 |
+
files = self._tokenizer.model.save(save_directory, name=filename_prefix)
|
| 163 |
+
return tuple(files)
|
| 164 |
+
|
| 165 |
+
@property
|
| 166 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.default_chat_template
|
| 167 |
+
def default_chat_template(self):
|
| 168 |
+
"""
|
| 169 |
+
A simple chat template that ignores role information and just concatenates messages with EOS tokens.
|
| 170 |
+
"""
|
| 171 |
+
logger.warning_once(
|
| 172 |
+
"\nNo chat template is defined for this tokenizer - using the default template "
|
| 173 |
+
f"for the {self.__class__.__name__} class. If the default is not appropriate for "
|
| 174 |
+
"your model, please set `tokenizer.chat_template` to an appropriate template. "
|
| 175 |
+
"See https://huggingface.co/docs/transformers/main/chat_templating for more information.\n"
|
| 176 |
+
)
|
| 177 |
+
return "{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}"
|
llava_next/lib/python3.10/site-packages/transformers/models/cpmant/__init__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa
|
| 2 |
+
# There's no way to ignore "F401 '...' imported but unused" warnings in this
|
| 3 |
+
# module, but to preserve other warnings. So, don't check this module at all.
|
| 4 |
+
|
| 5 |
+
# Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved.
|
| 6 |
+
#
|
| 7 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 8 |
+
# you may not use this file except in compliance with the License.
|
| 9 |
+
# You may obtain a copy of the License at
|
| 10 |
+
#
|
| 11 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 12 |
+
#
|
| 13 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 14 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 15 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 16 |
+
# See the License for the specific language governing permissions and
|
| 17 |
+
# limitations under the License.
|
| 18 |
+
from typing import TYPE_CHECKING
|
| 19 |
+
|
| 20 |
+
# rely on isort to merge the imports
|
| 21 |
+
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
_import_structure = {
|
| 25 |
+
"configuration_cpmant": ["CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP", "CpmAntConfig"],
|
| 26 |
+
"tokenization_cpmant": ["CpmAntTokenizer"],
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
if not is_torch_available():
|
| 31 |
+
raise OptionalDependencyNotAvailable()
|
| 32 |
+
except OptionalDependencyNotAvailable:
|
| 33 |
+
pass
|
| 34 |
+
else:
|
| 35 |
+
_import_structure["modeling_cpmant"] = [
|
| 36 |
+
"CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 37 |
+
"CpmAntForCausalLM",
|
| 38 |
+
"CpmAntModel",
|
| 39 |
+
"CpmAntPreTrainedModel",
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if TYPE_CHECKING:
|
| 44 |
+
from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig
|
| 45 |
+
from .tokenization_cpmant import CpmAntTokenizer
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
if not is_torch_available():
|
| 49 |
+
raise OptionalDependencyNotAvailable()
|
| 50 |
+
except OptionalDependencyNotAvailable:
|
| 51 |
+
pass
|
| 52 |
+
else:
|
| 53 |
+
from .modeling_cpmant import (
|
| 54 |
+
CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 55 |
+
CpmAntForCausalLM,
|
| 56 |
+
CpmAntModel,
|
| 57 |
+
CpmAntPreTrainedModel,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
else:
|
| 62 |
+
import sys
|
| 63 |
+
|
| 64 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
llava_next/lib/python3.10/site-packages/transformers/models/cpmant/__pycache__/configuration_cpmant.cpython-310.pyc
ADDED
|
Binary file (4.74 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/transformers/models/cpmant/__pycache__/modeling_cpmant.cpython-310.pyc
ADDED
|
Binary file (29.2 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/transformers/models/cpmant/__pycache__/tokenization_cpmant.cpython-310.pyc
ADDED
|
Binary file (9.82 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/transformers/models/cpmant/tokenization_cpmant.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The OpenBMB Team and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization classes for CPMAnt."""
|
| 16 |
+
import collections
|
| 17 |
+
import os
|
| 18 |
+
from typing import List, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from transformers.utils import is_jieba_available, requires_backends
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
if is_jieba_available():
|
| 24 |
+
import jieba
|
| 25 |
+
|
| 26 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 27 |
+
from ...utils import logging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
|
| 33 |
+
|
| 34 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
| 35 |
+
"vocab_file": {
|
| 36 |
+
"openbmb/cpm-ant-10b": "https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt",
|
| 37 |
+
},
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
|
| 41 |
+
"openbmb/cpm-ant-10b": 1024,
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def load_vocab(vocab_file):
|
| 46 |
+
"""Loads a vocabulary file into a dictionary."""
|
| 47 |
+
vocab = collections.OrderedDict()
|
| 48 |
+
with open(vocab_file, "r", encoding="utf-8") as reader:
|
| 49 |
+
tokens = reader.readlines()
|
| 50 |
+
for index, token in enumerate(tokens):
|
| 51 |
+
token = token.rstrip("\n")
|
| 52 |
+
vocab[token] = index
|
| 53 |
+
return vocab
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class WordpieceTokenizer(object):
|
| 57 |
+
def __init__(self, vocab, unk_token="<unk>", max_input_chars_per_word=200):
|
| 58 |
+
self.vocab = vocab
|
| 59 |
+
self.unk_token = unk_token
|
| 60 |
+
self.max_input_chars_per_word = max_input_chars_per_word
|
| 61 |
+
|
| 62 |
+
def tokenize(self, token):
|
| 63 |
+
chars = list(token)
|
| 64 |
+
if len(chars) > self.max_input_chars_per_word:
|
| 65 |
+
return [self.unk_token]
|
| 66 |
+
|
| 67 |
+
start = 0
|
| 68 |
+
sub_tokens = []
|
| 69 |
+
while start < len(chars):
|
| 70 |
+
end = len(chars)
|
| 71 |
+
cur_substr = None
|
| 72 |
+
while start < end:
|
| 73 |
+
substr = "".join(chars[start:end])
|
| 74 |
+
if substr in self.vocab:
|
| 75 |
+
cur_substr = substr
|
| 76 |
+
break
|
| 77 |
+
end -= 1
|
| 78 |
+
if cur_substr is None:
|
| 79 |
+
sub_tokens.append(self.unk_token)
|
| 80 |
+
start += 1
|
| 81 |
+
else:
|
| 82 |
+
sub_tokens.append(cur_substr)
|
| 83 |
+
start = end
|
| 84 |
+
|
| 85 |
+
return sub_tokens
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class CpmAntTokenizer(PreTrainedTokenizer):
|
| 89 |
+
"""
|
| 90 |
+
Construct a CPMAnt tokenizer. Based on byte-level Byte-Pair-Encoding.
|
| 91 |
+
|
| 92 |
+
Args:
|
| 93 |
+
vocab_file (`str`):
|
| 94 |
+
Path to the vocabulary file.
|
| 95 |
+
bod_token (`str`, *optional*, defaults to `"<d>"`):
|
| 96 |
+
The beginning of document token.
|
| 97 |
+
eod_token (`str`, *optional*, defaults to `"</d>"`):
|
| 98 |
+
The end of document token.
|
| 99 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 100 |
+
The beginning of sequence token.
|
| 101 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 102 |
+
The end of sequence token.
|
| 103 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 104 |
+
The token used for padding.
|
| 105 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 106 |
+
The unknown token.
|
| 107 |
+
line_token (`str`, *optional*, defaults to `"</n>"`):
|
| 108 |
+
The line token.
|
| 109 |
+
space_token (`str`, *optional*, defaults to `"</_>"`):
|
| 110 |
+
The space token.
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 114 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
| 115 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
| 116 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 117 |
+
add_prefix_space = False
|
| 118 |
+
|
| 119 |
+
def __init__(
|
| 120 |
+
self,
|
| 121 |
+
vocab_file,
|
| 122 |
+
bod_token="<d>",
|
| 123 |
+
eod_token="</d>",
|
| 124 |
+
bos_token="<s>",
|
| 125 |
+
eos_token="</s>",
|
| 126 |
+
pad_token="<pad>",
|
| 127 |
+
unk_token="<unk>",
|
| 128 |
+
line_token="</n>",
|
| 129 |
+
space_token="</_>",
|
| 130 |
+
padding_side="left",
|
| 131 |
+
**kwargs,
|
| 132 |
+
):
|
| 133 |
+
requires_backends(self, ["jieba"])
|
| 134 |
+
self.bod_token = bod_token
|
| 135 |
+
self.eod_token = eod_token
|
| 136 |
+
self.encoder = load_vocab(vocab_file)
|
| 137 |
+
self.encoder[" "] = self.encoder[space_token]
|
| 138 |
+
self.encoder["\n"] = self.encoder[line_token]
|
| 139 |
+
|
| 140 |
+
del self.encoder[space_token]
|
| 141 |
+
del self.encoder[line_token]
|
| 142 |
+
|
| 143 |
+
self.encoder = collections.OrderedDict(sorted(self.encoder.items(), key=lambda x: x[1]))
|
| 144 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 145 |
+
|
| 146 |
+
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.encoder, unk_token=unk_token)
|
| 147 |
+
|
| 148 |
+
super().__init__(
|
| 149 |
+
bod_token=bod_token,
|
| 150 |
+
eod_token=eod_token,
|
| 151 |
+
bos_token=bos_token,
|
| 152 |
+
eos_token=eos_token,
|
| 153 |
+
pad_token=pad_token,
|
| 154 |
+
unk_token=unk_token,
|
| 155 |
+
line_token=line_token,
|
| 156 |
+
space_token=space_token,
|
| 157 |
+
padding_side=padding_side,
|
| 158 |
+
**kwargs,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
@property
|
| 162 |
+
def bod_token_id(self):
|
| 163 |
+
return self.encoder[self.bod_token]
|
| 164 |
+
|
| 165 |
+
@property
|
| 166 |
+
def eod_token_id(self):
|
| 167 |
+
return self.encoder[self.eod_token]
|
| 168 |
+
|
| 169 |
+
@property
|
| 170 |
+
def newline_id(self):
|
| 171 |
+
return self.encoder["\n"]
|
| 172 |
+
|
| 173 |
+
@property
|
| 174 |
+
def vocab_size(self) -> int:
|
| 175 |
+
return len(self.encoder)
|
| 176 |
+
|
| 177 |
+
def get_vocab(self):
|
| 178 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
| 179 |
+
|
| 180 |
+
def _tokenize(self, text):
|
| 181 |
+
"""Tokenize a string."""
|
| 182 |
+
output_tokens = []
|
| 183 |
+
for x in jieba.cut(text, cut_all=False):
|
| 184 |
+
output_tokens.extend(self.wordpiece_tokenizer.tokenize(x))
|
| 185 |
+
return output_tokens
|
| 186 |
+
|
| 187 |
+
def _decode(self, token_ids, **kwargs):
|
| 188 |
+
"""Decode ids into a string."""
|
| 189 |
+
token_ids = [i for i in token_ids if i >= 0]
|
| 190 |
+
token_ids = [
|
| 191 |
+
x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id
|
| 192 |
+
]
|
| 193 |
+
return super()._decode(token_ids, **kwargs)
|
| 194 |
+
|
| 195 |
+
def check(self, token):
|
| 196 |
+
return token in self.encoder
|
| 197 |
+
|
| 198 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str:
|
| 199 |
+
return "".join(tokens)
|
| 200 |
+
|
| 201 |
+
def _convert_token_to_id(self, token):
|
| 202 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 203 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
| 204 |
+
|
| 205 |
+
def _convert_id_to_token(self, index):
|
| 206 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 207 |
+
return self.decoder.get(index, self.unk_token)
|
| 208 |
+
|
| 209 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 210 |
+
if os.path.isdir(save_directory):
|
| 211 |
+
vocab_file = os.path.join(
|
| 212 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 213 |
+
)
|
| 214 |
+
else:
|
| 215 |
+
vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
|
| 216 |
+
index = 0
|
| 217 |
+
if " " in self.encoder:
|
| 218 |
+
self.encoder["</_>"] = self.encoder[" "]
|
| 219 |
+
del self.encoder[" "]
|
| 220 |
+
if "\n" in self.encoder:
|
| 221 |
+
self.encoder["</n>"] = self.encoder["\n"]
|
| 222 |
+
del self.encoder["\n"]
|
| 223 |
+
self.encoder = collections.OrderedDict(sorted(self.encoder.items(), key=lambda x: x[1]))
|
| 224 |
+
with open(vocab_file, "w", encoding="utf-8") as writer:
|
| 225 |
+
for token, token_index in self.encoder.items():
|
| 226 |
+
if index != token_index:
|
| 227 |
+
logger.warning(
|
| 228 |
+
f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
|
| 229 |
+
" Please check that the vocabulary is not corrupted!"
|
| 230 |
+
)
|
| 231 |
+
index = token_index
|
| 232 |
+
writer.write(token + "\n")
|
| 233 |
+
index += 1
|
| 234 |
+
return (vocab_file,)
|
| 235 |
+
|
| 236 |
+
def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: List[int] = None) -> List[int]:
|
| 237 |
+
"""
|
| 238 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 239 |
+
adding special tokens. A CPMAnt sequence has the following format:
|
| 240 |
+
|
| 241 |
+
- single sequence: `[BOS] Sequence`.
|
| 242 |
+
|
| 243 |
+
Args:
|
| 244 |
+
token_ids_0 (`List[int]`): The first tokenized sequence that special tokens will be added.
|
| 245 |
+
token_ids_1 (`List[int]`): The optional second tokenized sequence that special tokens will be added.
|
| 246 |
+
|
| 247 |
+
Returns:
|
| 248 |
+
`List[int]`: The model input with special tokens.
|
| 249 |
+
"""
|
| 250 |
+
if token_ids_1 is None:
|
| 251 |
+
return [self.bos_token_id] + token_ids_0
|
| 252 |
+
return [self.bos_token_id] + token_ids_0 + [self.bos_token_id] + token_ids_1
|
| 253 |
+
|
| 254 |
+
def get_special_tokens_mask(
|
| 255 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 256 |
+
) -> List[int]:
|
| 257 |
+
"""
|
| 258 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 259 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
token_ids_0 (`List[int]`): List of IDs.
|
| 263 |
+
token_ids_1 (`List[int]`, *optional*): Optional second list of IDs for sequence pairs.
|
| 264 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 265 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 266 |
+
|
| 267 |
+
Returns:
|
| 268 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 269 |
+
"""
|
| 270 |
+
|
| 271 |
+
if already_has_special_tokens:
|
| 272 |
+
return super().get_special_tokens_mask(
|
| 273 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
if token_ids_1 is not None:
|
| 277 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
|
| 278 |
+
return [1] + ([0] * len(token_ids_0))
|
llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/__init__.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import TYPE_CHECKING
|
| 16 |
+
|
| 17 |
+
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
_import_structure = {
|
| 21 |
+
"configuration_deformable_detr": ["DEFORMABLE_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP", "DeformableDetrConfig"],
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
if not is_vision_available():
|
| 26 |
+
raise OptionalDependencyNotAvailable()
|
| 27 |
+
except OptionalDependencyNotAvailable:
|
| 28 |
+
pass
|
| 29 |
+
else:
|
| 30 |
+
_import_structure["feature_extraction_deformable_detr"] = ["DeformableDetrFeatureExtractor"]
|
| 31 |
+
_import_structure["image_processing_deformable_detr"] = ["DeformableDetrImageProcessor"]
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
if not is_torch_available():
|
| 35 |
+
raise OptionalDependencyNotAvailable()
|
| 36 |
+
except OptionalDependencyNotAvailable:
|
| 37 |
+
pass
|
| 38 |
+
else:
|
| 39 |
+
_import_structure["modeling_deformable_detr"] = [
|
| 40 |
+
"DEFORMABLE_DETR_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 41 |
+
"DeformableDetrForObjectDetection",
|
| 42 |
+
"DeformableDetrModel",
|
| 43 |
+
"DeformableDetrPreTrainedModel",
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if TYPE_CHECKING:
|
| 48 |
+
from .configuration_deformable_detr import DEFORMABLE_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, DeformableDetrConfig
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
if not is_vision_available():
|
| 52 |
+
raise OptionalDependencyNotAvailable()
|
| 53 |
+
except OptionalDependencyNotAvailable:
|
| 54 |
+
pass
|
| 55 |
+
else:
|
| 56 |
+
from .feature_extraction_deformable_detr import DeformableDetrFeatureExtractor
|
| 57 |
+
from .image_processing_deformable_detr import DeformableDetrImageProcessor
|
| 58 |
+
|
| 59 |
+
try:
|
| 60 |
+
if not is_torch_available():
|
| 61 |
+
raise OptionalDependencyNotAvailable()
|
| 62 |
+
except OptionalDependencyNotAvailable:
|
| 63 |
+
pass
|
| 64 |
+
else:
|
| 65 |
+
from .modeling_deformable_detr import (
|
| 66 |
+
DEFORMABLE_DETR_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 67 |
+
DeformableDetrForObjectDetection,
|
| 68 |
+
DeformableDetrModel,
|
| 69 |
+
DeformableDetrPreTrainedModel,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
else:
|
| 73 |
+
import sys
|
| 74 |
+
|
| 75 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/convert_deformable_detr_to_pytorch.cpython-310.pyc
ADDED
|
Binary file (6.82 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/feature_extraction_deformable_detr.cpython-310.pyc
ADDED
|
Binary file (1.41 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/image_processing_deformable_detr.cpython-310.pyc
ADDED
|
Binary file (48.1 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/configuration_deformable_detr.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 SenseTime 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 |
+
""" Deformable DETR model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
from ..auto import CONFIG_MAPPING
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
DEFORMABLE_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
| 25 |
+
"SenseTime/deformable-detr": "https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json",
|
| 26 |
+
# See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class DeformableDetrConfig(PretrainedConfig):
|
| 31 |
+
r"""
|
| 32 |
+
This is the configuration class to store the configuration of a [`DeformableDetrModel`]. It is used to instantiate
|
| 33 |
+
a Deformable DETR model according to the specified arguments, defining the model architecture. Instantiating a
|
| 34 |
+
configuration with the defaults will yield a similar configuration to that of the Deformable DETR
|
| 35 |
+
[SenseTime/deformable-detr](https://huggingface.co/SenseTime/deformable-detr) 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 |
+
use_timm_backbone (`bool`, *optional*, defaults to `True`):
|
| 42 |
+
Whether or not to use the `timm` library for the backbone. If set to `False`, will use the [`AutoBackbone`]
|
| 43 |
+
API.
|
| 44 |
+
backbone_config (`PretrainedConfig` or `dict`, *optional*):
|
| 45 |
+
The configuration of the backbone model. Only used in case `use_timm_backbone` is set to `False` in which
|
| 46 |
+
case it will default to `ResNetConfig()`.
|
| 47 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 48 |
+
The number of input channels.
|
| 49 |
+
num_queries (`int`, *optional*, defaults to 300):
|
| 50 |
+
Number of object queries, i.e. detection slots. This is the maximal number of objects
|
| 51 |
+
[`DeformableDetrModel`] can detect in a single image. In case `two_stage` is set to `True`, we use
|
| 52 |
+
`two_stage_num_proposals` instead.
|
| 53 |
+
d_model (`int`, *optional*, defaults to 256):
|
| 54 |
+
Dimension of the layers.
|
| 55 |
+
encoder_layers (`int`, *optional*, defaults to 6):
|
| 56 |
+
Number of encoder layers.
|
| 57 |
+
decoder_layers (`int`, *optional*, defaults to 6):
|
| 58 |
+
Number of decoder layers.
|
| 59 |
+
encoder_attention_heads (`int`, *optional*, defaults to 8):
|
| 60 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 61 |
+
decoder_attention_heads (`int`, *optional*, defaults to 8):
|
| 62 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 63 |
+
decoder_ffn_dim (`int`, *optional*, defaults to 1024):
|
| 64 |
+
Dimension of the "intermediate" (often named feed-forward) layer in decoder.
|
| 65 |
+
encoder_ffn_dim (`int`, *optional*, defaults to 1024):
|
| 66 |
+
Dimension of the "intermediate" (often named feed-forward) layer in decoder.
|
| 67 |
+
activation_function (`str` or `function`, *optional*, defaults to `"relu"`):
|
| 68 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 69 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 70 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 71 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 72 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 73 |
+
The dropout ratio for the attention probabilities.
|
| 74 |
+
activation_dropout (`float`, *optional*, defaults to 0.0):
|
| 75 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 76 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 77 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 78 |
+
init_xavier_std (`float`, *optional*, defaults to 1):
|
| 79 |
+
The scaling factor used for the Xavier initialization gain in the HM Attention map module.
|
| 80 |
+
encoder_layerdrop (`float`, *optional*, defaults to 0.0):
|
| 81 |
+
The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
|
| 82 |
+
for more details.
|
| 83 |
+
auxiliary_loss (`bool`, *optional*, defaults to `False`):
|
| 84 |
+
Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
|
| 85 |
+
position_embedding_type (`str`, *optional*, defaults to `"sine"`):
|
| 86 |
+
Type of position embeddings to be used on top of the image features. One of `"sine"` or `"learned"`.
|
| 87 |
+
backbone (`str`, *optional*, defaults to `"resnet50"`):
|
| 88 |
+
Name of convolutional backbone to use in case `use_timm_backbone` = `True`. Supports any convolutional
|
| 89 |
+
backbone from the timm package. For a list of all available models, see [this
|
| 90 |
+
page](https://rwightman.github.io/pytorch-image-models/#load-a-pretrained-model).
|
| 91 |
+
use_pretrained_backbone (`bool`, *optional*, defaults to `True`):
|
| 92 |
+
Whether to use pretrained weights for the backbone. Only supported when `use_timm_backbone` = `True`.
|
| 93 |
+
dilation (`bool`, *optional*, defaults to `False`):
|
| 94 |
+
Whether to replace stride with dilation in the last convolutional block (DC5). Only supported when
|
| 95 |
+
`use_timm_backbone` = `True`.
|
| 96 |
+
class_cost (`float`, *optional*, defaults to 1):
|
| 97 |
+
Relative weight of the classification error in the Hungarian matching cost.
|
| 98 |
+
bbox_cost (`float`, *optional*, defaults to 5):
|
| 99 |
+
Relative weight of the L1 error of the bounding box coordinates in the Hungarian matching cost.
|
| 100 |
+
giou_cost (`float`, *optional*, defaults to 2):
|
| 101 |
+
Relative weight of the generalized IoU loss of the bounding box in the Hungarian matching cost.
|
| 102 |
+
mask_loss_coefficient (`float`, *optional*, defaults to 1):
|
| 103 |
+
Relative weight of the Focal loss in the panoptic segmentation loss.
|
| 104 |
+
dice_loss_coefficient (`float`, *optional*, defaults to 1):
|
| 105 |
+
Relative weight of the DICE/F-1 loss in the panoptic segmentation loss.
|
| 106 |
+
bbox_loss_coefficient (`float`, *optional*, defaults to 5):
|
| 107 |
+
Relative weight of the L1 bounding box loss in the object detection loss.
|
| 108 |
+
giou_loss_coefficient (`float`, *optional*, defaults to 2):
|
| 109 |
+
Relative weight of the generalized IoU loss in the object detection loss.
|
| 110 |
+
eos_coefficient (`float`, *optional*, defaults to 0.1):
|
| 111 |
+
Relative classification weight of the 'no-object' class in the object detection loss.
|
| 112 |
+
num_feature_levels (`int`, *optional*, defaults to 4):
|
| 113 |
+
The number of input feature levels.
|
| 114 |
+
encoder_n_points (`int`, *optional*, defaults to 4):
|
| 115 |
+
The number of sampled keys in each feature level for each attention head in the encoder.
|
| 116 |
+
decoder_n_points (`int`, *optional*, defaults to 4):
|
| 117 |
+
The number of sampled keys in each feature level for each attention head in the decoder.
|
| 118 |
+
two_stage (`bool`, *optional*, defaults to `False`):
|
| 119 |
+
Whether to apply a two-stage deformable DETR, where the region proposals are also generated by a variant of
|
| 120 |
+
Deformable DETR, which are further fed into the decoder for iterative bounding box refinement.
|
| 121 |
+
two_stage_num_proposals (`int`, *optional*, defaults to 300):
|
| 122 |
+
The number of region proposals to be generated, in case `two_stage` is set to `True`.
|
| 123 |
+
with_box_refine (`bool`, *optional*, defaults to `False`):
|
| 124 |
+
Whether to apply iterative bounding box refinement, where each decoder layer refines the bounding boxes
|
| 125 |
+
based on the predictions from the previous layer.
|
| 126 |
+
focal_alpha (`float`, *optional*, defaults to 0.25):
|
| 127 |
+
Alpha parameter in the focal loss.
|
| 128 |
+
disable_custom_kernels (`bool`, *optional*, defaults to `False`):
|
| 129 |
+
Disable the use of custom CUDA and CPU kernels. This option is necessary for the ONNX export, as custom
|
| 130 |
+
kernels are not supported by PyTorch ONNX export.
|
| 131 |
+
|
| 132 |
+
Examples:
|
| 133 |
+
|
| 134 |
+
```python
|
| 135 |
+
>>> from transformers import DeformableDetrConfig, DeformableDetrModel
|
| 136 |
+
|
| 137 |
+
>>> # Initializing a Deformable DETR SenseTime/deformable-detr style configuration
|
| 138 |
+
>>> configuration = DeformableDetrConfig()
|
| 139 |
+
|
| 140 |
+
>>> # Initializing a model (with random weights) from the SenseTime/deformable-detr style configuration
|
| 141 |
+
>>> model = DeformableDetrModel(configuration)
|
| 142 |
+
|
| 143 |
+
>>> # Accessing the model configuration
|
| 144 |
+
>>> configuration = model.config
|
| 145 |
+
```"""
|
| 146 |
+
|
| 147 |
+
model_type = "deformable_detr"
|
| 148 |
+
attribute_map = {
|
| 149 |
+
"hidden_size": "d_model",
|
| 150 |
+
"num_attention_heads": "encoder_attention_heads",
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
def __init__(
|
| 154 |
+
self,
|
| 155 |
+
use_timm_backbone=True,
|
| 156 |
+
backbone_config=None,
|
| 157 |
+
num_channels=3,
|
| 158 |
+
num_queries=300,
|
| 159 |
+
max_position_embeddings=1024,
|
| 160 |
+
encoder_layers=6,
|
| 161 |
+
encoder_ffn_dim=1024,
|
| 162 |
+
encoder_attention_heads=8,
|
| 163 |
+
decoder_layers=6,
|
| 164 |
+
decoder_ffn_dim=1024,
|
| 165 |
+
decoder_attention_heads=8,
|
| 166 |
+
encoder_layerdrop=0.0,
|
| 167 |
+
is_encoder_decoder=True,
|
| 168 |
+
activation_function="relu",
|
| 169 |
+
d_model=256,
|
| 170 |
+
dropout=0.1,
|
| 171 |
+
attention_dropout=0.0,
|
| 172 |
+
activation_dropout=0.0,
|
| 173 |
+
init_std=0.02,
|
| 174 |
+
init_xavier_std=1.0,
|
| 175 |
+
return_intermediate=True,
|
| 176 |
+
auxiliary_loss=False,
|
| 177 |
+
position_embedding_type="sine",
|
| 178 |
+
backbone="resnet50",
|
| 179 |
+
use_pretrained_backbone=True,
|
| 180 |
+
dilation=False,
|
| 181 |
+
num_feature_levels=4,
|
| 182 |
+
encoder_n_points=4,
|
| 183 |
+
decoder_n_points=4,
|
| 184 |
+
two_stage=False,
|
| 185 |
+
two_stage_num_proposals=300,
|
| 186 |
+
with_box_refine=False,
|
| 187 |
+
class_cost=1,
|
| 188 |
+
bbox_cost=5,
|
| 189 |
+
giou_cost=2,
|
| 190 |
+
mask_loss_coefficient=1,
|
| 191 |
+
dice_loss_coefficient=1,
|
| 192 |
+
bbox_loss_coefficient=5,
|
| 193 |
+
giou_loss_coefficient=2,
|
| 194 |
+
eos_coefficient=0.1,
|
| 195 |
+
focal_alpha=0.25,
|
| 196 |
+
disable_custom_kernels=False,
|
| 197 |
+
**kwargs,
|
| 198 |
+
):
|
| 199 |
+
if backbone_config is not None and use_timm_backbone:
|
| 200 |
+
raise ValueError("You can't specify both `backbone_config` and `use_timm_backbone`.")
|
| 201 |
+
|
| 202 |
+
if not use_timm_backbone:
|
| 203 |
+
if backbone_config is None:
|
| 204 |
+
logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.")
|
| 205 |
+
backbone_config = CONFIG_MAPPING["resnet"](out_features=["stage4"])
|
| 206 |
+
elif isinstance(backbone_config, dict):
|
| 207 |
+
backbone_model_type = backbone_config.get("model_type")
|
| 208 |
+
config_class = CONFIG_MAPPING[backbone_model_type]
|
| 209 |
+
backbone_config = config_class.from_dict(backbone_config)
|
| 210 |
+
self.use_timm_backbone = use_timm_backbone
|
| 211 |
+
self.backbone_config = backbone_config
|
| 212 |
+
self.num_channels = num_channels
|
| 213 |
+
self.num_queries = num_queries
|
| 214 |
+
self.max_position_embeddings = max_position_embeddings
|
| 215 |
+
self.d_model = d_model
|
| 216 |
+
self.encoder_ffn_dim = encoder_ffn_dim
|
| 217 |
+
self.encoder_layers = encoder_layers
|
| 218 |
+
self.encoder_attention_heads = encoder_attention_heads
|
| 219 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 220 |
+
self.decoder_layers = decoder_layers
|
| 221 |
+
self.decoder_attention_heads = decoder_attention_heads
|
| 222 |
+
self.dropout = dropout
|
| 223 |
+
self.attention_dropout = attention_dropout
|
| 224 |
+
self.activation_dropout = activation_dropout
|
| 225 |
+
self.activation_function = activation_function
|
| 226 |
+
self.init_std = init_std
|
| 227 |
+
self.init_xavier_std = init_xavier_std
|
| 228 |
+
self.encoder_layerdrop = encoder_layerdrop
|
| 229 |
+
self.auxiliary_loss = auxiliary_loss
|
| 230 |
+
self.position_embedding_type = position_embedding_type
|
| 231 |
+
self.backbone = backbone
|
| 232 |
+
self.use_pretrained_backbone = use_pretrained_backbone
|
| 233 |
+
self.dilation = dilation
|
| 234 |
+
# deformable attributes
|
| 235 |
+
self.num_feature_levels = num_feature_levels
|
| 236 |
+
self.encoder_n_points = encoder_n_points
|
| 237 |
+
self.decoder_n_points = decoder_n_points
|
| 238 |
+
self.two_stage = two_stage
|
| 239 |
+
self.two_stage_num_proposals = two_stage_num_proposals
|
| 240 |
+
self.with_box_refine = with_box_refine
|
| 241 |
+
if two_stage is True and with_box_refine is False:
|
| 242 |
+
raise ValueError("If two_stage is True, with_box_refine must be True.")
|
| 243 |
+
# Hungarian matcher
|
| 244 |
+
self.class_cost = class_cost
|
| 245 |
+
self.bbox_cost = bbox_cost
|
| 246 |
+
self.giou_cost = giou_cost
|
| 247 |
+
# Loss coefficients
|
| 248 |
+
self.mask_loss_coefficient = mask_loss_coefficient
|
| 249 |
+
self.dice_loss_coefficient = dice_loss_coefficient
|
| 250 |
+
self.bbox_loss_coefficient = bbox_loss_coefficient
|
| 251 |
+
self.giou_loss_coefficient = giou_loss_coefficient
|
| 252 |
+
self.eos_coefficient = eos_coefficient
|
| 253 |
+
self.focal_alpha = focal_alpha
|
| 254 |
+
self.disable_custom_kernels = disable_custom_kernels
|
| 255 |
+
super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)
|
| 256 |
+
|
| 257 |
+
@property
|
| 258 |
+
def num_attention_heads(self) -> int:
|
| 259 |
+
return self.encoder_attention_heads
|
| 260 |
+
|
| 261 |
+
@property
|
| 262 |
+
def hidden_size(self) -> int:
|
| 263 |
+
return self.d_model
|
llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/feature_extraction_deformable_detr.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Feature extractor class for Deformable DETR."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
|
| 19 |
+
from ...image_transforms import rgb_to_id as _rgb_to_id
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
from .image_processing_deformable_detr import DeformableDetrImageProcessor
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def rgb_to_id(x):
|
| 28 |
+
warnings.warn(
|
| 29 |
+
"rgb_to_id has moved and will not be importable from this module from v5. "
|
| 30 |
+
"Please import from transformers.image_transforms instead.",
|
| 31 |
+
FutureWarning,
|
| 32 |
+
)
|
| 33 |
+
return _rgb_to_id(x)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class DeformableDetrFeatureExtractor(DeformableDetrImageProcessor):
|
| 37 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 38 |
+
warnings.warn(
|
| 39 |
+
"The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers."
|
| 40 |
+
" Please use DeformableDetrImageProcessor instead.",
|
| 41 |
+
FutureWarning,
|
| 42 |
+
)
|
| 43 |
+
super().__init__(*args, **kwargs)
|
llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/image_processing_deformable_detr.py
ADDED
|
@@ -0,0 +1,1429 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 Deformable DETR."""
|
| 16 |
+
|
| 17 |
+
import io
|
| 18 |
+
import pathlib
|
| 19 |
+
from collections import defaultdict
|
| 20 |
+
from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Union
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
from ...feature_extraction_utils import BatchFeature
|
| 25 |
+
from ...image_processing_utils import BaseImageProcessor, get_size_dict
|
| 26 |
+
from ...image_transforms import (
|
| 27 |
+
PaddingMode,
|
| 28 |
+
center_to_corners_format,
|
| 29 |
+
corners_to_center_format,
|
| 30 |
+
id_to_rgb,
|
| 31 |
+
pad,
|
| 32 |
+
rescale,
|
| 33 |
+
resize,
|
| 34 |
+
rgb_to_id,
|
| 35 |
+
to_channel_dimension_format,
|
| 36 |
+
)
|
| 37 |
+
from ...image_utils import (
|
| 38 |
+
IMAGENET_DEFAULT_MEAN,
|
| 39 |
+
IMAGENET_DEFAULT_STD,
|
| 40 |
+
AnnotationFormat,
|
| 41 |
+
AnnotationType,
|
| 42 |
+
ChannelDimension,
|
| 43 |
+
ImageInput,
|
| 44 |
+
PILImageResampling,
|
| 45 |
+
get_image_size,
|
| 46 |
+
infer_channel_dimension_format,
|
| 47 |
+
is_scaled_image,
|
| 48 |
+
make_list_of_images,
|
| 49 |
+
to_numpy_array,
|
| 50 |
+
valid_images,
|
| 51 |
+
validate_annotations,
|
| 52 |
+
)
|
| 53 |
+
from ...utils import (
|
| 54 |
+
TensorType,
|
| 55 |
+
is_flax_available,
|
| 56 |
+
is_jax_tensor,
|
| 57 |
+
is_scipy_available,
|
| 58 |
+
is_tf_available,
|
| 59 |
+
is_tf_tensor,
|
| 60 |
+
is_torch_available,
|
| 61 |
+
is_torch_tensor,
|
| 62 |
+
is_vision_available,
|
| 63 |
+
logging,
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
if is_torch_available():
|
| 68 |
+
import torch
|
| 69 |
+
from torch import nn
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
if is_vision_available():
|
| 73 |
+
import PIL
|
| 74 |
+
|
| 75 |
+
if is_scipy_available():
|
| 76 |
+
import scipy.special
|
| 77 |
+
import scipy.stats
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 81 |
+
|
| 82 |
+
SUPPORTED_ANNOTATION_FORMATS = (AnnotationFormat.COCO_DETECTION, AnnotationFormat.COCO_PANOPTIC)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
# Copied from transformers.models.detr.image_processing_detr.get_size_with_aspect_ratio
|
| 86 |
+
def get_size_with_aspect_ratio(image_size, size, max_size=None) -> Tuple[int, int]:
|
| 87 |
+
"""
|
| 88 |
+
Computes the output image size given the input image size and the desired output size.
|
| 89 |
+
|
| 90 |
+
Args:
|
| 91 |
+
image_size (`Tuple[int, int]`):
|
| 92 |
+
The input image size.
|
| 93 |
+
size (`int`):
|
| 94 |
+
The desired output size.
|
| 95 |
+
max_size (`int`, *optional*):
|
| 96 |
+
The maximum allowed output size.
|
| 97 |
+
"""
|
| 98 |
+
height, width = image_size
|
| 99 |
+
if max_size is not None:
|
| 100 |
+
min_original_size = float(min((height, width)))
|
| 101 |
+
max_original_size = float(max((height, width)))
|
| 102 |
+
if max_original_size / min_original_size * size > max_size:
|
| 103 |
+
size = int(round(max_size * min_original_size / max_original_size))
|
| 104 |
+
|
| 105 |
+
if (height <= width and height == size) or (width <= height and width == size):
|
| 106 |
+
return height, width
|
| 107 |
+
|
| 108 |
+
if width < height:
|
| 109 |
+
ow = size
|
| 110 |
+
oh = int(size * height / width)
|
| 111 |
+
else:
|
| 112 |
+
oh = size
|
| 113 |
+
ow = int(size * width / height)
|
| 114 |
+
return (oh, ow)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
# Copied from transformers.models.detr.image_processing_detr.get_resize_output_image_size
|
| 118 |
+
def get_resize_output_image_size(
|
| 119 |
+
input_image: np.ndarray,
|
| 120 |
+
size: Union[int, Tuple[int, int], List[int]],
|
| 121 |
+
max_size: Optional[int] = None,
|
| 122 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 123 |
+
) -> Tuple[int, int]:
|
| 124 |
+
"""
|
| 125 |
+
Computes the output image size given the input image size and the desired output size. If the desired output size
|
| 126 |
+
is a tuple or list, the output image size is returned as is. If the desired output size is an integer, the output
|
| 127 |
+
image size is computed by keeping the aspect ratio of the input image size.
|
| 128 |
+
|
| 129 |
+
Args:
|
| 130 |
+
input_image (`np.ndarray`):
|
| 131 |
+
The image to resize.
|
| 132 |
+
size (`int` or `Tuple[int, int]` or `List[int]`):
|
| 133 |
+
The desired output size.
|
| 134 |
+
max_size (`int`, *optional*):
|
| 135 |
+
The maximum allowed output size.
|
| 136 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 137 |
+
The channel dimension format of the input image. If not provided, it will be inferred from the input image.
|
| 138 |
+
"""
|
| 139 |
+
image_size = get_image_size(input_image, input_data_format)
|
| 140 |
+
if isinstance(size, (list, tuple)):
|
| 141 |
+
return size
|
| 142 |
+
|
| 143 |
+
return get_size_with_aspect_ratio(image_size, size, max_size)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
# Copied from transformers.models.detr.image_processing_detr.get_numpy_to_framework_fn
|
| 147 |
+
def get_numpy_to_framework_fn(arr) -> Callable:
|
| 148 |
+
"""
|
| 149 |
+
Returns a function that converts a numpy array to the framework of the input array.
|
| 150 |
+
|
| 151 |
+
Args:
|
| 152 |
+
arr (`np.ndarray`): The array to convert.
|
| 153 |
+
"""
|
| 154 |
+
if isinstance(arr, np.ndarray):
|
| 155 |
+
return np.array
|
| 156 |
+
if is_tf_available() and is_tf_tensor(arr):
|
| 157 |
+
import tensorflow as tf
|
| 158 |
+
|
| 159 |
+
return tf.convert_to_tensor
|
| 160 |
+
if is_torch_available() and is_torch_tensor(arr):
|
| 161 |
+
import torch
|
| 162 |
+
|
| 163 |
+
return torch.tensor
|
| 164 |
+
if is_flax_available() and is_jax_tensor(arr):
|
| 165 |
+
import jax.numpy as jnp
|
| 166 |
+
|
| 167 |
+
return jnp.array
|
| 168 |
+
raise ValueError(f"Cannot convert arrays of type {type(arr)}")
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
# Copied from transformers.models.detr.image_processing_detr.safe_squeeze
|
| 172 |
+
def safe_squeeze(arr: np.ndarray, axis: Optional[int] = None) -> np.ndarray:
|
| 173 |
+
"""
|
| 174 |
+
Squeezes an array, but only if the axis specified has dim 1.
|
| 175 |
+
"""
|
| 176 |
+
if axis is None:
|
| 177 |
+
return arr.squeeze()
|
| 178 |
+
|
| 179 |
+
try:
|
| 180 |
+
return arr.squeeze(axis=axis)
|
| 181 |
+
except ValueError:
|
| 182 |
+
return arr
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
# Copied from transformers.models.detr.image_processing_detr.normalize_annotation
|
| 186 |
+
def normalize_annotation(annotation: Dict, image_size: Tuple[int, int]) -> Dict:
|
| 187 |
+
image_height, image_width = image_size
|
| 188 |
+
norm_annotation = {}
|
| 189 |
+
for key, value in annotation.items():
|
| 190 |
+
if key == "boxes":
|
| 191 |
+
boxes = value
|
| 192 |
+
boxes = corners_to_center_format(boxes)
|
| 193 |
+
boxes /= np.asarray([image_width, image_height, image_width, image_height], dtype=np.float32)
|
| 194 |
+
norm_annotation[key] = boxes
|
| 195 |
+
else:
|
| 196 |
+
norm_annotation[key] = value
|
| 197 |
+
return norm_annotation
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# Copied from transformers.models.detr.image_processing_detr.max_across_indices
|
| 201 |
+
def max_across_indices(values: Iterable[Any]) -> List[Any]:
|
| 202 |
+
"""
|
| 203 |
+
Return the maximum value across all indices of an iterable of values.
|
| 204 |
+
"""
|
| 205 |
+
return [max(values_i) for values_i in zip(*values)]
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
# Copied from transformers.models.detr.image_processing_detr.get_max_height_width
|
| 209 |
+
def get_max_height_width(
|
| 210 |
+
images: List[np.ndarray], input_data_format: Optional[Union[str, ChannelDimension]] = None
|
| 211 |
+
) -> List[int]:
|
| 212 |
+
"""
|
| 213 |
+
Get the maximum height and width across all images in a batch.
|
| 214 |
+
"""
|
| 215 |
+
if input_data_format is None:
|
| 216 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 217 |
+
|
| 218 |
+
if input_data_format == ChannelDimension.FIRST:
|
| 219 |
+
_, max_height, max_width = max_across_indices([img.shape for img in images])
|
| 220 |
+
elif input_data_format == ChannelDimension.LAST:
|
| 221 |
+
max_height, max_width, _ = max_across_indices([img.shape for img in images])
|
| 222 |
+
else:
|
| 223 |
+
raise ValueError(f"Invalid channel dimension format: {input_data_format}")
|
| 224 |
+
return (max_height, max_width)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
# Copied from transformers.models.detr.image_processing_detr.make_pixel_mask
|
| 228 |
+
def make_pixel_mask(
|
| 229 |
+
image: np.ndarray, output_size: Tuple[int, int], input_data_format: Optional[Union[str, ChannelDimension]] = None
|
| 230 |
+
) -> np.ndarray:
|
| 231 |
+
"""
|
| 232 |
+
Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
|
| 233 |
+
|
| 234 |
+
Args:
|
| 235 |
+
image (`np.ndarray`):
|
| 236 |
+
Image to make the pixel mask for.
|
| 237 |
+
output_size (`Tuple[int, int]`):
|
| 238 |
+
Output size of the mask.
|
| 239 |
+
"""
|
| 240 |
+
input_height, input_width = get_image_size(image, channel_dim=input_data_format)
|
| 241 |
+
mask = np.zeros(output_size, dtype=np.int64)
|
| 242 |
+
mask[:input_height, :input_width] = 1
|
| 243 |
+
return mask
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
# Copied from transformers.models.detr.image_processing_detr.convert_coco_poly_to_mask
|
| 247 |
+
def convert_coco_poly_to_mask(segmentations, height: int, width: int) -> np.ndarray:
|
| 248 |
+
"""
|
| 249 |
+
Convert a COCO polygon annotation to a mask.
|
| 250 |
+
|
| 251 |
+
Args:
|
| 252 |
+
segmentations (`List[List[float]]`):
|
| 253 |
+
List of polygons, each polygon represented by a list of x-y coordinates.
|
| 254 |
+
height (`int`):
|
| 255 |
+
Height of the mask.
|
| 256 |
+
width (`int`):
|
| 257 |
+
Width of the mask.
|
| 258 |
+
"""
|
| 259 |
+
try:
|
| 260 |
+
from pycocotools import mask as coco_mask
|
| 261 |
+
except ImportError:
|
| 262 |
+
raise ImportError("Pycocotools is not installed in your environment.")
|
| 263 |
+
|
| 264 |
+
masks = []
|
| 265 |
+
for polygons in segmentations:
|
| 266 |
+
rles = coco_mask.frPyObjects(polygons, height, width)
|
| 267 |
+
mask = coco_mask.decode(rles)
|
| 268 |
+
if len(mask.shape) < 3:
|
| 269 |
+
mask = mask[..., None]
|
| 270 |
+
mask = np.asarray(mask, dtype=np.uint8)
|
| 271 |
+
mask = np.any(mask, axis=2)
|
| 272 |
+
masks.append(mask)
|
| 273 |
+
if masks:
|
| 274 |
+
masks = np.stack(masks, axis=0)
|
| 275 |
+
else:
|
| 276 |
+
masks = np.zeros((0, height, width), dtype=np.uint8)
|
| 277 |
+
|
| 278 |
+
return masks
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
# Copied from transformers.models.detr.image_processing_detr.prepare_coco_detection_annotation with DETR->DeformableDetr
|
| 282 |
+
def prepare_coco_detection_annotation(
|
| 283 |
+
image,
|
| 284 |
+
target,
|
| 285 |
+
return_segmentation_masks: bool = False,
|
| 286 |
+
input_data_format: Optional[Union[ChannelDimension, str]] = None,
|
| 287 |
+
):
|
| 288 |
+
"""
|
| 289 |
+
Convert the target in COCO format into the format expected by DeformableDetr.
|
| 290 |
+
"""
|
| 291 |
+
image_height, image_width = get_image_size(image, channel_dim=input_data_format)
|
| 292 |
+
|
| 293 |
+
image_id = target["image_id"]
|
| 294 |
+
image_id = np.asarray([image_id], dtype=np.int64)
|
| 295 |
+
|
| 296 |
+
# Get all COCO annotations for the given image.
|
| 297 |
+
annotations = target["annotations"]
|
| 298 |
+
annotations = [obj for obj in annotations if "iscrowd" not in obj or obj["iscrowd"] == 0]
|
| 299 |
+
|
| 300 |
+
classes = [obj["category_id"] for obj in annotations]
|
| 301 |
+
classes = np.asarray(classes, dtype=np.int64)
|
| 302 |
+
|
| 303 |
+
# for conversion to coco api
|
| 304 |
+
area = np.asarray([obj["area"] for obj in annotations], dtype=np.float32)
|
| 305 |
+
iscrowd = np.asarray([obj["iscrowd"] if "iscrowd" in obj else 0 for obj in annotations], dtype=np.int64)
|
| 306 |
+
|
| 307 |
+
boxes = [obj["bbox"] for obj in annotations]
|
| 308 |
+
# guard against no boxes via resizing
|
| 309 |
+
boxes = np.asarray(boxes, dtype=np.float32).reshape(-1, 4)
|
| 310 |
+
boxes[:, 2:] += boxes[:, :2]
|
| 311 |
+
boxes[:, 0::2] = boxes[:, 0::2].clip(min=0, max=image_width)
|
| 312 |
+
boxes[:, 1::2] = boxes[:, 1::2].clip(min=0, max=image_height)
|
| 313 |
+
|
| 314 |
+
keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])
|
| 315 |
+
|
| 316 |
+
new_target = {}
|
| 317 |
+
new_target["image_id"] = image_id
|
| 318 |
+
new_target["class_labels"] = classes[keep]
|
| 319 |
+
new_target["boxes"] = boxes[keep]
|
| 320 |
+
new_target["area"] = area[keep]
|
| 321 |
+
new_target["iscrowd"] = iscrowd[keep]
|
| 322 |
+
new_target["orig_size"] = np.asarray([int(image_height), int(image_width)], dtype=np.int64)
|
| 323 |
+
|
| 324 |
+
if annotations and "keypoints" in annotations[0]:
|
| 325 |
+
keypoints = [obj["keypoints"] for obj in annotations]
|
| 326 |
+
# Converting the filtered keypoints list to a numpy array
|
| 327 |
+
keypoints = np.asarray(keypoints, dtype=np.float32)
|
| 328 |
+
# Apply the keep mask here to filter the relevant annotations
|
| 329 |
+
keypoints = keypoints[keep]
|
| 330 |
+
num_keypoints = keypoints.shape[0]
|
| 331 |
+
keypoints = keypoints.reshape((-1, 3)) if num_keypoints else keypoints
|
| 332 |
+
new_target["keypoints"] = keypoints
|
| 333 |
+
|
| 334 |
+
if return_segmentation_masks:
|
| 335 |
+
segmentation_masks = [obj["segmentation"] for obj in annotations]
|
| 336 |
+
masks = convert_coco_poly_to_mask(segmentation_masks, image_height, image_width)
|
| 337 |
+
new_target["masks"] = masks[keep]
|
| 338 |
+
|
| 339 |
+
return new_target
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
# Copied from transformers.models.detr.image_processing_detr.masks_to_boxes
|
| 343 |
+
def masks_to_boxes(masks: np.ndarray) -> np.ndarray:
|
| 344 |
+
"""
|
| 345 |
+
Compute the bounding boxes around the provided panoptic segmentation masks.
|
| 346 |
+
|
| 347 |
+
Args:
|
| 348 |
+
masks: masks in format `[number_masks, height, width]` where N is the number of masks
|
| 349 |
+
|
| 350 |
+
Returns:
|
| 351 |
+
boxes: bounding boxes in format `[number_masks, 4]` in xyxy format
|
| 352 |
+
"""
|
| 353 |
+
if masks.size == 0:
|
| 354 |
+
return np.zeros((0, 4))
|
| 355 |
+
|
| 356 |
+
h, w = masks.shape[-2:]
|
| 357 |
+
y = np.arange(0, h, dtype=np.float32)
|
| 358 |
+
x = np.arange(0, w, dtype=np.float32)
|
| 359 |
+
# see https://github.com/pytorch/pytorch/issues/50276
|
| 360 |
+
y, x = np.meshgrid(y, x, indexing="ij")
|
| 361 |
+
|
| 362 |
+
x_mask = masks * np.expand_dims(x, axis=0)
|
| 363 |
+
x_max = x_mask.reshape(x_mask.shape[0], -1).max(-1)
|
| 364 |
+
x = np.ma.array(x_mask, mask=~(np.array(masks, dtype=bool)))
|
| 365 |
+
x_min = x.filled(fill_value=1e8)
|
| 366 |
+
x_min = x_min.reshape(x_min.shape[0], -1).min(-1)
|
| 367 |
+
|
| 368 |
+
y_mask = masks * np.expand_dims(y, axis=0)
|
| 369 |
+
y_max = y_mask.reshape(x_mask.shape[0], -1).max(-1)
|
| 370 |
+
y = np.ma.array(y_mask, mask=~(np.array(masks, dtype=bool)))
|
| 371 |
+
y_min = y.filled(fill_value=1e8)
|
| 372 |
+
y_min = y_min.reshape(y_min.shape[0], -1).min(-1)
|
| 373 |
+
|
| 374 |
+
return np.stack([x_min, y_min, x_max, y_max], 1)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
# Copied from transformers.models.detr.image_processing_detr.prepare_coco_panoptic_annotation with DETR->DeformableDetr
|
| 378 |
+
def prepare_coco_panoptic_annotation(
|
| 379 |
+
image: np.ndarray,
|
| 380 |
+
target: Dict,
|
| 381 |
+
masks_path: Union[str, pathlib.Path],
|
| 382 |
+
return_masks: bool = True,
|
| 383 |
+
input_data_format: Union[ChannelDimension, str] = None,
|
| 384 |
+
) -> Dict:
|
| 385 |
+
"""
|
| 386 |
+
Prepare a coco panoptic annotation for DeformableDetr.
|
| 387 |
+
"""
|
| 388 |
+
image_height, image_width = get_image_size(image, channel_dim=input_data_format)
|
| 389 |
+
annotation_path = pathlib.Path(masks_path) / target["file_name"]
|
| 390 |
+
|
| 391 |
+
new_target = {}
|
| 392 |
+
new_target["image_id"] = np.asarray([target["image_id"] if "image_id" in target else target["id"]], dtype=np.int64)
|
| 393 |
+
new_target["size"] = np.asarray([image_height, image_width], dtype=np.int64)
|
| 394 |
+
new_target["orig_size"] = np.asarray([image_height, image_width], dtype=np.int64)
|
| 395 |
+
|
| 396 |
+
if "segments_info" in target:
|
| 397 |
+
masks = np.asarray(PIL.Image.open(annotation_path), dtype=np.uint32)
|
| 398 |
+
masks = rgb_to_id(masks)
|
| 399 |
+
|
| 400 |
+
ids = np.array([segment_info["id"] for segment_info in target["segments_info"]])
|
| 401 |
+
masks = masks == ids[:, None, None]
|
| 402 |
+
masks = masks.astype(np.uint8)
|
| 403 |
+
if return_masks:
|
| 404 |
+
new_target["masks"] = masks
|
| 405 |
+
new_target["boxes"] = masks_to_boxes(masks)
|
| 406 |
+
new_target["class_labels"] = np.array(
|
| 407 |
+
[segment_info["category_id"] for segment_info in target["segments_info"]], dtype=np.int64
|
| 408 |
+
)
|
| 409 |
+
new_target["iscrowd"] = np.asarray(
|
| 410 |
+
[segment_info["iscrowd"] for segment_info in target["segments_info"]], dtype=np.int64
|
| 411 |
+
)
|
| 412 |
+
new_target["area"] = np.asarray(
|
| 413 |
+
[segment_info["area"] for segment_info in target["segments_info"]], dtype=np.float32
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
return new_target
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
# Copied from transformers.models.detr.image_processing_detr.get_segmentation_image
|
| 420 |
+
def get_segmentation_image(
|
| 421 |
+
masks: np.ndarray, input_size: Tuple, target_size: Tuple, stuff_equiv_classes, deduplicate=False
|
| 422 |
+
):
|
| 423 |
+
h, w = input_size
|
| 424 |
+
final_h, final_w = target_size
|
| 425 |
+
|
| 426 |
+
m_id = scipy.special.softmax(masks.transpose(0, 1), -1)
|
| 427 |
+
|
| 428 |
+
if m_id.shape[-1] == 0:
|
| 429 |
+
# We didn't detect any mask :(
|
| 430 |
+
m_id = np.zeros((h, w), dtype=np.int64)
|
| 431 |
+
else:
|
| 432 |
+
m_id = m_id.argmax(-1).reshape(h, w)
|
| 433 |
+
|
| 434 |
+
if deduplicate:
|
| 435 |
+
# Merge the masks corresponding to the same stuff class
|
| 436 |
+
for equiv in stuff_equiv_classes.values():
|
| 437 |
+
for eq_id in equiv:
|
| 438 |
+
m_id[m_id == eq_id] = equiv[0]
|
| 439 |
+
|
| 440 |
+
seg_img = id_to_rgb(m_id)
|
| 441 |
+
seg_img = resize(seg_img, (final_w, final_h), resample=PILImageResampling.NEAREST)
|
| 442 |
+
return seg_img
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
# Copied from transformers.models.detr.image_processing_detr.get_mask_area
|
| 446 |
+
def get_mask_area(seg_img: np.ndarray, target_size: Tuple[int, int], n_classes: int) -> np.ndarray:
|
| 447 |
+
final_h, final_w = target_size
|
| 448 |
+
np_seg_img = seg_img.astype(np.uint8)
|
| 449 |
+
np_seg_img = np_seg_img.reshape(final_h, final_w, 3)
|
| 450 |
+
m_id = rgb_to_id(np_seg_img)
|
| 451 |
+
area = [(m_id == i).sum() for i in range(n_classes)]
|
| 452 |
+
return area
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
# Copied from transformers.models.detr.image_processing_detr.score_labels_from_class_probabilities
|
| 456 |
+
def score_labels_from_class_probabilities(logits: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
|
| 457 |
+
probs = scipy.special.softmax(logits, axis=-1)
|
| 458 |
+
labels = probs.argmax(-1, keepdims=True)
|
| 459 |
+
scores = np.take_along_axis(probs, labels, axis=-1)
|
| 460 |
+
scores, labels = scores.squeeze(-1), labels.squeeze(-1)
|
| 461 |
+
return scores, labels
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
# Copied from transformers.models.detr.image_processing_detr.post_process_panoptic_sample
|
| 465 |
+
def post_process_panoptic_sample(
|
| 466 |
+
out_logits: np.ndarray,
|
| 467 |
+
masks: np.ndarray,
|
| 468 |
+
boxes: np.ndarray,
|
| 469 |
+
processed_size: Tuple[int, int],
|
| 470 |
+
target_size: Tuple[int, int],
|
| 471 |
+
is_thing_map: Dict,
|
| 472 |
+
threshold=0.85,
|
| 473 |
+
) -> Dict:
|
| 474 |
+
"""
|
| 475 |
+
Converts the output of [`DetrForSegmentation`] into panoptic segmentation predictions for a single sample.
|
| 476 |
+
|
| 477 |
+
Args:
|
| 478 |
+
out_logits (`torch.Tensor`):
|
| 479 |
+
The logits for this sample.
|
| 480 |
+
masks (`torch.Tensor`):
|
| 481 |
+
The predicted segmentation masks for this sample.
|
| 482 |
+
boxes (`torch.Tensor`):
|
| 483 |
+
The prediced bounding boxes for this sample. The boxes are in the normalized format `(center_x, center_y,
|
| 484 |
+
width, height)` and values between `[0, 1]`, relative to the size the image (disregarding padding).
|
| 485 |
+
processed_size (`Tuple[int, int]`):
|
| 486 |
+
The processed size of the image `(height, width)`, as returned by the preprocessing step i.e. the size
|
| 487 |
+
after data augmentation but before batching.
|
| 488 |
+
target_size (`Tuple[int, int]`):
|
| 489 |
+
The target size of the image, `(height, width)` corresponding to the requested final size of the
|
| 490 |
+
prediction.
|
| 491 |
+
is_thing_map (`Dict`):
|
| 492 |
+
A dictionary mapping class indices to a boolean value indicating whether the class is a thing or not.
|
| 493 |
+
threshold (`float`, *optional*, defaults to 0.85):
|
| 494 |
+
The threshold used to binarize the segmentation masks.
|
| 495 |
+
"""
|
| 496 |
+
# we filter empty queries and detection below threshold
|
| 497 |
+
scores, labels = score_labels_from_class_probabilities(out_logits)
|
| 498 |
+
keep = (labels != out_logits.shape[-1] - 1) & (scores > threshold)
|
| 499 |
+
|
| 500 |
+
cur_scores = scores[keep]
|
| 501 |
+
cur_classes = labels[keep]
|
| 502 |
+
cur_boxes = center_to_corners_format(boxes[keep])
|
| 503 |
+
|
| 504 |
+
if len(cur_boxes) != len(cur_classes):
|
| 505 |
+
raise ValueError("Not as many boxes as there are classes")
|
| 506 |
+
|
| 507 |
+
cur_masks = masks[keep]
|
| 508 |
+
cur_masks = resize(cur_masks[:, None], processed_size, resample=PILImageResampling.BILINEAR)
|
| 509 |
+
cur_masks = safe_squeeze(cur_masks, 1)
|
| 510 |
+
b, h, w = cur_masks.shape
|
| 511 |
+
|
| 512 |
+
# It may be that we have several predicted masks for the same stuff class.
|
| 513 |
+
# In the following, we track the list of masks ids for each stuff class (they are merged later on)
|
| 514 |
+
cur_masks = cur_masks.reshape(b, -1)
|
| 515 |
+
stuff_equiv_classes = defaultdict(list)
|
| 516 |
+
for k, label in enumerate(cur_classes):
|
| 517 |
+
if not is_thing_map[label]:
|
| 518 |
+
stuff_equiv_classes[label].append(k)
|
| 519 |
+
|
| 520 |
+
seg_img = get_segmentation_image(cur_masks, processed_size, target_size, stuff_equiv_classes, deduplicate=True)
|
| 521 |
+
area = get_mask_area(cur_masks, processed_size, n_classes=len(cur_scores))
|
| 522 |
+
|
| 523 |
+
# We filter out any mask that is too small
|
| 524 |
+
if cur_classes.size() > 0:
|
| 525 |
+
# We know filter empty masks as long as we find some
|
| 526 |
+
filtered_small = np.array([a <= 4 for a in area], dtype=bool)
|
| 527 |
+
while filtered_small.any():
|
| 528 |
+
cur_masks = cur_masks[~filtered_small]
|
| 529 |
+
cur_scores = cur_scores[~filtered_small]
|
| 530 |
+
cur_classes = cur_classes[~filtered_small]
|
| 531 |
+
seg_img = get_segmentation_image(cur_masks, (h, w), target_size, stuff_equiv_classes, deduplicate=True)
|
| 532 |
+
area = get_mask_area(seg_img, target_size, n_classes=len(cur_scores))
|
| 533 |
+
filtered_small = np.array([a <= 4 for a in area], dtype=bool)
|
| 534 |
+
else:
|
| 535 |
+
cur_classes = np.ones((1, 1), dtype=np.int64)
|
| 536 |
+
|
| 537 |
+
segments_info = [
|
| 538 |
+
{"id": i, "isthing": is_thing_map[cat], "category_id": int(cat), "area": a}
|
| 539 |
+
for i, (cat, a) in enumerate(zip(cur_classes, area))
|
| 540 |
+
]
|
| 541 |
+
del cur_classes
|
| 542 |
+
|
| 543 |
+
with io.BytesIO() as out:
|
| 544 |
+
PIL.Image.fromarray(seg_img).save(out, format="PNG")
|
| 545 |
+
predictions = {"png_string": out.getvalue(), "segments_info": segments_info}
|
| 546 |
+
|
| 547 |
+
return predictions
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
# Copied from transformers.models.detr.image_processing_detr.resize_annotation
|
| 551 |
+
def resize_annotation(
|
| 552 |
+
annotation: Dict[str, Any],
|
| 553 |
+
orig_size: Tuple[int, int],
|
| 554 |
+
target_size: Tuple[int, int],
|
| 555 |
+
threshold: float = 0.5,
|
| 556 |
+
resample: PILImageResampling = PILImageResampling.NEAREST,
|
| 557 |
+
):
|
| 558 |
+
"""
|
| 559 |
+
Resizes an annotation to a target size.
|
| 560 |
+
|
| 561 |
+
Args:
|
| 562 |
+
annotation (`Dict[str, Any]`):
|
| 563 |
+
The annotation dictionary.
|
| 564 |
+
orig_size (`Tuple[int, int]`):
|
| 565 |
+
The original size of the input image.
|
| 566 |
+
target_size (`Tuple[int, int]`):
|
| 567 |
+
The target size of the image, as returned by the preprocessing `resize` step.
|
| 568 |
+
threshold (`float`, *optional*, defaults to 0.5):
|
| 569 |
+
The threshold used to binarize the segmentation masks.
|
| 570 |
+
resample (`PILImageResampling`, defaults to `PILImageResampling.NEAREST`):
|
| 571 |
+
The resampling filter to use when resizing the masks.
|
| 572 |
+
"""
|
| 573 |
+
ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(target_size, orig_size))
|
| 574 |
+
ratio_height, ratio_width = ratios
|
| 575 |
+
|
| 576 |
+
new_annotation = {}
|
| 577 |
+
new_annotation["size"] = target_size
|
| 578 |
+
|
| 579 |
+
for key, value in annotation.items():
|
| 580 |
+
if key == "boxes":
|
| 581 |
+
boxes = value
|
| 582 |
+
scaled_boxes = boxes * np.asarray([ratio_width, ratio_height, ratio_width, ratio_height], dtype=np.float32)
|
| 583 |
+
new_annotation["boxes"] = scaled_boxes
|
| 584 |
+
elif key == "area":
|
| 585 |
+
area = value
|
| 586 |
+
scaled_area = area * (ratio_width * ratio_height)
|
| 587 |
+
new_annotation["area"] = scaled_area
|
| 588 |
+
elif key == "masks":
|
| 589 |
+
masks = value[:, None]
|
| 590 |
+
masks = np.array([resize(mask, target_size, resample=resample) for mask in masks])
|
| 591 |
+
masks = masks.astype(np.float32)
|
| 592 |
+
masks = masks[:, 0] > threshold
|
| 593 |
+
new_annotation["masks"] = masks
|
| 594 |
+
elif key == "size":
|
| 595 |
+
new_annotation["size"] = target_size
|
| 596 |
+
else:
|
| 597 |
+
new_annotation[key] = value
|
| 598 |
+
|
| 599 |
+
return new_annotation
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
# Copied from transformers.models.detr.image_processing_detr.binary_mask_to_rle
|
| 603 |
+
def binary_mask_to_rle(mask):
|
| 604 |
+
"""
|
| 605 |
+
Converts given binary mask of shape `(height, width)` to the run-length encoding (RLE) format.
|
| 606 |
+
|
| 607 |
+
Args:
|
| 608 |
+
mask (`torch.Tensor` or `numpy.array`):
|
| 609 |
+
A binary mask tensor of shape `(height, width)` where 0 denotes background and 1 denotes the target
|
| 610 |
+
segment_id or class_id.
|
| 611 |
+
Returns:
|
| 612 |
+
`List`: Run-length encoded list of the binary mask. Refer to COCO API for more information about the RLE
|
| 613 |
+
format.
|
| 614 |
+
"""
|
| 615 |
+
if is_torch_tensor(mask):
|
| 616 |
+
mask = mask.numpy()
|
| 617 |
+
|
| 618 |
+
pixels = mask.flatten()
|
| 619 |
+
pixels = np.concatenate([[0], pixels, [0]])
|
| 620 |
+
runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
|
| 621 |
+
runs[1::2] -= runs[::2]
|
| 622 |
+
return list(runs)
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
# Copied from transformers.models.detr.image_processing_detr.convert_segmentation_to_rle
|
| 626 |
+
def convert_segmentation_to_rle(segmentation):
|
| 627 |
+
"""
|
| 628 |
+
Converts given segmentation map of shape `(height, width)` to the run-length encoding (RLE) format.
|
| 629 |
+
|
| 630 |
+
Args:
|
| 631 |
+
segmentation (`torch.Tensor` or `numpy.array`):
|
| 632 |
+
A segmentation map of shape `(height, width)` where each value denotes a segment or class id.
|
| 633 |
+
Returns:
|
| 634 |
+
`List[List]`: A list of lists, where each list is the run-length encoding of a segment / class id.
|
| 635 |
+
"""
|
| 636 |
+
segment_ids = torch.unique(segmentation)
|
| 637 |
+
|
| 638 |
+
run_length_encodings = []
|
| 639 |
+
for idx in segment_ids:
|
| 640 |
+
mask = torch.where(segmentation == idx, 1, 0)
|
| 641 |
+
rle = binary_mask_to_rle(mask)
|
| 642 |
+
run_length_encodings.append(rle)
|
| 643 |
+
|
| 644 |
+
return run_length_encodings
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
# Copied from transformers.models.detr.image_processing_detr.remove_low_and_no_objects
|
| 648 |
+
def remove_low_and_no_objects(masks, scores, labels, object_mask_threshold, num_labels):
|
| 649 |
+
"""
|
| 650 |
+
Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and
|
| 651 |
+
`labels`.
|
| 652 |
+
|
| 653 |
+
Args:
|
| 654 |
+
masks (`torch.Tensor`):
|
| 655 |
+
A tensor of shape `(num_queries, height, width)`.
|
| 656 |
+
scores (`torch.Tensor`):
|
| 657 |
+
A tensor of shape `(num_queries)`.
|
| 658 |
+
labels (`torch.Tensor`):
|
| 659 |
+
A tensor of shape `(num_queries)`.
|
| 660 |
+
object_mask_threshold (`float`):
|
| 661 |
+
A number between 0 and 1 used to binarize the masks.
|
| 662 |
+
Raises:
|
| 663 |
+
`ValueError`: Raised when the first dimension doesn't match in all input tensors.
|
| 664 |
+
Returns:
|
| 665 |
+
`Tuple[`torch.Tensor`, `torch.Tensor`, `torch.Tensor`]`: The `masks`, `scores` and `labels` without the region
|
| 666 |
+
< `object_mask_threshold`.
|
| 667 |
+
"""
|
| 668 |
+
if not (masks.shape[0] == scores.shape[0] == labels.shape[0]):
|
| 669 |
+
raise ValueError("mask, scores and labels must have the same shape!")
|
| 670 |
+
|
| 671 |
+
to_keep = labels.ne(num_labels) & (scores > object_mask_threshold)
|
| 672 |
+
|
| 673 |
+
return masks[to_keep], scores[to_keep], labels[to_keep]
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
# Copied from transformers.models.detr.image_processing_detr.check_segment_validity
|
| 677 |
+
def check_segment_validity(mask_labels, mask_probs, k, mask_threshold=0.5, overlap_mask_area_threshold=0.8):
|
| 678 |
+
# Get the mask associated with the k class
|
| 679 |
+
mask_k = mask_labels == k
|
| 680 |
+
mask_k_area = mask_k.sum()
|
| 681 |
+
|
| 682 |
+
# Compute the area of all the stuff in query k
|
| 683 |
+
original_area = (mask_probs[k] >= mask_threshold).sum()
|
| 684 |
+
mask_exists = mask_k_area > 0 and original_area > 0
|
| 685 |
+
|
| 686 |
+
# Eliminate disconnected tiny segments
|
| 687 |
+
if mask_exists:
|
| 688 |
+
area_ratio = mask_k_area / original_area
|
| 689 |
+
if not area_ratio.item() > overlap_mask_area_threshold:
|
| 690 |
+
mask_exists = False
|
| 691 |
+
|
| 692 |
+
return mask_exists, mask_k
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
# Copied from transformers.models.detr.image_processing_detr.compute_segments
|
| 696 |
+
def compute_segments(
|
| 697 |
+
mask_probs,
|
| 698 |
+
pred_scores,
|
| 699 |
+
pred_labels,
|
| 700 |
+
mask_threshold: float = 0.5,
|
| 701 |
+
overlap_mask_area_threshold: float = 0.8,
|
| 702 |
+
label_ids_to_fuse: Optional[Set[int]] = None,
|
| 703 |
+
target_size: Tuple[int, int] = None,
|
| 704 |
+
):
|
| 705 |
+
height = mask_probs.shape[1] if target_size is None else target_size[0]
|
| 706 |
+
width = mask_probs.shape[2] if target_size is None else target_size[1]
|
| 707 |
+
|
| 708 |
+
segmentation = torch.zeros((height, width), dtype=torch.int32, device=mask_probs.device)
|
| 709 |
+
segments: List[Dict] = []
|
| 710 |
+
|
| 711 |
+
if target_size is not None:
|
| 712 |
+
mask_probs = nn.functional.interpolate(
|
| 713 |
+
mask_probs.unsqueeze(0), size=target_size, mode="bilinear", align_corners=False
|
| 714 |
+
)[0]
|
| 715 |
+
|
| 716 |
+
current_segment_id = 0
|
| 717 |
+
|
| 718 |
+
# Weigh each mask by its prediction score
|
| 719 |
+
mask_probs *= pred_scores.view(-1, 1, 1)
|
| 720 |
+
mask_labels = mask_probs.argmax(0) # [height, width]
|
| 721 |
+
|
| 722 |
+
# Keep track of instances of each class
|
| 723 |
+
stuff_memory_list: Dict[str, int] = {}
|
| 724 |
+
for k in range(pred_labels.shape[0]):
|
| 725 |
+
pred_class = pred_labels[k].item()
|
| 726 |
+
should_fuse = pred_class in label_ids_to_fuse
|
| 727 |
+
|
| 728 |
+
# Check if mask exists and large enough to be a segment
|
| 729 |
+
mask_exists, mask_k = check_segment_validity(
|
| 730 |
+
mask_labels, mask_probs, k, mask_threshold, overlap_mask_area_threshold
|
| 731 |
+
)
|
| 732 |
+
|
| 733 |
+
if mask_exists:
|
| 734 |
+
if pred_class in stuff_memory_list:
|
| 735 |
+
current_segment_id = stuff_memory_list[pred_class]
|
| 736 |
+
else:
|
| 737 |
+
current_segment_id += 1
|
| 738 |
+
|
| 739 |
+
# Add current object segment to final segmentation map
|
| 740 |
+
segmentation[mask_k] = current_segment_id
|
| 741 |
+
segment_score = round(pred_scores[k].item(), 6)
|
| 742 |
+
segments.append(
|
| 743 |
+
{
|
| 744 |
+
"id": current_segment_id,
|
| 745 |
+
"label_id": pred_class,
|
| 746 |
+
"was_fused": should_fuse,
|
| 747 |
+
"score": segment_score,
|
| 748 |
+
}
|
| 749 |
+
)
|
| 750 |
+
if should_fuse:
|
| 751 |
+
stuff_memory_list[pred_class] = current_segment_id
|
| 752 |
+
|
| 753 |
+
return segmentation, segments
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
class DeformableDetrImageProcessor(BaseImageProcessor):
|
| 757 |
+
r"""
|
| 758 |
+
Constructs a Deformable DETR image processor.
|
| 759 |
+
|
| 760 |
+
Args:
|
| 761 |
+
format (`str`, *optional*, defaults to `"coco_detection"`):
|
| 762 |
+
Data format of the annotations. One of "coco_detection" or "coco_panoptic".
|
| 763 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 764 |
+
Controls whether to resize the image's (height, width) dimensions to the specified `size`. Can be
|
| 765 |
+
overridden by the `do_resize` parameter in the `preprocess` method.
|
| 766 |
+
size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 800, "longest_edge": 1333}`):
|
| 767 |
+
Size of the image's (height, width) dimensions after resizing. Can be overridden by the `size` parameter in
|
| 768 |
+
the `preprocess` method.
|
| 769 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
|
| 770 |
+
Resampling filter to use if resizing the image.
|
| 771 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 772 |
+
Controls whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
|
| 773 |
+
`do_rescale` parameter in the `preprocess` method.
|
| 774 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
| 775 |
+
Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
|
| 776 |
+
`preprocess` method.
|
| 777 |
+
do_normalize:
|
| 778 |
+
Controls whether to normalize the image. Can be overridden by the `do_normalize` parameter in the
|
| 779 |
+
`preprocess` method.
|
| 780 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_MEAN`):
|
| 781 |
+
Mean values to use when normalizing the image. Can be a single value or a list of values, one for each
|
| 782 |
+
channel. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
| 783 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_STD`):
|
| 784 |
+
Standard deviation values to use when normalizing the image. Can be a single value or a list of values, one
|
| 785 |
+
for each channel. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 786 |
+
do_pad (`bool`, *optional*, defaults to `True`):
|
| 787 |
+
Controls whether to pad the image to the largest image in a batch and create a pixel mask. Can be
|
| 788 |
+
overridden by the `do_pad` parameter in the `preprocess` method.
|
| 789 |
+
"""
|
| 790 |
+
|
| 791 |
+
model_input_names = ["pixel_values", "pixel_mask"]
|
| 792 |
+
|
| 793 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.__init__
|
| 794 |
+
def __init__(
|
| 795 |
+
self,
|
| 796 |
+
format: Union[str, AnnotationFormat] = AnnotationFormat.COCO_DETECTION,
|
| 797 |
+
do_resize: bool = True,
|
| 798 |
+
size: Dict[str, int] = None,
|
| 799 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 800 |
+
do_rescale: bool = True,
|
| 801 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 802 |
+
do_normalize: bool = True,
|
| 803 |
+
image_mean: Union[float, List[float]] = None,
|
| 804 |
+
image_std: Union[float, List[float]] = None,
|
| 805 |
+
do_pad: bool = True,
|
| 806 |
+
**kwargs,
|
| 807 |
+
) -> None:
|
| 808 |
+
if "pad_and_return_pixel_mask" in kwargs:
|
| 809 |
+
do_pad = kwargs.pop("pad_and_return_pixel_mask")
|
| 810 |
+
|
| 811 |
+
if "max_size" in kwargs:
|
| 812 |
+
logger.warning_once(
|
| 813 |
+
"The `max_size` parameter is deprecated and will be removed in v4.26. "
|
| 814 |
+
"Please specify in `size['longest_edge'] instead`.",
|
| 815 |
+
)
|
| 816 |
+
max_size = kwargs.pop("max_size")
|
| 817 |
+
else:
|
| 818 |
+
max_size = None if size is None else 1333
|
| 819 |
+
|
| 820 |
+
size = size if size is not None else {"shortest_edge": 800, "longest_edge": 1333}
|
| 821 |
+
size = get_size_dict(size, max_size=max_size, default_to_square=False)
|
| 822 |
+
|
| 823 |
+
super().__init__(**kwargs)
|
| 824 |
+
self.format = format
|
| 825 |
+
self.do_resize = do_resize
|
| 826 |
+
self.size = size
|
| 827 |
+
self.resample = resample
|
| 828 |
+
self.do_rescale = do_rescale
|
| 829 |
+
self.rescale_factor = rescale_factor
|
| 830 |
+
self.do_normalize = do_normalize
|
| 831 |
+
self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
|
| 832 |
+
self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
|
| 833 |
+
self.do_pad = do_pad
|
| 834 |
+
|
| 835 |
+
@classmethod
|
| 836 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.from_dict with Detr->DeformableDetr
|
| 837 |
+
def from_dict(cls, image_processor_dict: Dict[str, Any], **kwargs):
|
| 838 |
+
"""
|
| 839 |
+
Overrides the `from_dict` method from the base class to make sure parameters are updated if image processor is
|
| 840 |
+
created using from_dict and kwargs e.g. `DeformableDetrImageProcessor.from_pretrained(checkpoint, size=600,
|
| 841 |
+
max_size=800)`
|
| 842 |
+
"""
|
| 843 |
+
image_processor_dict = image_processor_dict.copy()
|
| 844 |
+
if "max_size" in kwargs:
|
| 845 |
+
image_processor_dict["max_size"] = kwargs.pop("max_size")
|
| 846 |
+
if "pad_and_return_pixel_mask" in kwargs:
|
| 847 |
+
image_processor_dict["pad_and_return_pixel_mask"] = kwargs.pop("pad_and_return_pixel_mask")
|
| 848 |
+
return super().from_dict(image_processor_dict, **kwargs)
|
| 849 |
+
|
| 850 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.prepare_annotation with DETR->DeformableDetr
|
| 851 |
+
def prepare_annotation(
|
| 852 |
+
self,
|
| 853 |
+
image: np.ndarray,
|
| 854 |
+
target: Dict,
|
| 855 |
+
format: Optional[AnnotationFormat] = None,
|
| 856 |
+
return_segmentation_masks: bool = None,
|
| 857 |
+
masks_path: Optional[Union[str, pathlib.Path]] = None,
|
| 858 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 859 |
+
) -> Dict:
|
| 860 |
+
"""
|
| 861 |
+
Prepare an annotation for feeding into DeformableDetr model.
|
| 862 |
+
"""
|
| 863 |
+
format = format if format is not None else self.format
|
| 864 |
+
|
| 865 |
+
if format == AnnotationFormat.COCO_DETECTION:
|
| 866 |
+
return_segmentation_masks = False if return_segmentation_masks is None else return_segmentation_masks
|
| 867 |
+
target = prepare_coco_detection_annotation(
|
| 868 |
+
image, target, return_segmentation_masks, input_data_format=input_data_format
|
| 869 |
+
)
|
| 870 |
+
elif format == AnnotationFormat.COCO_PANOPTIC:
|
| 871 |
+
return_segmentation_masks = True if return_segmentation_masks is None else return_segmentation_masks
|
| 872 |
+
target = prepare_coco_panoptic_annotation(
|
| 873 |
+
image,
|
| 874 |
+
target,
|
| 875 |
+
masks_path=masks_path,
|
| 876 |
+
return_masks=return_segmentation_masks,
|
| 877 |
+
input_data_format=input_data_format,
|
| 878 |
+
)
|
| 879 |
+
else:
|
| 880 |
+
raise ValueError(f"Format {format} is not supported.")
|
| 881 |
+
return target
|
| 882 |
+
|
| 883 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.prepare
|
| 884 |
+
def prepare(self, image, target, return_segmentation_masks=None, masks_path=None):
|
| 885 |
+
logger.warning_once(
|
| 886 |
+
"The `prepare` method is deprecated and will be removed in a v4.33. "
|
| 887 |
+
"Please use `prepare_annotation` instead. Note: the `prepare_annotation` method "
|
| 888 |
+
"does not return the image anymore.",
|
| 889 |
+
)
|
| 890 |
+
target = self.prepare_annotation(image, target, return_segmentation_masks, masks_path, self.format)
|
| 891 |
+
return image, target
|
| 892 |
+
|
| 893 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.convert_coco_poly_to_mask
|
| 894 |
+
def convert_coco_poly_to_mask(self, *args, **kwargs):
|
| 895 |
+
logger.warning_once("The `convert_coco_poly_to_mask` method is deprecated and will be removed in v4.33. ")
|
| 896 |
+
return convert_coco_poly_to_mask(*args, **kwargs)
|
| 897 |
+
|
| 898 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.prepare_coco_detection
|
| 899 |
+
def prepare_coco_detection(self, *args, **kwargs):
|
| 900 |
+
logger.warning_once("The `prepare_coco_detection` method is deprecated and will be removed in v4.33. ")
|
| 901 |
+
return prepare_coco_detection_annotation(*args, **kwargs)
|
| 902 |
+
|
| 903 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.prepare_coco_panoptic
|
| 904 |
+
def prepare_coco_panoptic(self, *args, **kwargs):
|
| 905 |
+
logger.warning_once("The `prepare_coco_panoptic` method is deprecated and will be removed in v4.33. ")
|
| 906 |
+
return prepare_coco_panoptic_annotation(*args, **kwargs)
|
| 907 |
+
|
| 908 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.resize
|
| 909 |
+
def resize(
|
| 910 |
+
self,
|
| 911 |
+
image: np.ndarray,
|
| 912 |
+
size: Dict[str, int],
|
| 913 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 914 |
+
data_format: Optional[ChannelDimension] = None,
|
| 915 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 916 |
+
**kwargs,
|
| 917 |
+
) -> np.ndarray:
|
| 918 |
+
"""
|
| 919 |
+
Resize the image to the given size. Size can be `min_size` (scalar) or `(height, width)` tuple. If size is an
|
| 920 |
+
int, smaller edge of the image will be matched to this number.
|
| 921 |
+
|
| 922 |
+
Args:
|
| 923 |
+
image (`np.ndarray`):
|
| 924 |
+
Image to resize.
|
| 925 |
+
size (`Dict[str, int]`):
|
| 926 |
+
Dictionary containing the size to resize to. Can contain the keys `shortest_edge` and `longest_edge` or
|
| 927 |
+
`height` and `width`.
|
| 928 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
|
| 929 |
+
Resampling filter to use if resizing the image.
|
| 930 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 931 |
+
The channel dimension format for the output image. If unset, the channel dimension format of the input
|
| 932 |
+
image is used.
|
| 933 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 934 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 935 |
+
"""
|
| 936 |
+
if "max_size" in kwargs:
|
| 937 |
+
logger.warning_once(
|
| 938 |
+
"The `max_size` parameter is deprecated and will be removed in v4.26. "
|
| 939 |
+
"Please specify in `size['longest_edge'] instead`.",
|
| 940 |
+
)
|
| 941 |
+
max_size = kwargs.pop("max_size")
|
| 942 |
+
else:
|
| 943 |
+
max_size = None
|
| 944 |
+
size = get_size_dict(size, max_size=max_size, default_to_square=False)
|
| 945 |
+
if "shortest_edge" in size and "longest_edge" in size:
|
| 946 |
+
size = get_resize_output_image_size(
|
| 947 |
+
image, size["shortest_edge"], size["longest_edge"], input_data_format=input_data_format
|
| 948 |
+
)
|
| 949 |
+
elif "height" in size and "width" in size:
|
| 950 |
+
size = (size["height"], size["width"])
|
| 951 |
+
else:
|
| 952 |
+
raise ValueError(
|
| 953 |
+
"Size must contain 'height' and 'width' keys or 'shortest_edge' and 'longest_edge' keys. Got"
|
| 954 |
+
f" {size.keys()}."
|
| 955 |
+
)
|
| 956 |
+
image = resize(
|
| 957 |
+
image, size=size, resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs
|
| 958 |
+
)
|
| 959 |
+
return image
|
| 960 |
+
|
| 961 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.resize_annotation
|
| 962 |
+
def resize_annotation(
|
| 963 |
+
self,
|
| 964 |
+
annotation,
|
| 965 |
+
orig_size,
|
| 966 |
+
size,
|
| 967 |
+
resample: PILImageResampling = PILImageResampling.NEAREST,
|
| 968 |
+
) -> Dict:
|
| 969 |
+
"""
|
| 970 |
+
Resize the annotation to match the resized image. If size is an int, smaller edge of the mask will be matched
|
| 971 |
+
to this number.
|
| 972 |
+
"""
|
| 973 |
+
return resize_annotation(annotation, orig_size=orig_size, target_size=size, resample=resample)
|
| 974 |
+
|
| 975 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.rescale
|
| 976 |
+
def rescale(
|
| 977 |
+
self,
|
| 978 |
+
image: np.ndarray,
|
| 979 |
+
rescale_factor: float,
|
| 980 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 981 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 982 |
+
) -> np.ndarray:
|
| 983 |
+
"""
|
| 984 |
+
Rescale the image by the given factor. image = image * rescale_factor.
|
| 985 |
+
|
| 986 |
+
Args:
|
| 987 |
+
image (`np.ndarray`):
|
| 988 |
+
Image to rescale.
|
| 989 |
+
rescale_factor (`float`):
|
| 990 |
+
The value to use for rescaling.
|
| 991 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 992 |
+
The channel dimension format for the output image. If unset, the channel dimension format of the input
|
| 993 |
+
image is used. Can be one of:
|
| 994 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 995 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 996 |
+
input_data_format (`str` or `ChannelDimension`, *optional*):
|
| 997 |
+
The channel dimension format for the input image. If unset, is inferred from the input image. Can be
|
| 998 |
+
one of:
|
| 999 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 1000 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 1001 |
+
"""
|
| 1002 |
+
return rescale(image, rescale_factor, data_format=data_format, input_data_format=input_data_format)
|
| 1003 |
+
|
| 1004 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.normalize_annotation
|
| 1005 |
+
def normalize_annotation(self, annotation: Dict, image_size: Tuple[int, int]) -> Dict:
|
| 1006 |
+
"""
|
| 1007 |
+
Normalize the boxes in the annotation from `[top_left_x, top_left_y, bottom_right_x, bottom_right_y]` to
|
| 1008 |
+
`[center_x, center_y, width, height]` format.
|
| 1009 |
+
"""
|
| 1010 |
+
return normalize_annotation(annotation, image_size=image_size)
|
| 1011 |
+
|
| 1012 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor._pad_image
|
| 1013 |
+
def _pad_image(
|
| 1014 |
+
self,
|
| 1015 |
+
image: np.ndarray,
|
| 1016 |
+
output_size: Tuple[int, int],
|
| 1017 |
+
constant_values: Union[float, Iterable[float]] = 0,
|
| 1018 |
+
data_format: Optional[ChannelDimension] = None,
|
| 1019 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 1020 |
+
) -> np.ndarray:
|
| 1021 |
+
"""
|
| 1022 |
+
Pad an image with zeros to the given size.
|
| 1023 |
+
"""
|
| 1024 |
+
input_height, input_width = get_image_size(image, channel_dim=input_data_format)
|
| 1025 |
+
output_height, output_width = output_size
|
| 1026 |
+
|
| 1027 |
+
pad_bottom = output_height - input_height
|
| 1028 |
+
pad_right = output_width - input_width
|
| 1029 |
+
padding = ((0, pad_bottom), (0, pad_right))
|
| 1030 |
+
padded_image = pad(
|
| 1031 |
+
image,
|
| 1032 |
+
padding,
|
| 1033 |
+
mode=PaddingMode.CONSTANT,
|
| 1034 |
+
constant_values=constant_values,
|
| 1035 |
+
data_format=data_format,
|
| 1036 |
+
input_data_format=input_data_format,
|
| 1037 |
+
)
|
| 1038 |
+
return padded_image
|
| 1039 |
+
|
| 1040 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.pad
|
| 1041 |
+
def pad(
|
| 1042 |
+
self,
|
| 1043 |
+
images: List[np.ndarray],
|
| 1044 |
+
constant_values: Union[float, Iterable[float]] = 0,
|
| 1045 |
+
return_pixel_mask: bool = True,
|
| 1046 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 1047 |
+
data_format: Optional[ChannelDimension] = None,
|
| 1048 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 1049 |
+
) -> BatchFeature:
|
| 1050 |
+
"""
|
| 1051 |
+
Pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width
|
| 1052 |
+
in the batch and optionally returns their corresponding pixel mask.
|
| 1053 |
+
|
| 1054 |
+
Args:
|
| 1055 |
+
image (`np.ndarray`):
|
| 1056 |
+
Image to pad.
|
| 1057 |
+
constant_values (`float` or `Iterable[float]`, *optional*):
|
| 1058 |
+
The value to use for the padding if `mode` is `"constant"`.
|
| 1059 |
+
return_pixel_mask (`bool`, *optional*, defaults to `True`):
|
| 1060 |
+
Whether to return a pixel mask.
|
| 1061 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 1062 |
+
The type of tensors to return. Can be one of:
|
| 1063 |
+
- Unset: Return a list of `np.ndarray`.
|
| 1064 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 1065 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 1066 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 1067 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 1068 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 1069 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
| 1070 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 1071 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 1072 |
+
"""
|
| 1073 |
+
pad_size = get_max_height_width(images, input_data_format=input_data_format)
|
| 1074 |
+
|
| 1075 |
+
padded_images = [
|
| 1076 |
+
self._pad_image(
|
| 1077 |
+
image,
|
| 1078 |
+
pad_size,
|
| 1079 |
+
constant_values=constant_values,
|
| 1080 |
+
data_format=data_format,
|
| 1081 |
+
input_data_format=input_data_format,
|
| 1082 |
+
)
|
| 1083 |
+
for image in images
|
| 1084 |
+
]
|
| 1085 |
+
data = {"pixel_values": padded_images}
|
| 1086 |
+
|
| 1087 |
+
if return_pixel_mask:
|
| 1088 |
+
masks = [
|
| 1089 |
+
make_pixel_mask(image=image, output_size=pad_size, input_data_format=input_data_format)
|
| 1090 |
+
for image in images
|
| 1091 |
+
]
|
| 1092 |
+
data["pixel_mask"] = masks
|
| 1093 |
+
|
| 1094 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 1095 |
+
|
| 1096 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.preprocess
|
| 1097 |
+
def preprocess(
|
| 1098 |
+
self,
|
| 1099 |
+
images: ImageInput,
|
| 1100 |
+
annotations: Optional[Union[AnnotationType, List[AnnotationType]]] = None,
|
| 1101 |
+
return_segmentation_masks: bool = None,
|
| 1102 |
+
masks_path: Optional[Union[str, pathlib.Path]] = None,
|
| 1103 |
+
do_resize: Optional[bool] = None,
|
| 1104 |
+
size: Optional[Dict[str, int]] = None,
|
| 1105 |
+
resample=None, # PILImageResampling
|
| 1106 |
+
do_rescale: Optional[bool] = None,
|
| 1107 |
+
rescale_factor: Optional[Union[int, float]] = None,
|
| 1108 |
+
do_normalize: Optional[bool] = None,
|
| 1109 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 1110 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 1111 |
+
do_pad: Optional[bool] = None,
|
| 1112 |
+
format: Optional[Union[str, AnnotationFormat]] = None,
|
| 1113 |
+
return_tensors: Optional[Union[TensorType, str]] = None,
|
| 1114 |
+
data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
|
| 1115 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 1116 |
+
**kwargs,
|
| 1117 |
+
) -> BatchFeature:
|
| 1118 |
+
"""
|
| 1119 |
+
Preprocess an image or a batch of images so that it can be used by the model.
|
| 1120 |
+
|
| 1121 |
+
Args:
|
| 1122 |
+
images (`ImageInput`):
|
| 1123 |
+
Image or batch of images to preprocess. Expects a single or batch of images with pixel values ranging
|
| 1124 |
+
from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 1125 |
+
annotations (`AnnotationType` or `List[AnnotationType]`, *optional*):
|
| 1126 |
+
List of annotations associated with the image or batch of images. If annotation is for object
|
| 1127 |
+
detection, the annotations should be a dictionary with the following keys:
|
| 1128 |
+
- "image_id" (`int`): The image id.
|
| 1129 |
+
- "annotations" (`List[Dict]`): List of annotations for an image. Each annotation should be a
|
| 1130 |
+
dictionary. An image can have no annotations, in which case the list should be empty.
|
| 1131 |
+
If annotation is for segmentation, the annotations should be a dictionary with the following keys:
|
| 1132 |
+
- "image_id" (`int`): The image id.
|
| 1133 |
+
- "segments_info" (`List[Dict]`): List of segments for an image. Each segment should be a dictionary.
|
| 1134 |
+
An image can have no segments, in which case the list should be empty.
|
| 1135 |
+
- "file_name" (`str`): The file name of the image.
|
| 1136 |
+
return_segmentation_masks (`bool`, *optional*, defaults to self.return_segmentation_masks):
|
| 1137 |
+
Whether to return segmentation masks.
|
| 1138 |
+
masks_path (`str` or `pathlib.Path`, *optional*):
|
| 1139 |
+
Path to the directory containing the segmentation masks.
|
| 1140 |
+
do_resize (`bool`, *optional*, defaults to self.do_resize):
|
| 1141 |
+
Whether to resize the image.
|
| 1142 |
+
size (`Dict[str, int]`, *optional*, defaults to self.size):
|
| 1143 |
+
Size of the image after resizing.
|
| 1144 |
+
resample (`PILImageResampling`, *optional*, defaults to self.resample):
|
| 1145 |
+
Resampling filter to use when resizing the image.
|
| 1146 |
+
do_rescale (`bool`, *optional*, defaults to self.do_rescale):
|
| 1147 |
+
Whether to rescale the image.
|
| 1148 |
+
rescale_factor (`float`, *optional*, defaults to self.rescale_factor):
|
| 1149 |
+
Rescale factor to use when rescaling the image.
|
| 1150 |
+
do_normalize (`bool`, *optional*, defaults to self.do_normalize):
|
| 1151 |
+
Whether to normalize the image.
|
| 1152 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to self.image_mean):
|
| 1153 |
+
Mean to use when normalizing the image.
|
| 1154 |
+
image_std (`float` or `List[float]`, *optional*, defaults to self.image_std):
|
| 1155 |
+
Standard deviation to use when normalizing the image.
|
| 1156 |
+
do_pad (`bool`, *optional*, defaults to self.do_pad):
|
| 1157 |
+
Whether to pad the image.
|
| 1158 |
+
format (`str` or `AnnotationFormat`, *optional*, defaults to self.format):
|
| 1159 |
+
Format of the annotations.
|
| 1160 |
+
return_tensors (`str` or `TensorType`, *optional*, defaults to self.return_tensors):
|
| 1161 |
+
Type of tensors to return. If `None`, will return the list of images.
|
| 1162 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 1163 |
+
The channel dimension format for the output image. Can be one of:
|
| 1164 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 1165 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 1166 |
+
- Unset: Use the channel dimension format of the input image.
|
| 1167 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 1168 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 1169 |
+
from the input image. Can be one of:
|
| 1170 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 1171 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 1172 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 1173 |
+
"""
|
| 1174 |
+
if "pad_and_return_pixel_mask" in kwargs:
|
| 1175 |
+
logger.warning_once(
|
| 1176 |
+
"The `pad_and_return_pixel_mask` argument is deprecated and will be removed in a future version, "
|
| 1177 |
+
"use `do_pad` instead."
|
| 1178 |
+
)
|
| 1179 |
+
do_pad = kwargs.pop("pad_and_return_pixel_mask")
|
| 1180 |
+
|
| 1181 |
+
max_size = None
|
| 1182 |
+
if "max_size" in kwargs:
|
| 1183 |
+
logger.warning_once(
|
| 1184 |
+
"The `max_size` argument is deprecated and will be removed in a future version, use"
|
| 1185 |
+
" `size['longest_edge']` instead."
|
| 1186 |
+
)
|
| 1187 |
+
size = kwargs.pop("max_size")
|
| 1188 |
+
|
| 1189 |
+
do_resize = self.do_resize if do_resize is None else do_resize
|
| 1190 |
+
size = self.size if size is None else size
|
| 1191 |
+
size = get_size_dict(size=size, max_size=max_size, default_to_square=False)
|
| 1192 |
+
resample = self.resample if resample is None else resample
|
| 1193 |
+
do_rescale = self.do_rescale if do_rescale is None else do_rescale
|
| 1194 |
+
rescale_factor = self.rescale_factor if rescale_factor is None else rescale_factor
|
| 1195 |
+
do_normalize = self.do_normalize if do_normalize is None else do_normalize
|
| 1196 |
+
image_mean = self.image_mean if image_mean is None else image_mean
|
| 1197 |
+
image_std = self.image_std if image_std is None else image_std
|
| 1198 |
+
do_pad = self.do_pad if do_pad is None else do_pad
|
| 1199 |
+
format = self.format if format is None else format
|
| 1200 |
+
|
| 1201 |
+
if do_resize is not None and size is None:
|
| 1202 |
+
raise ValueError("Size and max_size must be specified if do_resize is True.")
|
| 1203 |
+
|
| 1204 |
+
if do_rescale is not None and rescale_factor is None:
|
| 1205 |
+
raise ValueError("Rescale factor must be specified if do_rescale is True.")
|
| 1206 |
+
|
| 1207 |
+
if do_normalize is not None and (image_mean is None or image_std is None):
|
| 1208 |
+
raise ValueError("Image mean and std must be specified if do_normalize is True.")
|
| 1209 |
+
|
| 1210 |
+
images = make_list_of_images(images)
|
| 1211 |
+
if annotations is not None and isinstance(annotations, dict):
|
| 1212 |
+
annotations = [annotations]
|
| 1213 |
+
|
| 1214 |
+
if annotations is not None and len(images) != len(annotations):
|
| 1215 |
+
raise ValueError(
|
| 1216 |
+
f"The number of images ({len(images)}) and annotations ({len(annotations)}) do not match."
|
| 1217 |
+
)
|
| 1218 |
+
|
| 1219 |
+
if not valid_images(images):
|
| 1220 |
+
raise ValueError(
|
| 1221 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 1222 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 1223 |
+
)
|
| 1224 |
+
|
| 1225 |
+
format = AnnotationFormat(format)
|
| 1226 |
+
if annotations is not None:
|
| 1227 |
+
validate_annotations(format, SUPPORTED_ANNOTATION_FORMATS, annotations)
|
| 1228 |
+
|
| 1229 |
+
if (
|
| 1230 |
+
masks_path is not None
|
| 1231 |
+
and format == AnnotationFormat.COCO_PANOPTIC
|
| 1232 |
+
and not isinstance(masks_path, (pathlib.Path, str))
|
| 1233 |
+
):
|
| 1234 |
+
raise ValueError(
|
| 1235 |
+
"The path to the directory containing the mask PNG files should be provided as a"
|
| 1236 |
+
f" `pathlib.Path` or string object, but is {type(masks_path)} instead."
|
| 1237 |
+
)
|
| 1238 |
+
|
| 1239 |
+
# All transformations expect numpy arrays
|
| 1240 |
+
images = [to_numpy_array(image) for image in images]
|
| 1241 |
+
|
| 1242 |
+
if is_scaled_image(images[0]) and do_rescale:
|
| 1243 |
+
logger.warning_once(
|
| 1244 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 1245 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 1246 |
+
)
|
| 1247 |
+
|
| 1248 |
+
if input_data_format is None:
|
| 1249 |
+
# We assume that all images have the same channel dimension format.
|
| 1250 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 1251 |
+
|
| 1252 |
+
# prepare (COCO annotations as a list of Dict -> DETR target as a single Dict per image)
|
| 1253 |
+
if annotations is not None:
|
| 1254 |
+
prepared_images = []
|
| 1255 |
+
prepared_annotations = []
|
| 1256 |
+
for image, target in zip(images, annotations):
|
| 1257 |
+
target = self.prepare_annotation(
|
| 1258 |
+
image,
|
| 1259 |
+
target,
|
| 1260 |
+
format,
|
| 1261 |
+
return_segmentation_masks=return_segmentation_masks,
|
| 1262 |
+
masks_path=masks_path,
|
| 1263 |
+
input_data_format=input_data_format,
|
| 1264 |
+
)
|
| 1265 |
+
prepared_images.append(image)
|
| 1266 |
+
prepared_annotations.append(target)
|
| 1267 |
+
images = prepared_images
|
| 1268 |
+
annotations = prepared_annotations
|
| 1269 |
+
del prepared_images, prepared_annotations
|
| 1270 |
+
|
| 1271 |
+
# transformations
|
| 1272 |
+
if do_resize:
|
| 1273 |
+
if annotations is not None:
|
| 1274 |
+
resized_images, resized_annotations = [], []
|
| 1275 |
+
for image, target in zip(images, annotations):
|
| 1276 |
+
orig_size = get_image_size(image, input_data_format)
|
| 1277 |
+
resized_image = self.resize(
|
| 1278 |
+
image, size=size, max_size=max_size, resample=resample, input_data_format=input_data_format
|
| 1279 |
+
)
|
| 1280 |
+
resized_annotation = self.resize_annotation(
|
| 1281 |
+
target, orig_size, get_image_size(resized_image, input_data_format)
|
| 1282 |
+
)
|
| 1283 |
+
resized_images.append(resized_image)
|
| 1284 |
+
resized_annotations.append(resized_annotation)
|
| 1285 |
+
images = resized_images
|
| 1286 |
+
annotations = resized_annotations
|
| 1287 |
+
del resized_images, resized_annotations
|
| 1288 |
+
else:
|
| 1289 |
+
images = [
|
| 1290 |
+
self.resize(image, size=size, resample=resample, input_data_format=input_data_format)
|
| 1291 |
+
for image in images
|
| 1292 |
+
]
|
| 1293 |
+
|
| 1294 |
+
if do_rescale:
|
| 1295 |
+
images = [self.rescale(image, rescale_factor, input_data_format=input_data_format) for image in images]
|
| 1296 |
+
|
| 1297 |
+
if do_normalize:
|
| 1298 |
+
images = [
|
| 1299 |
+
self.normalize(image, image_mean, image_std, input_data_format=input_data_format) for image in images
|
| 1300 |
+
]
|
| 1301 |
+
if annotations is not None:
|
| 1302 |
+
annotations = [
|
| 1303 |
+
self.normalize_annotation(annotation, get_image_size(image, input_data_format))
|
| 1304 |
+
for annotation, image in zip(annotations, images)
|
| 1305 |
+
]
|
| 1306 |
+
|
| 1307 |
+
if do_pad:
|
| 1308 |
+
# Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...}
|
| 1309 |
+
data = self.pad(
|
| 1310 |
+
images, return_pixel_mask=True, data_format=data_format, input_data_format=input_data_format
|
| 1311 |
+
)
|
| 1312 |
+
else:
|
| 1313 |
+
images = [
|
| 1314 |
+
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
| 1315 |
+
for image in images
|
| 1316 |
+
]
|
| 1317 |
+
data = {"pixel_values": images}
|
| 1318 |
+
|
| 1319 |
+
encoded_inputs = BatchFeature(data=data, tensor_type=return_tensors)
|
| 1320 |
+
if annotations is not None:
|
| 1321 |
+
encoded_inputs["labels"] = [
|
| 1322 |
+
BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations
|
| 1323 |
+
]
|
| 1324 |
+
|
| 1325 |
+
return encoded_inputs
|
| 1326 |
+
|
| 1327 |
+
# POSTPROCESSING METHODS - TODO: add support for other frameworks
|
| 1328 |
+
def post_process(self, outputs, target_sizes):
|
| 1329 |
+
"""
|
| 1330 |
+
Converts the raw output of [`DeformableDetrForObjectDetection`] into final bounding boxes in (top_left_x,
|
| 1331 |
+
top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
|
| 1332 |
+
|
| 1333 |
+
Args:
|
| 1334 |
+
outputs ([`DeformableDetrObjectDetectionOutput`]):
|
| 1335 |
+
Raw outputs of the model.
|
| 1336 |
+
target_sizes (`torch.Tensor` of shape `(batch_size, 2)`):
|
| 1337 |
+
Tensor containing the size (height, width) of each image of the batch. For evaluation, this must be the
|
| 1338 |
+
original image size (before any data augmentation). For visualization, this should be the image size
|
| 1339 |
+
after data augment, but before padding.
|
| 1340 |
+
Returns:
|
| 1341 |
+
`List[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
|
| 1342 |
+
in the batch as predicted by the model.
|
| 1343 |
+
"""
|
| 1344 |
+
logger.warning_once(
|
| 1345 |
+
"`post_process` is deprecated and will be removed in v5 of Transformers, please use"
|
| 1346 |
+
" `post_process_object_detection` instead, with `threshold=0.` for equivalent results.",
|
| 1347 |
+
)
|
| 1348 |
+
|
| 1349 |
+
out_logits, out_bbox = outputs.logits, outputs.pred_boxes
|
| 1350 |
+
|
| 1351 |
+
if len(out_logits) != len(target_sizes):
|
| 1352 |
+
raise ValueError("Make sure that you pass in as many target sizes as the batch dimension of the logits")
|
| 1353 |
+
if target_sizes.shape[1] != 2:
|
| 1354 |
+
raise ValueError("Each element of target_sizes must contain the size (h, w) of each image of the batch")
|
| 1355 |
+
|
| 1356 |
+
prob = out_logits.sigmoid()
|
| 1357 |
+
topk_values, topk_indexes = torch.topk(prob.view(out_logits.shape[0], -1), 100, dim=1)
|
| 1358 |
+
scores = topk_values
|
| 1359 |
+
topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode="floor")
|
| 1360 |
+
labels = topk_indexes % out_logits.shape[2]
|
| 1361 |
+
boxes = center_to_corners_format(out_bbox)
|
| 1362 |
+
boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4))
|
| 1363 |
+
|
| 1364 |
+
# and from relative [0, 1] to absolute [0, height] coordinates
|
| 1365 |
+
img_h, img_w = target_sizes.unbind(1)
|
| 1366 |
+
scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1)
|
| 1367 |
+
boxes = boxes * scale_fct[:, None, :]
|
| 1368 |
+
|
| 1369 |
+
results = [{"scores": s, "labels": l, "boxes": b} for s, l, b in zip(scores, labels, boxes)]
|
| 1370 |
+
|
| 1371 |
+
return results
|
| 1372 |
+
|
| 1373 |
+
def post_process_object_detection(
|
| 1374 |
+
self, outputs, threshold: float = 0.5, target_sizes: Union[TensorType, List[Tuple]] = None, top_k: int = 100
|
| 1375 |
+
):
|
| 1376 |
+
"""
|
| 1377 |
+
Converts the raw output of [`DeformableDetrForObjectDetection`] into final bounding boxes in (top_left_x,
|
| 1378 |
+
top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
|
| 1379 |
+
|
| 1380 |
+
Args:
|
| 1381 |
+
outputs ([`DetrObjectDetectionOutput`]):
|
| 1382 |
+
Raw outputs of the model.
|
| 1383 |
+
threshold (`float`, *optional*):
|
| 1384 |
+
Score threshold to keep object detection predictions.
|
| 1385 |
+
target_sizes (`torch.Tensor` or `List[Tuple[int, int]]`, *optional*):
|
| 1386 |
+
Tensor of shape `(batch_size, 2)` or list of tuples (`Tuple[int, int]`) containing the target size
|
| 1387 |
+
(height, width) of each image in the batch. If left to None, predictions will not be resized.
|
| 1388 |
+
top_k (`int`, *optional*, defaults to 100):
|
| 1389 |
+
Keep only top k bounding boxes before filtering by thresholding.
|
| 1390 |
+
|
| 1391 |
+
Returns:
|
| 1392 |
+
`List[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
|
| 1393 |
+
in the batch as predicted by the model.
|
| 1394 |
+
"""
|
| 1395 |
+
out_logits, out_bbox = outputs.logits, outputs.pred_boxes
|
| 1396 |
+
|
| 1397 |
+
if target_sizes is not None:
|
| 1398 |
+
if len(out_logits) != len(target_sizes):
|
| 1399 |
+
raise ValueError(
|
| 1400 |
+
"Make sure that you pass in as many target sizes as the batch dimension of the logits"
|
| 1401 |
+
)
|
| 1402 |
+
|
| 1403 |
+
prob = out_logits.sigmoid()
|
| 1404 |
+
prob = prob.view(out_logits.shape[0], -1)
|
| 1405 |
+
k_value = min(top_k, prob.size(1))
|
| 1406 |
+
topk_values, topk_indexes = torch.topk(prob, k_value, dim=1)
|
| 1407 |
+
scores = topk_values
|
| 1408 |
+
topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode="floor")
|
| 1409 |
+
labels = topk_indexes % out_logits.shape[2]
|
| 1410 |
+
boxes = center_to_corners_format(out_bbox)
|
| 1411 |
+
boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4))
|
| 1412 |
+
|
| 1413 |
+
# and from relative [0, 1] to absolute [0, height] coordinates
|
| 1414 |
+
if isinstance(target_sizes, List):
|
| 1415 |
+
img_h = torch.Tensor([i[0] for i in target_sizes])
|
| 1416 |
+
img_w = torch.Tensor([i[1] for i in target_sizes])
|
| 1417 |
+
else:
|
| 1418 |
+
img_h, img_w = target_sizes.unbind(1)
|
| 1419 |
+
scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
|
| 1420 |
+
boxes = boxes * scale_fct[:, None, :]
|
| 1421 |
+
|
| 1422 |
+
results = []
|
| 1423 |
+
for s, l, b in zip(scores, labels, boxes):
|
| 1424 |
+
score = s[s > threshold]
|
| 1425 |
+
label = l[s > threshold]
|
| 1426 |
+
box = b[s > threshold]
|
| 1427 |
+
results.append({"scores": score, "labels": label, "boxes": box})
|
| 1428 |
+
|
| 1429 |
+
return results
|
llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/load_custom.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
""" Loading of Deformable DETR's CUDA kernels"""
|
| 16 |
+
import os
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def load_cuda_kernels():
|
| 21 |
+
from torch.utils.cpp_extension import load
|
| 22 |
+
|
| 23 |
+
root = Path(__file__).resolve().parent.parent.parent / "kernels" / "deformable_detr"
|
| 24 |
+
src_files = [
|
| 25 |
+
root / filename
|
| 26 |
+
for filename in [
|
| 27 |
+
"vision.cpp",
|
| 28 |
+
os.path.join("cpu", "ms_deform_attn_cpu.cpp"),
|
| 29 |
+
os.path.join("cuda", "ms_deform_attn_cuda.cu"),
|
| 30 |
+
]
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
load(
|
| 34 |
+
"MultiScaleDeformableAttention",
|
| 35 |
+
src_files,
|
| 36 |
+
with_cuda=True,
|
| 37 |
+
extra_include_paths=[str(root)],
|
| 38 |
+
extra_cflags=["-DWITH_CUDA=1"],
|
| 39 |
+
extra_cuda_cflags=[
|
| 40 |
+
"-DCUDA_HAS_FP16=1",
|
| 41 |
+
"-D__CUDA_NO_HALF_OPERATORS__",
|
| 42 |
+
"-D__CUDA_NO_HALF_CONVERSIONS__",
|
| 43 |
+
"-D__CUDA_NO_HALF2_OPERATORS__",
|
| 44 |
+
],
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
import MultiScaleDeformableAttention as MSDA
|
| 48 |
+
|
| 49 |
+
return MSDA
|
llava_next/lib/python3.10/site-packages/transformers/models/deformable_detr/modeling_deformable_detr.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
llava_next/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.4 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/configuration_mobilenet_v2.cpython-310.pyc
ADDED
|
Binary file (6.91 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/convert_original_tf_checkpoint_to_pytorch.cpython-310.pyc
ADDED
|
Binary file (4.89 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/transformers/models/mobilenet_v2/feature_extraction_mobilenet_v2.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Feature extractor class for MobileNetV2."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
|
| 19 |
+
from ...utils import logging
|
| 20 |
+
from .image_processing_mobilenet_v2 import MobileNetV2ImageProcessor
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class MobileNetV2FeatureExtractor(MobileNetV2ImageProcessor):
|
| 27 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 28 |
+
warnings.warn(
|
| 29 |
+
"The class MobileNetV2FeatureExtractor is deprecated and will be removed in version 5 of Transformers."
|
| 30 |
+
" Please use MobileNetV2ImageProcessor instead.",
|
| 31 |
+
FutureWarning,
|
| 32 |
+
)
|
| 33 |
+
super().__init__(*args, **kwargs)
|
llava_next/lib/python3.10/site-packages/transformers/models/rembert/__pycache__/modeling_rembert.cpython-310.pyc
ADDED
|
Binary file (43.8 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/transformers/models/xglm/__init__.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import (
|
| 17 |
+
OptionalDependencyNotAvailable,
|
| 18 |
+
_LazyModule,
|
| 19 |
+
is_flax_available,
|
| 20 |
+
is_sentencepiece_available,
|
| 21 |
+
is_tf_available,
|
| 22 |
+
is_tokenizers_available,
|
| 23 |
+
is_torch_available,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
_import_structure = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]}
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
if not is_sentencepiece_available():
|
| 31 |
+
raise OptionalDependencyNotAvailable()
|
| 32 |
+
except OptionalDependencyNotAvailable:
|
| 33 |
+
pass
|
| 34 |
+
else:
|
| 35 |
+
_import_structure["tokenization_xglm"] = ["XGLMTokenizer"]
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
if not is_tokenizers_available():
|
| 39 |
+
raise OptionalDependencyNotAvailable()
|
| 40 |
+
except OptionalDependencyNotAvailable:
|
| 41 |
+
pass
|
| 42 |
+
else:
|
| 43 |
+
_import_structure["tokenization_xglm_fast"] = ["XGLMTokenizerFast"]
|
| 44 |
+
|
| 45 |
+
try:
|
| 46 |
+
if not is_torch_available():
|
| 47 |
+
raise OptionalDependencyNotAvailable()
|
| 48 |
+
except OptionalDependencyNotAvailable:
|
| 49 |
+
pass
|
| 50 |
+
else:
|
| 51 |
+
_import_structure["modeling_xglm"] = [
|
| 52 |
+
"XGLM_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 53 |
+
"XGLMForCausalLM",
|
| 54 |
+
"XGLMModel",
|
| 55 |
+
"XGLMPreTrainedModel",
|
| 56 |
+
]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
try:
|
| 60 |
+
if not is_flax_available():
|
| 61 |
+
raise OptionalDependencyNotAvailable()
|
| 62 |
+
except OptionalDependencyNotAvailable:
|
| 63 |
+
pass
|
| 64 |
+
else:
|
| 65 |
+
_import_structure["modeling_flax_xglm"] = [
|
| 66 |
+
"FlaxXGLMForCausalLM",
|
| 67 |
+
"FlaxXGLMModel",
|
| 68 |
+
"FlaxXGLMPreTrainedModel",
|
| 69 |
+
]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
try:
|
| 73 |
+
if not is_tf_available():
|
| 74 |
+
raise OptionalDependencyNotAvailable()
|
| 75 |
+
except OptionalDependencyNotAvailable:
|
| 76 |
+
pass
|
| 77 |
+
else:
|
| 78 |
+
_import_structure["modeling_tf_xglm"] = [
|
| 79 |
+
"TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 80 |
+
"TFXGLMForCausalLM",
|
| 81 |
+
"TFXGLMModel",
|
| 82 |
+
"TFXGLMPreTrainedModel",
|
| 83 |
+
]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
if TYPE_CHECKING:
|
| 87 |
+
from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig
|
| 88 |
+
|
| 89 |
+
try:
|
| 90 |
+
if not is_sentencepiece_available():
|
| 91 |
+
raise OptionalDependencyNotAvailable()
|
| 92 |
+
except OptionalDependencyNotAvailable:
|
| 93 |
+
pass
|
| 94 |
+
else:
|
| 95 |
+
from .tokenization_xglm import XGLMTokenizer
|
| 96 |
+
|
| 97 |
+
try:
|
| 98 |
+
if not is_tokenizers_available():
|
| 99 |
+
raise OptionalDependencyNotAvailable()
|
| 100 |
+
except OptionalDependencyNotAvailable:
|
| 101 |
+
pass
|
| 102 |
+
else:
|
| 103 |
+
from .tokenization_xglm_fast import XGLMTokenizerFast
|
| 104 |
+
|
| 105 |
+
try:
|
| 106 |
+
if not is_torch_available():
|
| 107 |
+
raise OptionalDependencyNotAvailable()
|
| 108 |
+
except OptionalDependencyNotAvailable:
|
| 109 |
+
pass
|
| 110 |
+
else:
|
| 111 |
+
from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel
|
| 112 |
+
|
| 113 |
+
try:
|
| 114 |
+
if not is_flax_available():
|
| 115 |
+
raise OptionalDependencyNotAvailable()
|
| 116 |
+
except OptionalDependencyNotAvailable:
|
| 117 |
+
pass
|
| 118 |
+
else:
|
| 119 |
+
from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel
|
| 120 |
+
|
| 121 |
+
try:
|
| 122 |
+
if not is_tf_available():
|
| 123 |
+
raise OptionalDependencyNotAvailable()
|
| 124 |
+
except OptionalDependencyNotAvailable:
|
| 125 |
+
pass
|
| 126 |
+
else:
|
| 127 |
+
from .modeling_tf_xglm import (
|
| 128 |
+
TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 129 |
+
TFXGLMForCausalLM,
|
| 130 |
+
TFXGLMModel,
|
| 131 |
+
TFXGLMPreTrainedModel,
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
else:
|
| 136 |
+
import sys
|
| 137 |
+
|
| 138 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure)
|
llava_next/lib/python3.10/site-packages/transformers/models/xglm/configuration_xglm.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 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 |
+
""" XGLM model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
| 24 |
+
"facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/config.json",
|
| 25 |
+
# See all XGLM models at https://huggingface.co/models?filter=xglm
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class XGLMConfig(PretrainedConfig):
|
| 30 |
+
r"""
|
| 31 |
+
This is the configuration class to store the configuration of a [`XGLMModel`]. It is used to instantiate an XGLM
|
| 32 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 33 |
+
defaults will yield a similar configuration to that of the XGLM
|
| 34 |
+
[facebook/xglm-564M](https://huggingface.co/facebook/xglm-564M) architecture.
|
| 35 |
+
|
| 36 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 37 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
vocab_size (`int`, *optional*, defaults to 256008):
|
| 42 |
+
Vocabulary size of the XGLM model. Defines the number of different tokens that can be represented by the
|
| 43 |
+
`inputs_ids` passed when calling [`XGLMModel`] or [`FlaxXGLMModel`].
|
| 44 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
| 45 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 46 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 47 |
+
d_model (`int`, *optional*, defaults to 1024):
|
| 48 |
+
Dimension of the layers and the pooler layer.
|
| 49 |
+
ffn_dim (`int`, *optional*, defaults to 4096):
|
| 50 |
+
Dimension of the "intermediate" (often named feed-forward) layer in decoder.
|
| 51 |
+
num_layers (`int`, *optional*, defaults to 24):
|
| 52 |
+
Number of hidden layers Transformer decoder.
|
| 53 |
+
attention_heads (`int`, *optional*, defaults to 16):
|
| 54 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 55 |
+
activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 56 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 57 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 58 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 59 |
+
The dropout probability for all fully connected layers in the embeddings, dencoder, and pooler.
|
| 60 |
+
attention_dropout (`float`, *optional*, defaults to 0.1):
|
| 61 |
+
The dropout ratio for the attention probabilities.
|
| 62 |
+
activation_dropout (`float`, *optional*, defaults to 0.0):
|
| 63 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 64 |
+
layerdrop (`float`, *optional*, defaults to 0.0):
|
| 65 |
+
The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
|
| 66 |
+
for more details.
|
| 67 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 68 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 69 |
+
scale_embedding (`bool`, *optional*, defaults to `True`):
|
| 70 |
+
Scale embeddings by diving by sqrt(d_model).
|
| 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 |
+
|
| 74 |
+
Example:
|
| 75 |
+
|
| 76 |
+
```python
|
| 77 |
+
>>> from transformers import XGLMModel, XGLMConfig
|
| 78 |
+
|
| 79 |
+
>>> # Initializing a XGLM facebook/xglm-564M style configuration
|
| 80 |
+
>>> configuration = XGLMConfig()
|
| 81 |
+
|
| 82 |
+
>>> # Initializing a model from the facebook/xglm-564M style configuration
|
| 83 |
+
>>> model = XGLMModel(configuration)
|
| 84 |
+
|
| 85 |
+
>>> # Accessing the model configuration
|
| 86 |
+
>>> configuration = model.config
|
| 87 |
+
```"""
|
| 88 |
+
|
| 89 |
+
model_type = "xglm"
|
| 90 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 91 |
+
|
| 92 |
+
attribute_map = {
|
| 93 |
+
"num_attention_heads": "attention_heads",
|
| 94 |
+
"hidden_size": "d_model",
|
| 95 |
+
"num_hidden_layers": "num_layers",
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
def __init__(
|
| 99 |
+
self,
|
| 100 |
+
vocab_size=256008,
|
| 101 |
+
max_position_embeddings=2048,
|
| 102 |
+
d_model=1024,
|
| 103 |
+
ffn_dim=4096,
|
| 104 |
+
num_layers=24,
|
| 105 |
+
attention_heads=16,
|
| 106 |
+
activation_function="gelu",
|
| 107 |
+
dropout=0.1,
|
| 108 |
+
attention_dropout=0.1,
|
| 109 |
+
activation_dropout=0.0,
|
| 110 |
+
layerdrop=0.0,
|
| 111 |
+
init_std=0.02,
|
| 112 |
+
scale_embedding=True,
|
| 113 |
+
use_cache=True,
|
| 114 |
+
decoder_start_token_id=2,
|
| 115 |
+
pad_token_id=1,
|
| 116 |
+
bos_token_id=0,
|
| 117 |
+
eos_token_id=2,
|
| 118 |
+
**kwargs,
|
| 119 |
+
):
|
| 120 |
+
self.vocab_size = vocab_size
|
| 121 |
+
self.max_position_embeddings = max_position_embeddings
|
| 122 |
+
self.d_model = d_model
|
| 123 |
+
self.ffn_dim = ffn_dim
|
| 124 |
+
self.num_layers = num_layers
|
| 125 |
+
self.attention_heads = attention_heads
|
| 126 |
+
self.activation_function = activation_function
|
| 127 |
+
self.dropout = dropout
|
| 128 |
+
self.attention_dropout = attention_dropout
|
| 129 |
+
self.activation_dropout = activation_dropout
|
| 130 |
+
self.layerdrop = layerdrop
|
| 131 |
+
self.init_std = init_std
|
| 132 |
+
self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
|
| 133 |
+
self.use_cache = use_cache
|
| 134 |
+
|
| 135 |
+
super().__init__(
|
| 136 |
+
pad_token_id=pad_token_id,
|
| 137 |
+
bos_token_id=bos_token_id,
|
| 138 |
+
eos_token_id=eos_token_id,
|
| 139 |
+
decoder_start_token_id=decoder_start_token_id,
|
| 140 |
+
**kwargs,
|
| 141 |
+
)
|
llava_next/lib/python3.10/site-packages/transformers/models/xglm/convert_xglm_original_ckpt_to_trfms.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
from argparse import Namespace
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
|
| 7 |
+
from transformers import XGLMConfig, XGLMForCausalLM
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def remove_ignore_keys_(state_dict):
|
| 11 |
+
ignore_keys = [
|
| 12 |
+
"decoder.version",
|
| 13 |
+
"decoder.output_projection.weight",
|
| 14 |
+
"_float_tensor",
|
| 15 |
+
"decoder.embed_positions._float_tensor",
|
| 16 |
+
]
|
| 17 |
+
for k in ignore_keys:
|
| 18 |
+
state_dict.pop(k, None)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def make_linear_from_emb(emb):
|
| 22 |
+
vocab_size, emb_size = emb.weight.shape
|
| 23 |
+
lin_layer = nn.Linear(vocab_size, emb_size, bias=False)
|
| 24 |
+
lin_layer.weight.data = emb.weight.data
|
| 25 |
+
return lin_layer
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def convert_fairseq_xglm_checkpoint_from_disk(checkpoint_path):
|
| 29 |
+
checkpoint = torch.load(checkpoint_path, map_location="cpu")
|
| 30 |
+
args = Namespace(**checkpoint["cfg"]["model"])
|
| 31 |
+
state_dict = checkpoint["model"]
|
| 32 |
+
remove_ignore_keys_(state_dict)
|
| 33 |
+
vocab_size = state_dict["decoder.embed_tokens.weight"].shape[0]
|
| 34 |
+
|
| 35 |
+
state_dict = {key.replace("decoder", "model"): val for key, val in state_dict.items()}
|
| 36 |
+
|
| 37 |
+
config = XGLMConfig(
|
| 38 |
+
vocab_size=vocab_size,
|
| 39 |
+
max_position_embeddings=args.max_target_positions,
|
| 40 |
+
num_layers=args.decoder_layers,
|
| 41 |
+
attention_heads=args.decoder_attention_heads,
|
| 42 |
+
ffn_dim=args.decoder_ffn_embed_dim,
|
| 43 |
+
d_model=args.decoder_embed_dim,
|
| 44 |
+
layerdrop=args.decoder_layerdrop,
|
| 45 |
+
dropout=args.dropout,
|
| 46 |
+
attention_dropout=args.attention_dropout,
|
| 47 |
+
activation_dropout=args.activation_dropout,
|
| 48 |
+
activation_function="gelu",
|
| 49 |
+
scale_embedding=not args.no_scale_embedding,
|
| 50 |
+
tie_word_embeddings=args.share_decoder_input_output_embed,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
model = XGLMForCausalLM(config)
|
| 54 |
+
missing = model.load_state_dict(state_dict, strict=False)
|
| 55 |
+
print(missing)
|
| 56 |
+
model.lm_head = make_linear_from_emb(model.model.embed_tokens)
|
| 57 |
+
|
| 58 |
+
return model
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
if __name__ == "__main__":
|
| 62 |
+
parser = argparse.ArgumentParser()
|
| 63 |
+
# Required parameters
|
| 64 |
+
parser.add_argument("fairseq_path", type=str, help="path to a model.pt on local filesystem.")
|
| 65 |
+
parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
|
| 66 |
+
args = parser.parse_args()
|
| 67 |
+
model = convert_fairseq_xglm_checkpoint_from_disk(args.fairseq_path)
|
| 68 |
+
model.save_pretrained(args.pytorch_dump_folder_path)
|
vlmpy310/lib/python3.10/site-packages/transformers/models/cpm/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (539 Bytes). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/cpm/tokenization_cpm.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization classes."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
import unicodedata
|
| 19 |
+
from shutil import copyfile
|
| 20 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
import sentencepiece as spm
|
| 23 |
+
|
| 24 |
+
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
|
| 25 |
+
from ...utils import SPIECE_UNDERLINE, logging
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class CpmTokenizer(PreTrainedTokenizer):
|
| 34 |
+
"""Runs pre-tokenization with Jieba segmentation tool. It is used in CPM models."""
|
| 35 |
+
|
| 36 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 37 |
+
|
| 38 |
+
def __init__(
|
| 39 |
+
self,
|
| 40 |
+
vocab_file,
|
| 41 |
+
do_lower_case=False,
|
| 42 |
+
remove_space=True,
|
| 43 |
+
keep_accents=False,
|
| 44 |
+
bos_token="<s>",
|
| 45 |
+
eos_token="</s>",
|
| 46 |
+
unk_token="<unk>",
|
| 47 |
+
sep_token="<sep>",
|
| 48 |
+
pad_token="<pad>",
|
| 49 |
+
cls_token="<cls>",
|
| 50 |
+
mask_token="<mask>",
|
| 51 |
+
additional_special_tokens=["<eop>", "<eod>"],
|
| 52 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
| 53 |
+
**kwargs,
|
| 54 |
+
) -> None:
|
| 55 |
+
"""
|
| 56 |
+
Construct a CPM tokenizer. Based on [Jieba](https://pypi.org/project/jieba/) and
|
| 57 |
+
[SentencePiece](https://github.com/google/sentencepiece).
|
| 58 |
+
|
| 59 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should
|
| 60 |
+
refer to this superclass for more information regarding those methods.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
vocab_file (`str`):
|
| 64 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
|
| 65 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 66 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 67 |
+
Whether to lowercase the input when tokenizing.
|
| 68 |
+
remove_space (`bool`, *optional*, defaults to `True`):
|
| 69 |
+
Whether to strip the text when tokenizing (removing excess spaces before and after the string).
|
| 70 |
+
keep_accents (`bool`, *optional*, defaults to `False`):
|
| 71 |
+
Whether to keep accents when tokenizing.
|
| 72 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 73 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier
|
| 74 |
+
token.
|
| 75 |
+
|
| 76 |
+
<Tip>
|
| 77 |
+
|
| 78 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 79 |
+
sequence. The token used is the `cls_token`.
|
| 80 |
+
|
| 81 |
+
</Tip>
|
| 82 |
+
|
| 83 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 84 |
+
The end of sequence token.
|
| 85 |
+
|
| 86 |
+
<Tip>
|
| 87 |
+
|
| 88 |
+
When building a sequence using special tokens, this is not the token that is used for the end of
|
| 89 |
+
sequence. The token used is the `sep_token`.
|
| 90 |
+
|
| 91 |
+
</Tip>
|
| 92 |
+
|
| 93 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 94 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be
|
| 95 |
+
this token instead.
|
| 96 |
+
sep_token (`str`, *optional*, defaults to `"<sep>"`):
|
| 97 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences
|
| 98 |
+
for sequence classification or for a text and a question for question answering. It is also used as the
|
| 99 |
+
last token of a sequence built with special tokens.
|
| 100 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 101 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 102 |
+
cls_token (`str`, *optional*, defaults to `"<cls>"`):
|
| 103 |
+
The classifier token which is used when doing sequence classification (classification of the whole
|
| 104 |
+
sequence instead of per-token classification). It is the first token of the sequence when built with
|
| 105 |
+
special tokens.
|
| 106 |
+
mask_token (`str`, *optional*, defaults to `"<mask>"`):
|
| 107 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 108 |
+
modeling. This is the token which the model will try to predict.
|
| 109 |
+
additional_special_tokens (`List[str]`, *optional*, defaults to `["<eop>", "<eod>"]`):
|
| 110 |
+
Additional special tokens used by the tokenizer.
|
| 111 |
+
|
| 112 |
+
Attributes:
|
| 113 |
+
sp_model (`SentencePieceProcessor`):
|
| 114 |
+
The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
|
| 115 |
+
"""
|
| 116 |
+
# Mask token behave like a normal word, i.e. include the space before it
|
| 117 |
+
mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
|
| 118 |
+
|
| 119 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 120 |
+
|
| 121 |
+
self.do_lower_case = do_lower_case
|
| 122 |
+
self.remove_space = remove_space
|
| 123 |
+
self.keep_accents = keep_accents
|
| 124 |
+
self.vocab_file = vocab_file
|
| 125 |
+
|
| 126 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 127 |
+
self.sp_model.Load(vocab_file)
|
| 128 |
+
|
| 129 |
+
try:
|
| 130 |
+
import jieba
|
| 131 |
+
except ModuleNotFoundError as error:
|
| 132 |
+
raise error.__class__(
|
| 133 |
+
"You need to install jieba to use CpmTokenizer or CpmTokenizerFast. "
|
| 134 |
+
"See https://pypi.org/project/jieba/ for installation."
|
| 135 |
+
)
|
| 136 |
+
self.jieba = jieba
|
| 137 |
+
self.translator = str.maketrans(" \n", "\u2582\u2583")
|
| 138 |
+
|
| 139 |
+
super().__init__(
|
| 140 |
+
do_lower_case=do_lower_case,
|
| 141 |
+
remove_space=remove_space,
|
| 142 |
+
keep_accents=keep_accents,
|
| 143 |
+
bos_token=bos_token,
|
| 144 |
+
eos_token=eos_token,
|
| 145 |
+
unk_token=unk_token,
|
| 146 |
+
sep_token=sep_token,
|
| 147 |
+
pad_token=pad_token,
|
| 148 |
+
cls_token=cls_token,
|
| 149 |
+
mask_token=mask_token,
|
| 150 |
+
additional_special_tokens=additional_special_tokens,
|
| 151 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 152 |
+
**kwargs,
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
self._pad_token_type_id = 3
|
| 156 |
+
|
| 157 |
+
@property
|
| 158 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size
|
| 159 |
+
def vocab_size(self):
|
| 160 |
+
return len(self.sp_model)
|
| 161 |
+
|
| 162 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.get_vocab
|
| 163 |
+
def get_vocab(self):
|
| 164 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
| 165 |
+
vocab.update(self.added_tokens_encoder)
|
| 166 |
+
return vocab
|
| 167 |
+
|
| 168 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.__getstate__
|
| 169 |
+
def __getstate__(self):
|
| 170 |
+
state = self.__dict__.copy()
|
| 171 |
+
state["sp_model"] = None
|
| 172 |
+
return state
|
| 173 |
+
|
| 174 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.__setstate__
|
| 175 |
+
def __setstate__(self, d):
|
| 176 |
+
self.__dict__ = d
|
| 177 |
+
|
| 178 |
+
# for backward compatibility
|
| 179 |
+
if not hasattr(self, "sp_model_kwargs"):
|
| 180 |
+
self.sp_model_kwargs = {}
|
| 181 |
+
|
| 182 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 183 |
+
self.sp_model.Load(self.vocab_file)
|
| 184 |
+
|
| 185 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.preprocess_text
|
| 186 |
+
def preprocess_text(self, inputs):
|
| 187 |
+
if self.remove_space:
|
| 188 |
+
outputs = " ".join(inputs.strip().split())
|
| 189 |
+
else:
|
| 190 |
+
outputs = inputs
|
| 191 |
+
outputs = outputs.replace("``", '"').replace("''", '"')
|
| 192 |
+
|
| 193 |
+
if not self.keep_accents:
|
| 194 |
+
outputs = unicodedata.normalize("NFKD", outputs)
|
| 195 |
+
outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
|
| 196 |
+
if self.do_lower_case:
|
| 197 |
+
outputs = outputs.lower()
|
| 198 |
+
|
| 199 |
+
return outputs
|
| 200 |
+
|
| 201 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer._tokenize
|
| 202 |
+
def _tokenize(self, text: str) -> List[str]:
|
| 203 |
+
"""Tokenize a string."""
|
| 204 |
+
text = self.preprocess_text(text)
|
| 205 |
+
pieces = self.sp_model.encode(text, out_type=str)
|
| 206 |
+
new_pieces = []
|
| 207 |
+
for piece in pieces:
|
| 208 |
+
if len(piece) > 1 and piece[-1] == str(",") and piece[-2].isdigit():
|
| 209 |
+
cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
|
| 210 |
+
if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
|
| 211 |
+
if len(cur_pieces[0]) == 1:
|
| 212 |
+
cur_pieces = cur_pieces[1:]
|
| 213 |
+
else:
|
| 214 |
+
cur_pieces[0] = cur_pieces[0][1:]
|
| 215 |
+
cur_pieces.append(piece[-1])
|
| 216 |
+
new_pieces.extend(cur_pieces)
|
| 217 |
+
else:
|
| 218 |
+
new_pieces.append(piece)
|
| 219 |
+
|
| 220 |
+
return new_pieces
|
| 221 |
+
|
| 222 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer._convert_token_to_id
|
| 223 |
+
def _convert_token_to_id(self, token):
|
| 224 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 225 |
+
return self.sp_model.PieceToId(token)
|
| 226 |
+
|
| 227 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer._convert_id_to_token
|
| 228 |
+
def _convert_id_to_token(self, index):
|
| 229 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 230 |
+
return self.sp_model.IdToPiece(index)
|
| 231 |
+
|
| 232 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.convert_tokens_to_string
|
| 233 |
+
def convert_tokens_to_string(self, tokens):
|
| 234 |
+
"""Converts a sequence of tokens (strings for sub-words) in a single string."""
|
| 235 |
+
out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
|
| 236 |
+
return out_string
|
| 237 |
+
|
| 238 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.build_inputs_with_special_tokens
|
| 239 |
+
def build_inputs_with_special_tokens(
|
| 240 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 241 |
+
) -> List[int]:
|
| 242 |
+
"""
|
| 243 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 244 |
+
adding special tokens. An XLNet sequence has the following format:
|
| 245 |
+
|
| 246 |
+
- single sequence: `X <sep> <cls>`
|
| 247 |
+
- pair of sequences: `A <sep> B <sep> <cls>`
|
| 248 |
+
|
| 249 |
+
Args:
|
| 250 |
+
token_ids_0 (`List[int]`):
|
| 251 |
+
List of IDs to which the special tokens will be added.
|
| 252 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 253 |
+
Optional second list of IDs for sequence pairs.
|
| 254 |
+
|
| 255 |
+
Returns:
|
| 256 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 257 |
+
"""
|
| 258 |
+
sep = [self.sep_token_id]
|
| 259 |
+
cls = [self.cls_token_id]
|
| 260 |
+
if token_ids_1 is None:
|
| 261 |
+
return token_ids_0 + sep + cls
|
| 262 |
+
return token_ids_0 + sep + token_ids_1 + sep + cls
|
| 263 |
+
|
| 264 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.get_special_tokens_mask
|
| 265 |
+
def get_special_tokens_mask(
|
| 266 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 267 |
+
) -> List[int]:
|
| 268 |
+
"""
|
| 269 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 270 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 271 |
+
|
| 272 |
+
Args:
|
| 273 |
+
token_ids_0 (`List[int]`):
|
| 274 |
+
List of IDs.
|
| 275 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 276 |
+
Optional second list of IDs for sequence pairs.
|
| 277 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 278 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 279 |
+
|
| 280 |
+
Returns:
|
| 281 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 282 |
+
"""
|
| 283 |
+
|
| 284 |
+
if already_has_special_tokens:
|
| 285 |
+
return super().get_special_tokens_mask(
|
| 286 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
if token_ids_1 is not None:
|
| 290 |
+
return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1, 1]
|
| 291 |
+
return ([0] * len(token_ids_0)) + [1, 1]
|
| 292 |
+
|
| 293 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.create_token_type_ids_from_sequences
|
| 294 |
+
def create_token_type_ids_from_sequences(
|
| 295 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 296 |
+
) -> List[int]:
|
| 297 |
+
"""
|
| 298 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
|
| 299 |
+
sequence pair mask has the following format:
|
| 300 |
+
|
| 301 |
+
```
|
| 302 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
| 303 |
+
| first sequence | second sequence |
|
| 304 |
+
```
|
| 305 |
+
|
| 306 |
+
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
|
| 307 |
+
|
| 308 |
+
Args:
|
| 309 |
+
token_ids_0 (`List[int]`):
|
| 310 |
+
List of IDs.
|
| 311 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 312 |
+
Optional second list of IDs for sequence pairs.
|
| 313 |
+
|
| 314 |
+
Returns:
|
| 315 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 316 |
+
"""
|
| 317 |
+
sep = [self.sep_token_id]
|
| 318 |
+
cls_segment_id = [2]
|
| 319 |
+
|
| 320 |
+
if token_ids_1 is None:
|
| 321 |
+
return len(token_ids_0 + sep) * [0] + cls_segment_id
|
| 322 |
+
return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] + cls_segment_id
|
| 323 |
+
|
| 324 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.save_vocabulary
|
| 325 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 326 |
+
if not os.path.isdir(save_directory):
|
| 327 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 328 |
+
return
|
| 329 |
+
out_vocab_file = os.path.join(
|
| 330 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
| 334 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 335 |
+
elif not os.path.isfile(self.vocab_file):
|
| 336 |
+
with open(out_vocab_file, "wb") as fi:
|
| 337 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 338 |
+
fi.write(content_spiece_model)
|
| 339 |
+
|
| 340 |
+
return (out_vocab_file,)
|
| 341 |
+
|
| 342 |
+
def _decode(self, *args, **kwargs):
|
| 343 |
+
text = super()._decode(*args, **kwargs)
|
| 344 |
+
text = text.replace(" ", "").replace("\u2582", " ").replace("\u2583", "\n")
|
| 345 |
+
return text
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
__all__ = ["CpmTokenizer"]
|
vlmpy310/lib/python3.10/site-packages/transformers/models/cpm/tokenization_cpm_fast.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization classes."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
from shutil import copyfile
|
| 19 |
+
from typing import List, Optional, Tuple
|
| 20 |
+
|
| 21 |
+
from ...tokenization_utils_fast import AddedToken, PreTrainedTokenizerFast
|
| 22 |
+
from ...utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class CpmTokenizerFast(PreTrainedTokenizerFast):
|
| 31 |
+
"""Runs pre-tokenization with Jieba segmentation tool. It is used in CPM models."""
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
vocab_file=None,
|
| 36 |
+
tokenizer_file=None,
|
| 37 |
+
do_lower_case=False,
|
| 38 |
+
remove_space=True,
|
| 39 |
+
keep_accents=False,
|
| 40 |
+
bos_token="<s>",
|
| 41 |
+
eos_token="</s>",
|
| 42 |
+
unk_token="<unk>",
|
| 43 |
+
sep_token="<sep>",
|
| 44 |
+
pad_token="<pad>",
|
| 45 |
+
cls_token="<cls>",
|
| 46 |
+
mask_token="<mask>",
|
| 47 |
+
additional_special_tokens=["<eop>", "<eod>"],
|
| 48 |
+
**kwargs,
|
| 49 |
+
):
|
| 50 |
+
"""
|
| 51 |
+
Construct a CPM tokenizer. Based on [Jieba](https://pypi.org/project/jieba/) and
|
| 52 |
+
[SentencePiece](https://github.com/google/sentencepiece).
|
| 53 |
+
|
| 54 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should
|
| 55 |
+
refer to this superclass for more information regarding those methods.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
vocab_file (`str`):
|
| 59 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
|
| 60 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 61 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 62 |
+
Whether to lowercase the input when tokenizing.
|
| 63 |
+
remove_space (`bool`, *optional*, defaults to `True`):
|
| 64 |
+
Whether to strip the text when tokenizing (removing excess spaces before and after the string).
|
| 65 |
+
keep_accents (`bool`, *optional*, defaults to `False`):
|
| 66 |
+
Whether to keep accents when tokenizing.
|
| 67 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 68 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier
|
| 69 |
+
token.
|
| 70 |
+
|
| 71 |
+
<Tip>
|
| 72 |
+
|
| 73 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 74 |
+
sequence. The token used is the `cls_token`.
|
| 75 |
+
|
| 76 |
+
</Tip>
|
| 77 |
+
|
| 78 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 79 |
+
The end of sequence token.
|
| 80 |
+
|
| 81 |
+
<Tip>
|
| 82 |
+
|
| 83 |
+
When building a sequence using special tokens, this is not the token that is used for the end of
|
| 84 |
+
sequence. The token used is the `sep_token`.
|
| 85 |
+
|
| 86 |
+
</Tip>
|
| 87 |
+
|
| 88 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 89 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be
|
| 90 |
+
this token instead.
|
| 91 |
+
sep_token (`str`, *optional*, defaults to `"<sep>"`):
|
| 92 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences
|
| 93 |
+
for sequence classification or for a text and a question for question answering. It is also used as the
|
| 94 |
+
last token of a sequence built with special tokens.
|
| 95 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 96 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 97 |
+
cls_token (`str`, *optional*, defaults to `"<cls>"`):
|
| 98 |
+
The classifier token which is used when doing sequence classification (classification of the whole
|
| 99 |
+
sequence instead of per-token classification). It is the first token of the sequence when built with
|
| 100 |
+
special tokens.
|
| 101 |
+
mask_token (`str`, *optional*, defaults to `"<mask>"`):
|
| 102 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 103 |
+
modeling. This is the token which the model will try to predict.
|
| 104 |
+
additional_special_tokens (`List[str]`, *optional*, defaults to `["<eop>", "<eod>"]`):
|
| 105 |
+
Additional special tokens used by the tokenizer.
|
| 106 |
+
|
| 107 |
+
Attributes:
|
| 108 |
+
sp_model (`SentencePieceProcessor`):
|
| 109 |
+
The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
|
| 110 |
+
"""
|
| 111 |
+
# Mask token behave like a normal word, i.e. include the space before it
|
| 112 |
+
mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
|
| 113 |
+
|
| 114 |
+
super().__init__(
|
| 115 |
+
vocab_file=vocab_file,
|
| 116 |
+
tokenizer_file=tokenizer_file,
|
| 117 |
+
do_lower_case=do_lower_case,
|
| 118 |
+
remove_space=remove_space,
|
| 119 |
+
keep_accents=keep_accents,
|
| 120 |
+
bos_token=bos_token,
|
| 121 |
+
eos_token=eos_token,
|
| 122 |
+
unk_token=unk_token,
|
| 123 |
+
sep_token=sep_token,
|
| 124 |
+
pad_token=pad_token,
|
| 125 |
+
cls_token=cls_token,
|
| 126 |
+
mask_token=mask_token,
|
| 127 |
+
additional_special_tokens=additional_special_tokens,
|
| 128 |
+
**kwargs,
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
self._pad_token_type_id = 3
|
| 132 |
+
self.do_lower_case = do_lower_case
|
| 133 |
+
self.remove_space = remove_space
|
| 134 |
+
self.keep_accents = keep_accents
|
| 135 |
+
self.vocab_file = vocab_file
|
| 136 |
+
|
| 137 |
+
try:
|
| 138 |
+
import jieba
|
| 139 |
+
except ModuleNotFoundError as error:
|
| 140 |
+
raise error.__class__(
|
| 141 |
+
"You need to install jieba to use CpmTokenizer or CpmTokenizerFast. "
|
| 142 |
+
"See https://pypi.org/project/jieba/ for installation."
|
| 143 |
+
)
|
| 144 |
+
self.jieba = jieba
|
| 145 |
+
self.translator = str.maketrans(" \n", "\u2582\u2583")
|
| 146 |
+
|
| 147 |
+
@property
|
| 148 |
+
def can_save_slow_tokenizer(self) -> bool:
|
| 149 |
+
return os.path.isfile(self.vocab_file) if self.vocab_file else False
|
| 150 |
+
|
| 151 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet_fast.XLNetTokenizerFast.build_inputs_with_special_tokens
|
| 152 |
+
def build_inputs_with_special_tokens(
|
| 153 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 154 |
+
) -> List[int]:
|
| 155 |
+
"""
|
| 156 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 157 |
+
adding special tokens. An XLNet sequence has the following format:
|
| 158 |
+
|
| 159 |
+
- single sequence: `X <sep> <cls>`
|
| 160 |
+
- pair of sequences: `A <sep> B <sep> <cls>`
|
| 161 |
+
|
| 162 |
+
Args:
|
| 163 |
+
token_ids_0 (`List[int]`):
|
| 164 |
+
List of IDs to which the special tokens will be added.
|
| 165 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 166 |
+
Optional second list of IDs for sequence pairs.
|
| 167 |
+
|
| 168 |
+
Returns:
|
| 169 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 170 |
+
"""
|
| 171 |
+
sep = [self.sep_token_id]
|
| 172 |
+
cls = [self.cls_token_id]
|
| 173 |
+
if token_ids_1 is None:
|
| 174 |
+
return token_ids_0 + sep + cls
|
| 175 |
+
return token_ids_0 + sep + token_ids_1 + sep + cls
|
| 176 |
+
|
| 177 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet_fast.XLNetTokenizerFast.create_token_type_ids_from_sequences
|
| 178 |
+
def create_token_type_ids_from_sequences(
|
| 179 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 180 |
+
) -> List[int]:
|
| 181 |
+
"""
|
| 182 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
|
| 183 |
+
sequence pair mask has the following format:
|
| 184 |
+
|
| 185 |
+
```
|
| 186 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
| 187 |
+
| first sequence | second sequence |
|
| 188 |
+
```
|
| 189 |
+
|
| 190 |
+
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
|
| 191 |
+
|
| 192 |
+
Args:
|
| 193 |
+
token_ids_0 (`List[int]`):
|
| 194 |
+
List of IDs.
|
| 195 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 196 |
+
Optional second list of IDs for sequence pairs.
|
| 197 |
+
|
| 198 |
+
Returns:
|
| 199 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 200 |
+
"""
|
| 201 |
+
sep = [self.sep_token_id]
|
| 202 |
+
cls_segment_id = [2]
|
| 203 |
+
|
| 204 |
+
if token_ids_1 is None:
|
| 205 |
+
return len(token_ids_0 + sep) * [0] + cls_segment_id
|
| 206 |
+
return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] + cls_segment_id
|
| 207 |
+
|
| 208 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet_fast.XLNetTokenizerFast.save_vocabulary
|
| 209 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 210 |
+
if not self.can_save_slow_tokenizer:
|
| 211 |
+
raise ValueError(
|
| 212 |
+
"Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
|
| 213 |
+
"tokenizer."
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
if not os.path.isdir(save_directory):
|
| 217 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 218 |
+
return
|
| 219 |
+
out_vocab_file = os.path.join(
|
| 220 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
|
| 224 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 225 |
+
|
| 226 |
+
return (out_vocab_file,)
|
| 227 |
+
|
| 228 |
+
def _batch_encode_plus(self, batch_text_or_text_pairs, *args, **kwargs):
|
| 229 |
+
batch_text_or_text_pairs = [
|
| 230 |
+
" ".join([x.translate(self.translator) for x in self.jieba.cut(text, cut_all=False)])
|
| 231 |
+
for text in batch_text_or_text_pairs
|
| 232 |
+
]
|
| 233 |
+
return super()._batch_encode_plus(batch_text_or_text_pairs, *args, **kwargs)
|
| 234 |
+
|
| 235 |
+
def _decode(self, *args, **kwargs):
|
| 236 |
+
text = super()._decode(*args, **kwargs)
|
| 237 |
+
text = text.replace(" ", "").replace("\u2582", " ").replace("\u2583", "\n")
|
| 238 |
+
return text
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
__all__ = ["CpmTokenizerFast"]
|
vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_longt5 import *
|
| 22 |
+
from .modeling_flax_longt5 import *
|
| 23 |
+
from .modeling_longt5 import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (572 Bytes). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/__pycache__/configuration_longt5.cpython-310.pyc
ADDED
|
Binary file (6.86 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/__pycache__/convert_longt5x_checkpoint_to_flax.cpython-310.pyc
ADDED
|
Binary file (5.06 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/__pycache__/modeling_flax_longt5.cpython-310.pyc
ADDED
|
Binary file (60.1 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/__pycache__/modeling_longt5.cpython-310.pyc
ADDED
|
Binary file (61.8 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/configuration_longt5.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022, The LongT5 Authors and HuggingFace 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 |
+
"""LongT5 model configuration"""
|
| 16 |
+
|
| 17 |
+
from typing import Mapping
|
| 18 |
+
|
| 19 |
+
from ...configuration_utils import PretrainedConfig
|
| 20 |
+
from ...onnx import OnnxSeq2SeqConfigWithPast
|
| 21 |
+
from ...utils import logging
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class LongT5Config(PretrainedConfig):
|
| 28 |
+
r"""
|
| 29 |
+
This is the configuration class to store the configuration of a [`LongT5Model`] or a [`FlaxLongT5Model`]. It is
|
| 30 |
+
used to instantiate a LongT5 model according to the specified arguments, defining the model architecture.
|
| 31 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the LongT5
|
| 32 |
+
[google/long-t5-local-base](https://huggingface.co/google/long-t5-local-base) architecture.
|
| 33 |
+
|
| 34 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 35 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 36 |
+
|
| 37 |
+
Arguments:
|
| 38 |
+
vocab_size (`int`, *optional*, defaults to 32128):
|
| 39 |
+
Vocabulary size of the LongT5 model. Defines the number of different tokens that can be represented by the
|
| 40 |
+
`inputs_ids` passed when calling [`LongT5Model`].
|
| 41 |
+
d_model (`int`, *optional*, defaults to 512):
|
| 42 |
+
Size of the encoder layers and the pooler layer.
|
| 43 |
+
d_kv (`int`, *optional*, defaults to 64):
|
| 44 |
+
Size of the key, query, value projections per attention head. `d_kv` has to be equal to `d_model //
|
| 45 |
+
num_heads`.
|
| 46 |
+
d_ff (`int`, *optional*, defaults to 2048):
|
| 47 |
+
Size of the intermediate feed forward layer in each `LongT5Block`.
|
| 48 |
+
num_layers (`int`, *optional*, defaults to 6):
|
| 49 |
+
Number of hidden layers in the Transformer encoder.
|
| 50 |
+
num_decoder_layers (`int`, *optional*):
|
| 51 |
+
Number of hidden layers in the Transformer decoder. Will use the same value as `num_layers` if not set.
|
| 52 |
+
num_heads (`int`, *optional*, defaults to 8):
|
| 53 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 54 |
+
local_radius (`int`, *optional*, defaults to 127)
|
| 55 |
+
Number of tokens to the left/right for each token to locally self-attend in a local attention mechanism.
|
| 56 |
+
global_block_size (`int`, *optional*, defaults to 16)
|
| 57 |
+
Lenght of blocks an input sequence is divided into for a global token representation. Used only for
|
| 58 |
+
`encoder_attention_type = "transient-global"`.
|
| 59 |
+
relative_attention_num_buckets (`int`, *optional*, defaults to 32):
|
| 60 |
+
The number of buckets to use for each attention layer.
|
| 61 |
+
relative_attention_max_distance (`int`, *optional*, defaults to 128):
|
| 62 |
+
The maximum distance of the longer sequences for the bucket separation.
|
| 63 |
+
dropout_rate (`float`, *optional*, defaults to 0.1):
|
| 64 |
+
The ratio for all dropout layers.
|
| 65 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-6):
|
| 66 |
+
The epsilon used by the layer normalization layers.
|
| 67 |
+
initializer_factor (`float`, *optional*, defaults to 1):
|
| 68 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
| 69 |
+
testing).
|
| 70 |
+
feed_forward_proj (`string`, *optional*, defaults to `"relu"`):
|
| 71 |
+
Type of feed forward layer to be used. Should be one of `"relu"` or `"gated-gelu"`. LongT5v1.1 uses the
|
| 72 |
+
`"gated-gelu"` feed forward projection. Original LongT5 implementation uses `"gated-gelu"`.
|
| 73 |
+
encoder_attention_type (`string`, *optional*, defaults to `"local"`):
|
| 74 |
+
Type of encoder attention to be used. Should be one of `"local"` or `"transient-global"`, which are
|
| 75 |
+
supported by LongT5 implementation.
|
| 76 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 77 |
+
Whether or not the model should return the last key/values attentions (not used by all models).
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
model_type = "longt5"
|
| 81 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 82 |
+
attribute_map = {
|
| 83 |
+
"hidden_size": "d_model",
|
| 84 |
+
"num_attention_heads": "num_heads",
|
| 85 |
+
"num_hidden_layers": "num_layers",
|
| 86 |
+
"head_dim": "d_kv",
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
def __init__(
|
| 90 |
+
self,
|
| 91 |
+
vocab_size=32128,
|
| 92 |
+
d_model=512,
|
| 93 |
+
d_kv=64,
|
| 94 |
+
d_ff=2048,
|
| 95 |
+
num_layers=6,
|
| 96 |
+
num_decoder_layers=None,
|
| 97 |
+
num_heads=8,
|
| 98 |
+
local_radius=127,
|
| 99 |
+
global_block_size=16,
|
| 100 |
+
relative_attention_num_buckets=32,
|
| 101 |
+
relative_attention_max_distance=128,
|
| 102 |
+
dropout_rate=0.1,
|
| 103 |
+
layer_norm_epsilon=1e-6,
|
| 104 |
+
initializer_factor=1.0,
|
| 105 |
+
feed_forward_proj="relu",
|
| 106 |
+
is_encoder_decoder=True,
|
| 107 |
+
encoder_attention_type="local",
|
| 108 |
+
use_cache=True,
|
| 109 |
+
pad_token_id=0,
|
| 110 |
+
eos_token_id=1,
|
| 111 |
+
**kwargs,
|
| 112 |
+
):
|
| 113 |
+
self.vocab_size = vocab_size
|
| 114 |
+
self.d_model = d_model
|
| 115 |
+
self.d_kv = d_kv
|
| 116 |
+
self.d_ff = d_ff
|
| 117 |
+
self.num_layers = num_layers
|
| 118 |
+
# default = symmetry
|
| 119 |
+
self.num_decoder_layers = num_decoder_layers if num_decoder_layers is not None else self.num_layers
|
| 120 |
+
self.num_heads = num_heads
|
| 121 |
+
self.local_radius = local_radius
|
| 122 |
+
self.global_block_size = global_block_size
|
| 123 |
+
self.relative_attention_num_buckets = relative_attention_num_buckets
|
| 124 |
+
self.relative_attention_max_distance = relative_attention_max_distance
|
| 125 |
+
self.dropout_rate = dropout_rate
|
| 126 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
| 127 |
+
self.initializer_factor = initializer_factor
|
| 128 |
+
self.feed_forward_proj = feed_forward_proj
|
| 129 |
+
self.encoder_attention_type = encoder_attention_type
|
| 130 |
+
self.use_cache = use_cache
|
| 131 |
+
|
| 132 |
+
act_info = self.feed_forward_proj.split("-")
|
| 133 |
+
self.dense_act_fn = act_info[-1]
|
| 134 |
+
self.is_gated_act = act_info[0] == "gated"
|
| 135 |
+
|
| 136 |
+
if len(act_info) > 1 and act_info[0] != "gated" or len(act_info) > 2:
|
| 137 |
+
raise ValueError(
|
| 138 |
+
f"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer. "
|
| 139 |
+
"Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. "
|
| 140 |
+
"'gated-gelu' or 'relu'"
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
# for backwards compatibility
|
| 144 |
+
if feed_forward_proj == "gated-gelu":
|
| 145 |
+
self.dense_act_fn = "gelu_new"
|
| 146 |
+
|
| 147 |
+
super().__init__(
|
| 148 |
+
pad_token_id=pad_token_id,
|
| 149 |
+
eos_token_id=eos_token_id,
|
| 150 |
+
is_encoder_decoder=is_encoder_decoder,
|
| 151 |
+
**kwargs,
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class LongT5OnnxConfig(OnnxSeq2SeqConfigWithPast):
|
| 156 |
+
@property
|
| 157 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 158 |
+
common_inputs = {
|
| 159 |
+
"input_ids": {0: "batch", 1: "encoder_sequence"},
|
| 160 |
+
"attention_mask": {0: "batch", 1: "encoder_sequence"},
|
| 161 |
+
}
|
| 162 |
+
if self.use_past:
|
| 163 |
+
common_inputs["attention_mask"][1] = "past_encoder_sequence + sequence"
|
| 164 |
+
common_inputs["decoder_input_ids"] = {0: "batch"}
|
| 165 |
+
common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
|
| 166 |
+
else:
|
| 167 |
+
common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
|
| 168 |
+
common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"}
|
| 169 |
+
|
| 170 |
+
if self.use_past:
|
| 171 |
+
self.fill_with_past_key_values_(common_inputs, direction="inputs")
|
| 172 |
+
|
| 173 |
+
return common_inputs
|
| 174 |
+
|
| 175 |
+
@property
|
| 176 |
+
def default_onnx_opset(self) -> int:
|
| 177 |
+
return 13
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
__all__ = ["LongT5Config", "LongT5OnnxConfig"]
|
vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/convert_longt5x_checkpoint_to_flax.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
"""Convert T5/LongT5X checkpoints from the original repository to JAX/FLAX model. This script is an extension of
|
| 17 |
+
'src/transformers/models/t5/convert_t5x_checkpoint_to_flax.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
|
| 22 |
+
from t5x import checkpoints
|
| 23 |
+
|
| 24 |
+
from transformers import AutoConfig, FlaxAutoModelForSeq2SeqLM
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def convert_t5x_checkpoint_to_flax(t5x_checkpoint_path, config_name, flax_dump_folder_path):
|
| 28 |
+
config = AutoConfig.from_pretrained(config_name)
|
| 29 |
+
flax_model = FlaxAutoModelForSeq2SeqLM.from_config(config=config)
|
| 30 |
+
t5x_model = checkpoints.load_t5x_checkpoint(t5x_checkpoint_path)
|
| 31 |
+
|
| 32 |
+
split_mlp_wi = "wi_0" in t5x_model["target"]["encoder"]["layers_0"]["mlp"]
|
| 33 |
+
|
| 34 |
+
if config.model_type == "t5":
|
| 35 |
+
encoder_attn_name = "SelfAttention"
|
| 36 |
+
if config.model_type == "longt5" and config.encoder_attention_type == "local":
|
| 37 |
+
encoder_attn_name = "LocalSelfAttention"
|
| 38 |
+
elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
|
| 39 |
+
encoder_attn_name = "TransientGlobalSelfAttention"
|
| 40 |
+
else:
|
| 41 |
+
raise ValueError(
|
| 42 |
+
"Given config is expected to have `model_type='t5'`, or `model_type='longt5` with `encoder_attention_type`"
|
| 43 |
+
" attribute with a value from ['local', 'transient-global]."
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
# Encoder
|
| 47 |
+
for layer_index in range(config.num_layers):
|
| 48 |
+
layer_name = f"layers_{str(layer_index)}"
|
| 49 |
+
|
| 50 |
+
# Self-Attention
|
| 51 |
+
t5x_attention_key = t5x_model["target"]["encoder"][layer_name]["attention"]["key"]["kernel"]
|
| 52 |
+
t5x_attention_out = t5x_model["target"]["encoder"][layer_name]["attention"]["out"]["kernel"]
|
| 53 |
+
t5x_attention_query = t5x_model["target"]["encoder"][layer_name]["attention"]["query"]["kernel"]
|
| 54 |
+
t5x_attention_value = t5x_model["target"]["encoder"][layer_name]["attention"]["value"]["kernel"]
|
| 55 |
+
|
| 56 |
+
# Global input layer norm
|
| 57 |
+
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
|
| 58 |
+
t5x_global_layer_norm = t5x_model["target"]["encoder"][layer_name]["attention"]["T5LayerNorm_0"]["scale"]
|
| 59 |
+
|
| 60 |
+
# Layer Normalization
|
| 61 |
+
t5x_attention_layer_norm = t5x_model["target"]["encoder"][layer_name]["pre_attention_layer_norm"]["scale"]
|
| 62 |
+
|
| 63 |
+
if split_mlp_wi:
|
| 64 |
+
t5x_mlp_wi_0 = t5x_model["target"]["encoder"][layer_name]["mlp"]["wi_0"]["kernel"]
|
| 65 |
+
t5x_mlp_wi_1 = t5x_model["target"]["encoder"][layer_name]["mlp"]["wi_1"]["kernel"]
|
| 66 |
+
else:
|
| 67 |
+
t5x_mlp_wi = t5x_model["target"]["encoder"][layer_name]["mlp"]["wi"]["kernel"]
|
| 68 |
+
|
| 69 |
+
t5x_mlp_wo = t5x_model["target"]["encoder"][layer_name]["mlp"]["wo"]["kernel"]
|
| 70 |
+
|
| 71 |
+
# Layer Normalization
|
| 72 |
+
t5x_mlp_layer_norm = t5x_model["target"]["encoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
|
| 73 |
+
|
| 74 |
+
# Assigning
|
| 75 |
+
flax_model_encoder_layer_block = flax_model.params["encoder"]["block"][str(layer_index)]["layer"]
|
| 76 |
+
flax_model_encoder_layer_block["0"][encoder_attn_name]["k"]["kernel"] = t5x_attention_key
|
| 77 |
+
flax_model_encoder_layer_block["0"][encoder_attn_name]["o"]["kernel"] = t5x_attention_out
|
| 78 |
+
flax_model_encoder_layer_block["0"][encoder_attn_name]["q"]["kernel"] = t5x_attention_query
|
| 79 |
+
flax_model_encoder_layer_block["0"][encoder_attn_name]["v"]["kernel"] = t5x_attention_value
|
| 80 |
+
|
| 81 |
+
flax_model_encoder_layer_block["0"]["layer_norm"]["weight"] = t5x_attention_layer_norm
|
| 82 |
+
|
| 83 |
+
# Global input layer norm
|
| 84 |
+
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
|
| 85 |
+
flax_model_encoder_layer_block["0"][encoder_attn_name]["global_input_layer_norm"]["weight"] = (
|
| 86 |
+
t5x_global_layer_norm
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
if split_mlp_wi:
|
| 90 |
+
flax_model_encoder_layer_block["1"]["DenseReluDense"]["wi_0"]["kernel"] = t5x_mlp_wi_0
|
| 91 |
+
flax_model_encoder_layer_block["1"]["DenseReluDense"]["wi_1"]["kernel"] = t5x_mlp_wi_1
|
| 92 |
+
else:
|
| 93 |
+
flax_model_encoder_layer_block["1"]["DenseReluDense"]["wi"]["kernel"] = t5x_mlp_wi
|
| 94 |
+
|
| 95 |
+
flax_model_encoder_layer_block["1"]["DenseReluDense"]["wo"]["kernel"] = t5x_mlp_wo
|
| 96 |
+
flax_model_encoder_layer_block["1"]["layer_norm"]["weight"] = t5x_mlp_layer_norm
|
| 97 |
+
|
| 98 |
+
flax_model.params["encoder"]["block"][str(layer_index)]["layer"] = flax_model_encoder_layer_block
|
| 99 |
+
|
| 100 |
+
# Only for layer 0:
|
| 101 |
+
t5x_encoder_rel_embedding = t5x_model["target"]["encoder"]["relpos_bias"]["rel_embedding"].T
|
| 102 |
+
flax_model.params["encoder"]["block"]["0"]["layer"]["0"][encoder_attn_name]["relative_attention_bias"][
|
| 103 |
+
"embedding"
|
| 104 |
+
] = t5x_encoder_rel_embedding
|
| 105 |
+
|
| 106 |
+
# Side/global relative position_bias + layer norm
|
| 107 |
+
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
|
| 108 |
+
t5x_encoder_global_rel_embedding = t5x_model["target"]["encoder"]["side_relpos_bias"]["rel_embedding"].T
|
| 109 |
+
flax_model.params["encoder"]["block"]["0"]["layer"]["0"][encoder_attn_name]["global_relative_attention_bias"][
|
| 110 |
+
"embedding"
|
| 111 |
+
] = t5x_encoder_global_rel_embedding
|
| 112 |
+
|
| 113 |
+
# Assigning
|
| 114 |
+
t5x_encoder_norm = t5x_model["target"]["encoder"]["encoder_norm"]["scale"]
|
| 115 |
+
flax_model.params["encoder"]["final_layer_norm"]["weight"] = t5x_encoder_norm
|
| 116 |
+
|
| 117 |
+
# Decoder
|
| 118 |
+
for layer_index in range(config.num_layers):
|
| 119 |
+
layer_name = f"layers_{str(layer_index)}"
|
| 120 |
+
|
| 121 |
+
# Self-Attention
|
| 122 |
+
t5x_attention_key = t5x_model["target"]["decoder"][layer_name]["self_attention"]["key"]["kernel"]
|
| 123 |
+
t5x_attention_out = t5x_model["target"]["decoder"][layer_name]["self_attention"]["out"]["kernel"]
|
| 124 |
+
t5x_attention_query = t5x_model["target"]["decoder"][layer_name]["self_attention"]["query"]["kernel"]
|
| 125 |
+
t5x_attention_value = t5x_model["target"]["decoder"][layer_name]["self_attention"]["value"]["kernel"]
|
| 126 |
+
|
| 127 |
+
# Layer Normalization
|
| 128 |
+
t5x_pre_attention_layer_norm = t5x_model["target"]["decoder"][layer_name]["pre_self_attention_layer_norm"][
|
| 129 |
+
"scale"
|
| 130 |
+
]
|
| 131 |
+
|
| 132 |
+
# Encoder-Decoder-Attention
|
| 133 |
+
t5x_enc_dec_attention_module = t5x_model["target"]["decoder"][layer_name]["encoder_decoder_attention"]
|
| 134 |
+
t5x_enc_dec_attention_key = t5x_enc_dec_attention_module["key"]["kernel"]
|
| 135 |
+
t5x_enc_dec_attention_out = t5x_enc_dec_attention_module["out"]["kernel"]
|
| 136 |
+
t5x_enc_dec_attention_query = t5x_enc_dec_attention_module["query"]["kernel"]
|
| 137 |
+
t5x_enc_dec_attention_value = t5x_enc_dec_attention_module["value"]["kernel"]
|
| 138 |
+
|
| 139 |
+
# Layer Normalization
|
| 140 |
+
t5x_cross_layer_norm = t5x_model["target"]["decoder"][layer_name]["pre_cross_attention_layer_norm"]["scale"]
|
| 141 |
+
|
| 142 |
+
# MLP
|
| 143 |
+
if split_mlp_wi:
|
| 144 |
+
t5x_mlp_wi_0 = t5x_model["target"]["decoder"][layer_name]["mlp"]["wi_0"]["kernel"]
|
| 145 |
+
t5x_mlp_wi_1 = t5x_model["target"]["decoder"][layer_name]["mlp"]["wi_1"]["kernel"]
|
| 146 |
+
else:
|
| 147 |
+
t5x_mlp_wi = t5x_model["target"]["decoder"][layer_name]["mlp"]["wi"]["kernel"]
|
| 148 |
+
|
| 149 |
+
t5x_mlp_wo = t5x_model["target"]["decoder"][layer_name]["mlp"]["wo"]["kernel"]
|
| 150 |
+
|
| 151 |
+
# Layer Normalization
|
| 152 |
+
tx5_mlp_layer_norm = t5x_model["target"]["decoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
|
| 153 |
+
|
| 154 |
+
# Assigning
|
| 155 |
+
flax_model_decoder_layer_block = flax_model.params["decoder"]["block"][str(layer_index)]["layer"]
|
| 156 |
+
flax_model_decoder_layer_block["0"]["SelfAttention"]["k"]["kernel"] = t5x_attention_key
|
| 157 |
+
flax_model_decoder_layer_block["0"]["SelfAttention"]["o"]["kernel"] = t5x_attention_out
|
| 158 |
+
flax_model_decoder_layer_block["0"]["SelfAttention"]["q"]["kernel"] = t5x_attention_query
|
| 159 |
+
flax_model_decoder_layer_block["0"]["SelfAttention"]["v"]["kernel"] = t5x_attention_value
|
| 160 |
+
|
| 161 |
+
flax_model_decoder_layer_block["0"]["layer_norm"]["weight"] = t5x_pre_attention_layer_norm
|
| 162 |
+
|
| 163 |
+
flax_model_decoder_layer_block["1"]["EncDecAttention"]["k"]["kernel"] = t5x_enc_dec_attention_key
|
| 164 |
+
flax_model_decoder_layer_block["1"]["EncDecAttention"]["o"]["kernel"] = t5x_enc_dec_attention_out
|
| 165 |
+
flax_model_decoder_layer_block["1"]["EncDecAttention"]["q"]["kernel"] = t5x_enc_dec_attention_query
|
| 166 |
+
flax_model_decoder_layer_block["1"]["EncDecAttention"]["v"]["kernel"] = t5x_enc_dec_attention_value
|
| 167 |
+
|
| 168 |
+
flax_model_decoder_layer_block["1"]["layer_norm"]["weight"] = t5x_cross_layer_norm
|
| 169 |
+
|
| 170 |
+
if split_mlp_wi:
|
| 171 |
+
flax_model_decoder_layer_block["2"]["DenseReluDense"]["wi_0"]["kernel"] = t5x_mlp_wi_0
|
| 172 |
+
flax_model_decoder_layer_block["2"]["DenseReluDense"]["wi_1"]["kernel"] = t5x_mlp_wi_1
|
| 173 |
+
else:
|
| 174 |
+
flax_model_decoder_layer_block["2"]["DenseReluDense"]["wi"]["kernel"] = t5x_mlp_wi
|
| 175 |
+
|
| 176 |
+
flax_model_decoder_layer_block["2"]["DenseReluDense"]["wo"]["kernel"] = t5x_mlp_wo
|
| 177 |
+
|
| 178 |
+
flax_model_decoder_layer_block["2"]["layer_norm"]["weight"] = tx5_mlp_layer_norm
|
| 179 |
+
|
| 180 |
+
flax_model.params["decoder"]["block"][str(layer_index)]["layer"] = flax_model_decoder_layer_block
|
| 181 |
+
|
| 182 |
+
# Decoder Normalization
|
| 183 |
+
tx5_decoder_norm = t5x_model["target"]["decoder"]["decoder_norm"]["scale"]
|
| 184 |
+
flax_model.params["decoder"]["final_layer_norm"]["weight"] = tx5_decoder_norm
|
| 185 |
+
|
| 186 |
+
# Only for layer 0:
|
| 187 |
+
t5x_decoder_rel_embedding = t5x_model["target"]["decoder"]["relpos_bias"]["rel_embedding"].T
|
| 188 |
+
flax_model.params["decoder"]["block"]["0"]["layer"]["0"]["SelfAttention"]["relative_attention_bias"][
|
| 189 |
+
"embedding"
|
| 190 |
+
] = t5x_decoder_rel_embedding
|
| 191 |
+
|
| 192 |
+
# Token Embeddings
|
| 193 |
+
tx5_token_embeddings = t5x_model["target"]["token_embedder"]["embedding"]
|
| 194 |
+
flax_model.params["shared"]["embedding"] = tx5_token_embeddings
|
| 195 |
+
|
| 196 |
+
# LM Head (only in v1.1 and LongT5 checkpoints)
|
| 197 |
+
if "logits_dense" in t5x_model["target"]["decoder"]:
|
| 198 |
+
flax_model.params["lm_head"]["kernel"] = t5x_model["target"]["decoder"]["logits_dense"]["kernel"]
|
| 199 |
+
|
| 200 |
+
flax_model.save_pretrained(flax_dump_folder_path)
|
| 201 |
+
print("T5X Model was sucessfully converted!")
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
if __name__ == "__main__":
|
| 205 |
+
parser = argparse.ArgumentParser()
|
| 206 |
+
# Required parameters
|
| 207 |
+
parser.add_argument(
|
| 208 |
+
"--t5x_checkpoint_path", default=None, type=str, required=True, help="Path the T5X checkpoint."
|
| 209 |
+
)
|
| 210 |
+
parser.add_argument("--config_name", default=None, type=str, required=True, help="Config name of LongT5/T5 model.")
|
| 211 |
+
parser.add_argument(
|
| 212 |
+
"--flax_dump_folder_path", default=None, type=str, required=True, help="Path to the output FLAX model."
|
| 213 |
+
)
|
| 214 |
+
args = parser.parse_args()
|
| 215 |
+
convert_t5x_checkpoint_to_flax(args.t5x_checkpoint_path, args.config_name, args.flax_dump_folder_path)
|
vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/modeling_flax_longt5.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/longt5/modeling_longt5.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/mt5/__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_mt5 import *
|
| 22 |
+
from .modeling_flax_mt5 import *
|
| 23 |
+
from .modeling_mt5 import *
|
| 24 |
+
from .modeling_tf_mt5 import *
|
| 25 |
+
from .tokenization_mt5 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/mt5/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (615 Bytes). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/mt5/__pycache__/configuration_mt5.cpython-310.pyc
ADDED
|
Binary file (6.58 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/mt5/__pycache__/modeling_flax_mt5.cpython-310.pyc
ADDED
|
Binary file (3.92 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/mt5/__pycache__/modeling_mt5.cpython-310.pyc
ADDED
|
Binary file (69.3 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/mt5/__pycache__/modeling_tf_mt5.cpython-310.pyc
ADDED
|
Binary file (3.14 kB). View file
|
|
|