Stage Harbor release files 85501-86000
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/speech_to_text_2/modeling_speech_to_text_2.py +923 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/speech_to_text_2/processing_speech_to_text_2.py +116 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/speech_to_text_2/tokenization_speech_to_text_2.py +249 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/tapex/__init__.py +29 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/tapex/tokenization_tapex.py +1467 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/trajectory_transformer/__init__.py +57 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/trajectory_transformer/configuration_trajectory_transformer.py +152 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/trajectory_transformer/convert_trajectory_transformer_original_pytorch_checkpoint_to_pytorch.py +70 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/trajectory_transformer/modeling_trajectory_transformer.py +603 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/transfo_xl/__init__.py +93 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/transfo_xl/configuration_transfo_xl.py +186 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/transfo_xl/convert_transfo_xl_original_tf_checkpoint_to_pytorch.py +121 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl.py +1119 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl_utilities.py +178 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/transfo_xl/modeling_transfo_xl.py +1293 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/transfo_xl/modeling_transfo_xl_utilities.py +251 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/transfo_xl/tokenization_transfo_xl.py +818 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/tvlt/__init__.py +86 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/tvlt/configuration_tvlt.py +184 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/tvlt/feature_extraction_tvlt.py +230 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/tvlt/image_processing_tvlt.py +435 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/tvlt/modeling_tvlt.py +1288 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/tvlt/processing_tvlt.py +89 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/van/__init__.py +52 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/van/configuration_van.py +107 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/van/convert_van_to_pytorch.py +290 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/van/modeling_van.py +536 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/vit_hybrid/__init__.py +69 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/vit_hybrid/configuration_vit_hybrid.py +169 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/vit_hybrid/convert_vit_hybrid_timm_to_pytorch.py +282 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/vit_hybrid/image_processing_vit_hybrid.py +338 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/vit_hybrid/modeling_vit_hybrid.py +767 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/xlm_prophetnet/__init__.py +76 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/xlm_prophetnet/configuration_xlm_prophetnet.py +178 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/xlm_prophetnet/modeling_xlm_prophetnet.py +0 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/xlm_prophetnet/tokenization_xlm_prophetnet.py +323 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_anything/__init__.py +27 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_anything/configuration_depth_anything.py +168 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_anything/convert_depth_anything_to_hf.py +368 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_anything/modeling_depth_anything.py +468 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_pro/__init__.py +29 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_pro/configuration_depth_pro.py +205 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_pro/convert_depth_pro_weights_to_hf.py +254 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_pro/image_processing_depth_pro.py +389 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_pro/image_processing_depth_pro_fast.py +187 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_pro/modeling_depth_pro.py +1218 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/detr/__init__.py +31 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/detr/configuration_detr.py +289 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/detr/convert_detr_original_pytorch_checkpoint_to_pytorch.py +277 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/detr/convert_detr_to_pytorch.py +385 -0
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/speech_to_text_2/modeling_speech_to_text_2.py
ADDED
|
@@ -0,0 +1,923 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch Speech2Text2 model."""
|
| 16 |
+
|
| 17 |
+
import copy
|
| 18 |
+
import math
|
| 19 |
+
from typing import Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
from torch import nn
|
| 23 |
+
from torch.nn import CrossEntropyLoss
|
| 24 |
+
|
| 25 |
+
from ....activations import ACT2FN
|
| 26 |
+
from ....modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask
|
| 27 |
+
from ....modeling_outputs import BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions
|
| 28 |
+
from ....modeling_utils import PreTrainedModel
|
| 29 |
+
from ....utils import add_start_docstrings, logging, replace_return_docstrings
|
| 30 |
+
from .configuration_speech_to_text_2 import Speech2Text2Config
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
_CONFIG_FOR_DOC = "Speech2Text2Config"
|
| 36 |
+
_CHECKPOINT_FOR_DOC = "facebook/s2t-wav2vec2-large-en-de"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class Speech2Text2SinusoidalPositionalEmbedding(nn.Module):
|
| 40 |
+
"""This module produces sinusoidal positional embeddings of any length."""
|
| 41 |
+
|
| 42 |
+
def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None):
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.offset = 2
|
| 45 |
+
self.embedding_dim = embedding_dim
|
| 46 |
+
self.padding_idx = padding_idx
|
| 47 |
+
self.make_weights(num_positions + self.offset, embedding_dim, padding_idx)
|
| 48 |
+
|
| 49 |
+
def make_weights(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
|
| 50 |
+
emb_weights = self.get_embedding(num_embeddings, embedding_dim, padding_idx)
|
| 51 |
+
if hasattr(self, "weights"):
|
| 52 |
+
# in forward put the weights on the correct dtype and device of the param
|
| 53 |
+
emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device)
|
| 54 |
+
|
| 55 |
+
self.weights = nn.Parameter(emb_weights)
|
| 56 |
+
self.weights.requires_grad = False
|
| 57 |
+
self.weights.detach_()
|
| 58 |
+
|
| 59 |
+
@staticmethod
|
| 60 |
+
def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
|
| 61 |
+
"""
|
| 62 |
+
Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the
|
| 63 |
+
description in Section 3.5 of "Attention Is All You Need".
|
| 64 |
+
"""
|
| 65 |
+
half_dim = embedding_dim // 2
|
| 66 |
+
emb = math.log(10000) / (half_dim - 1)
|
| 67 |
+
emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb)
|
| 68 |
+
emb = torch.arange(num_embeddings, dtype=torch.int64).float().unsqueeze(1) * emb.unsqueeze(0)
|
| 69 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
|
| 70 |
+
if embedding_dim % 2 == 1:
|
| 71 |
+
# zero pad
|
| 72 |
+
emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
|
| 73 |
+
if padding_idx is not None:
|
| 74 |
+
emb[padding_idx, :] = 0
|
| 75 |
+
return emb.to(torch.get_default_dtype())
|
| 76 |
+
|
| 77 |
+
@torch.no_grad()
|
| 78 |
+
def forward(self, input_ids: torch.Tensor, past_key_values_length: int = 0):
|
| 79 |
+
bsz, seq_len = input_ids.size()
|
| 80 |
+
# Create the position ids from the input token ids. Any padded tokens remain padded.
|
| 81 |
+
position_ids = self.create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length).to(
|
| 82 |
+
input_ids.device
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
# expand embeddings if needed
|
| 86 |
+
max_pos = self.padding_idx + 1 + seq_len
|
| 87 |
+
if max_pos > self.weights.size(0):
|
| 88 |
+
self.make_weights(max_pos + self.offset, self.embedding_dim, self.padding_idx)
|
| 89 |
+
|
| 90 |
+
return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, -1).detach()
|
| 91 |
+
|
| 92 |
+
def create_position_ids_from_input_ids(
|
| 93 |
+
self, input_ids: torch.Tensor, padding_idx: int, past_key_values_length: Optional[int] = 0
|
| 94 |
+
):
|
| 95 |
+
"""
|
| 96 |
+
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding
|
| 97 |
+
symbols are ignored. This is modified from fairseq's `utils.make_positions`.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
x: torch.Tensor x:
|
| 101 |
+
Returns: torch.Tensor
|
| 102 |
+
"""
|
| 103 |
+
# The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
|
| 104 |
+
mask = input_ids.ne(padding_idx).int()
|
| 105 |
+
incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
|
| 106 |
+
return incremental_indices.long() + padding_idx
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class Speech2Text2Attention(nn.Module):
|
| 110 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 111 |
+
|
| 112 |
+
def __init__(
|
| 113 |
+
self,
|
| 114 |
+
embed_dim: int,
|
| 115 |
+
num_heads: int,
|
| 116 |
+
dropout: float = 0.0,
|
| 117 |
+
is_decoder: bool = False,
|
| 118 |
+
bias: bool = True,
|
| 119 |
+
is_causal: bool = False,
|
| 120 |
+
config: Optional[Speech2Text2Config] = None,
|
| 121 |
+
):
|
| 122 |
+
super().__init__()
|
| 123 |
+
self.embed_dim = embed_dim
|
| 124 |
+
self.num_heads = num_heads
|
| 125 |
+
self.dropout = dropout
|
| 126 |
+
self.head_dim = embed_dim // num_heads
|
| 127 |
+
self.config = config
|
| 128 |
+
|
| 129 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 130 |
+
raise ValueError(
|
| 131 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 132 |
+
f" and `num_heads`: {num_heads})."
|
| 133 |
+
)
|
| 134 |
+
self.scaling = self.head_dim**-0.5
|
| 135 |
+
self.is_decoder = is_decoder
|
| 136 |
+
self.is_causal = is_causal
|
| 137 |
+
|
| 138 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 139 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 140 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 141 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 142 |
+
|
| 143 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 144 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 145 |
+
|
| 146 |
+
def forward(
|
| 147 |
+
self,
|
| 148 |
+
hidden_states: torch.Tensor,
|
| 149 |
+
key_value_states: Optional[torch.Tensor] = None,
|
| 150 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 151 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 152 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 153 |
+
output_attentions: bool = False,
|
| 154 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 155 |
+
"""Input shape: Batch x Time x Channel"""
|
| 156 |
+
|
| 157 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 158 |
+
# for the decoder
|
| 159 |
+
is_cross_attention = key_value_states is not None
|
| 160 |
+
|
| 161 |
+
bsz, tgt_len, _ = hidden_states.size()
|
| 162 |
+
|
| 163 |
+
# get query proj
|
| 164 |
+
query_states = self.q_proj(hidden_states) * self.scaling
|
| 165 |
+
# get key, value proj
|
| 166 |
+
# `past_key_value[0].shape[2] == key_value_states.shape[1]`
|
| 167 |
+
# is checking that the `sequence_length` of the `past_key_value` is the same as
|
| 168 |
+
# the provided `key_value_states` to support prefix tuning
|
| 169 |
+
if (
|
| 170 |
+
is_cross_attention
|
| 171 |
+
and past_key_value is not None
|
| 172 |
+
and past_key_value[0].shape[2] == key_value_states.shape[1]
|
| 173 |
+
):
|
| 174 |
+
# reuse k,v, cross_attentions
|
| 175 |
+
key_states = past_key_value[0]
|
| 176 |
+
value_states = past_key_value[1]
|
| 177 |
+
elif is_cross_attention:
|
| 178 |
+
# cross_attentions
|
| 179 |
+
key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
|
| 180 |
+
value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
|
| 181 |
+
elif past_key_value is not None:
|
| 182 |
+
# reuse k, v, self_attention
|
| 183 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 184 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 185 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 186 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 187 |
+
else:
|
| 188 |
+
# self_attention
|
| 189 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 190 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 191 |
+
|
| 192 |
+
if self.is_decoder:
|
| 193 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 194 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 195 |
+
# key/value_states (first "if" case)
|
| 196 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 197 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 198 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 199 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 200 |
+
past_key_value = (key_states, value_states)
|
| 201 |
+
|
| 202 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 203 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
| 204 |
+
key_states = key_states.reshape(*proj_shape)
|
| 205 |
+
value_states = value_states.reshape(*proj_shape)
|
| 206 |
+
|
| 207 |
+
src_len = key_states.size(1)
|
| 208 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 209 |
+
|
| 210 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
| 211 |
+
raise ValueError(
|
| 212 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 213 |
+
f" {attn_weights.size()}"
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
if attention_mask is not None:
|
| 217 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 218 |
+
raise ValueError(
|
| 219 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
| 220 |
+
)
|
| 221 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
| 222 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 223 |
+
|
| 224 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 225 |
+
|
| 226 |
+
if layer_head_mask is not None:
|
| 227 |
+
if layer_head_mask.size() != (self.num_heads,):
|
| 228 |
+
raise ValueError(
|
| 229 |
+
f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
|
| 230 |
+
f" {layer_head_mask.size()}"
|
| 231 |
+
)
|
| 232 |
+
attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 233 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 234 |
+
|
| 235 |
+
if output_attentions:
|
| 236 |
+
# this operation is a bit awkward, but it's required to
|
| 237 |
+
# make sure that attn_weights keeps its gradient.
|
| 238 |
+
# In order to do so, attn_weights have to be reshaped
|
| 239 |
+
# twice and have to be reused in the following
|
| 240 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 241 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
| 242 |
+
else:
|
| 243 |
+
attn_weights_reshaped = None
|
| 244 |
+
|
| 245 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 246 |
+
|
| 247 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
| 248 |
+
|
| 249 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 250 |
+
raise ValueError(
|
| 251 |
+
f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 252 |
+
f" {attn_output.size()}"
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
| 256 |
+
attn_output = attn_output.transpose(1, 2)
|
| 257 |
+
|
| 258 |
+
# Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
|
| 259 |
+
# partitioned across GPUs when using tensor-parallelism.
|
| 260 |
+
attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
|
| 261 |
+
|
| 262 |
+
attn_output = self.out_proj(attn_output)
|
| 263 |
+
|
| 264 |
+
return attn_output, attn_weights_reshaped, past_key_value
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class Speech2Text2DecoderLayer(nn.Module):
|
| 268 |
+
def __init__(self, config: Speech2Text2Config):
|
| 269 |
+
super().__init__()
|
| 270 |
+
self.embed_dim = config.d_model
|
| 271 |
+
|
| 272 |
+
self.self_attn = Speech2Text2Attention(
|
| 273 |
+
embed_dim=self.embed_dim,
|
| 274 |
+
num_heads=config.decoder_attention_heads,
|
| 275 |
+
dropout=config.attention_dropout,
|
| 276 |
+
is_decoder=True,
|
| 277 |
+
)
|
| 278 |
+
self.dropout = config.dropout
|
| 279 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 280 |
+
self.activation_dropout = config.activation_dropout
|
| 281 |
+
|
| 282 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 283 |
+
|
| 284 |
+
if config.is_decoder:
|
| 285 |
+
self.encoder_attn = Speech2Text2Attention(
|
| 286 |
+
self.embed_dim,
|
| 287 |
+
config.decoder_attention_heads,
|
| 288 |
+
dropout=config.attention_dropout,
|
| 289 |
+
is_decoder=True,
|
| 290 |
+
)
|
| 291 |
+
self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 292 |
+
|
| 293 |
+
self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
|
| 294 |
+
self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
|
| 295 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 296 |
+
|
| 297 |
+
def forward(
|
| 298 |
+
self,
|
| 299 |
+
hidden_states: torch.Tensor,
|
| 300 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 301 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 302 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 303 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 304 |
+
cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
|
| 305 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 306 |
+
output_attentions: Optional[bool] = False,
|
| 307 |
+
use_cache: Optional[bool] = True,
|
| 308 |
+
):
|
| 309 |
+
"""
|
| 310 |
+
Args:
|
| 311 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 312 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 313 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 314 |
+
encoder_hidden_states (`torch.FloatTensor`):
|
| 315 |
+
cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 316 |
+
encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
|
| 317 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 318 |
+
layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
|
| 319 |
+
`(encoder_attention_heads,)`.
|
| 320 |
+
cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
|
| 321 |
+
size *(decoder_attention_heads,)*.
|
| 322 |
+
past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
|
| 323 |
+
output_attentions (`bool`, *optional*):
|
| 324 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 325 |
+
returned tensors for more detail.
|
| 326 |
+
"""
|
| 327 |
+
residual = hidden_states
|
| 328 |
+
|
| 329 |
+
# Self Attention
|
| 330 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 331 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 332 |
+
# add present self-attn cache to positions 1,2 of present_key_value tuple
|
| 333 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 334 |
+
hidden_states=hidden_states,
|
| 335 |
+
past_key_value=self_attn_past_key_value,
|
| 336 |
+
attention_mask=attention_mask,
|
| 337 |
+
layer_head_mask=layer_head_mask,
|
| 338 |
+
output_attentions=output_attentions,
|
| 339 |
+
)
|
| 340 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 341 |
+
hidden_states = residual + hidden_states
|
| 342 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 343 |
+
|
| 344 |
+
# Cross-Attention Block
|
| 345 |
+
cross_attn_present_key_value = None
|
| 346 |
+
cross_attn_weights = None
|
| 347 |
+
if encoder_hidden_states is not None:
|
| 348 |
+
residual = hidden_states
|
| 349 |
+
|
| 350 |
+
# cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
|
| 351 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 352 |
+
hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
|
| 353 |
+
hidden_states=hidden_states,
|
| 354 |
+
key_value_states=encoder_hidden_states,
|
| 355 |
+
attention_mask=encoder_attention_mask,
|
| 356 |
+
layer_head_mask=cross_attn_layer_head_mask,
|
| 357 |
+
past_key_value=cross_attn_past_key_value,
|
| 358 |
+
output_attentions=output_attentions,
|
| 359 |
+
)
|
| 360 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 361 |
+
hidden_states = residual + hidden_states
|
| 362 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 363 |
+
|
| 364 |
+
# add cross-attn to positions 3,4 of present_key_value tuple
|
| 365 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 366 |
+
|
| 367 |
+
# Fully Connected
|
| 368 |
+
residual = hidden_states
|
| 369 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 370 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 371 |
+
hidden_states = self.fc2(hidden_states)
|
| 372 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 373 |
+
hidden_states = residual + hidden_states
|
| 374 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 375 |
+
|
| 376 |
+
outputs = (hidden_states,)
|
| 377 |
+
|
| 378 |
+
if output_attentions:
|
| 379 |
+
outputs += (self_attn_weights, cross_attn_weights)
|
| 380 |
+
|
| 381 |
+
if use_cache:
|
| 382 |
+
outputs += (present_key_value,)
|
| 383 |
+
|
| 384 |
+
return outputs
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
class Speech2Text2PreTrainedModel(PreTrainedModel):
|
| 388 |
+
config_class = Speech2Text2Config
|
| 389 |
+
base_model_prefix = "model"
|
| 390 |
+
supports_gradient_checkpointing = True
|
| 391 |
+
|
| 392 |
+
def _init_weights(self, module):
|
| 393 |
+
std = self.config.init_std
|
| 394 |
+
if isinstance(module, (nn.Linear, nn.Conv1d)):
|
| 395 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 396 |
+
if module.bias is not None:
|
| 397 |
+
module.bias.data.zero_()
|
| 398 |
+
elif isinstance(module, nn.Embedding):
|
| 399 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 400 |
+
if module.padding_idx is not None:
|
| 401 |
+
module.weight.data[module.padding_idx].zero_()
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
SPEECH_TO_TEXT_2_START_DOCSTRING = r"""
|
| 405 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 406 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 407 |
+
etc.)
|
| 408 |
+
|
| 409 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 410 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 411 |
+
and behavior.
|
| 412 |
+
|
| 413 |
+
Parameters:
|
| 414 |
+
config ([`Speech2Text2Config`]):
|
| 415 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 416 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 417 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 418 |
+
"""
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
class Speech2Text2Decoder(Speech2Text2PreTrainedModel):
|
| 422 |
+
"""
|
| 423 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`Speech2Text2DecoderLayer`]
|
| 424 |
+
|
| 425 |
+
Args:
|
| 426 |
+
config: Speech2Text2Config
|
| 427 |
+
embed_tokens (nn.Embedding): output embedding
|
| 428 |
+
"""
|
| 429 |
+
|
| 430 |
+
def __init__(self, config: Speech2Text2Config):
|
| 431 |
+
super().__init__(config)
|
| 432 |
+
self.dropout = config.dropout
|
| 433 |
+
self.layerdrop = config.decoder_layerdrop
|
| 434 |
+
self.padding_idx = config.pad_token_id
|
| 435 |
+
self.max_target_positions = config.max_target_positions
|
| 436 |
+
self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 437 |
+
|
| 438 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
|
| 439 |
+
|
| 440 |
+
self.embed_positions = Speech2Text2SinusoidalPositionalEmbedding(
|
| 441 |
+
self.max_target_positions,
|
| 442 |
+
config.d_model,
|
| 443 |
+
self.padding_idx,
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
self.layers = nn.ModuleList([Speech2Text2DecoderLayer(config) for _ in range(config.decoder_layers)])
|
| 447 |
+
|
| 448 |
+
self.gradient_checkpointing = False
|
| 449 |
+
# Initialize weights and apply final processing
|
| 450 |
+
self.post_init()
|
| 451 |
+
|
| 452 |
+
def get_input_embeddings(self):
|
| 453 |
+
return self.embed_tokens
|
| 454 |
+
|
| 455 |
+
def set_input_embeddings(self, value):
|
| 456 |
+
self.embed_tokens = value
|
| 457 |
+
|
| 458 |
+
def forward(
|
| 459 |
+
self,
|
| 460 |
+
input_ids=None,
|
| 461 |
+
attention_mask=None,
|
| 462 |
+
encoder_hidden_states=None,
|
| 463 |
+
encoder_attention_mask=None,
|
| 464 |
+
head_mask=None,
|
| 465 |
+
cross_attn_head_mask=None,
|
| 466 |
+
past_key_values=None,
|
| 467 |
+
inputs_embeds=None,
|
| 468 |
+
use_cache=None,
|
| 469 |
+
output_attentions=None,
|
| 470 |
+
output_hidden_states=None,
|
| 471 |
+
return_dict=None,
|
| 472 |
+
):
|
| 473 |
+
r"""
|
| 474 |
+
Args:
|
| 475 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 476 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 477 |
+
provide it.
|
| 478 |
+
|
| 479 |
+
Indices can be obtained using [`Speech2Text2Tokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 480 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 481 |
+
|
| 482 |
+
[What are input IDs?](../glossary#input-ids)
|
| 483 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 484 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 485 |
+
|
| 486 |
+
- 1 for tokens that are **not masked**,
|
| 487 |
+
- 0 for tokens that are **masked**.
|
| 488 |
+
|
| 489 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 490 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 491 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 492 |
+
of the decoder.
|
| 493 |
+
encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
|
| 494 |
+
Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
|
| 495 |
+
selected in `[0, 1]`:
|
| 496 |
+
|
| 497 |
+
- 1 for tokens that are **not masked**,
|
| 498 |
+
- 0 for tokens that are **masked**.
|
| 499 |
+
|
| 500 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 501 |
+
head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 502 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 503 |
+
|
| 504 |
+
- 1 indicates the head is **not masked**,
|
| 505 |
+
- 0 indicates the head is **masked**.
|
| 506 |
+
|
| 507 |
+
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 508 |
+
Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention
|
| 509 |
+
on hidden heads. Mask values selected in `[0, 1]`:
|
| 510 |
+
|
| 511 |
+
- 1 indicates the head is **not masked**,
|
| 512 |
+
- 0 indicates the head is **masked**.
|
| 513 |
+
|
| 514 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 515 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 516 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
|
| 517 |
+
shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
| 518 |
+
|
| 519 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
|
| 520 |
+
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 521 |
+
|
| 522 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
|
| 523 |
+
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
|
| 524 |
+
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 525 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 526 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 527 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 528 |
+
than the model's internal embedding lookup matrix.
|
| 529 |
+
output_attentions (`bool`, *optional*):
|
| 530 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 531 |
+
returned tensors for more detail.
|
| 532 |
+
output_hidden_states (`bool`, *optional*):
|
| 533 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 534 |
+
for more detail.
|
| 535 |
+
return_dict (`bool`, *optional*):
|
| 536 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 537 |
+
"""
|
| 538 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 539 |
+
output_hidden_states = (
|
| 540 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 541 |
+
)
|
| 542 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 543 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 544 |
+
|
| 545 |
+
# retrieve input_ids and inputs_embeds
|
| 546 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 547 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 548 |
+
elif input_ids is not None:
|
| 549 |
+
input_shape = input_ids.size()
|
| 550 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 551 |
+
elif inputs_embeds is not None:
|
| 552 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 553 |
+
else:
|
| 554 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
| 555 |
+
|
| 556 |
+
# past_key_values_length
|
| 557 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
| 558 |
+
|
| 559 |
+
if inputs_embeds is None:
|
| 560 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 561 |
+
|
| 562 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
| 563 |
+
attention_mask, input_shape, inputs_embeds, past_key_values_length
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
# expand encoder attention mask
|
| 567 |
+
if encoder_hidden_states is not None and encoder_attention_mask is not None:
|
| 568 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 569 |
+
encoder_attention_mask = _prepare_4d_attention_mask(
|
| 570 |
+
encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
# embed positions
|
| 574 |
+
positions = self.embed_positions(input_ids, past_key_values_length=past_key_values_length)
|
| 575 |
+
|
| 576 |
+
hidden_states = inputs_embeds + positions
|
| 577 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 578 |
+
|
| 579 |
+
if self.gradient_checkpointing and self.training:
|
| 580 |
+
if use_cache:
|
| 581 |
+
logger.warning_once(
|
| 582 |
+
"`use_cache = True` is incompatible with gradient checkpointing. Setting `use_cache =" " False`..."
|
| 583 |
+
)
|
| 584 |
+
use_cache = False
|
| 585 |
+
|
| 586 |
+
# decoder layers
|
| 587 |
+
all_hidden_states = () if output_hidden_states else None
|
| 588 |
+
all_self_attns = () if output_attentions else None
|
| 589 |
+
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 590 |
+
next_decoder_cache = () if use_cache else None
|
| 591 |
+
|
| 592 |
+
# check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
|
| 593 |
+
for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
|
| 594 |
+
if attn_mask is not None:
|
| 595 |
+
if attn_mask.size()[0] != (len(self.layers)):
|
| 596 |
+
raise ValueError(
|
| 597 |
+
f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
|
| 598 |
+
f" {head_mask.size()[0]}."
|
| 599 |
+
)
|
| 600 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 601 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 602 |
+
if output_hidden_states:
|
| 603 |
+
all_hidden_states += (hidden_states,)
|
| 604 |
+
if self.training:
|
| 605 |
+
dropout_probability = torch.rand([])
|
| 606 |
+
if dropout_probability < self.layerdrop:
|
| 607 |
+
continue
|
| 608 |
+
|
| 609 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 610 |
+
|
| 611 |
+
if self.gradient_checkpointing and self.training:
|
| 612 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 613 |
+
decoder_layer.__call__,
|
| 614 |
+
hidden_states,
|
| 615 |
+
attention_mask,
|
| 616 |
+
encoder_hidden_states,
|
| 617 |
+
encoder_attention_mask,
|
| 618 |
+
head_mask[idx] if head_mask is not None else None,
|
| 619 |
+
cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
|
| 620 |
+
None,
|
| 621 |
+
)
|
| 622 |
+
else:
|
| 623 |
+
layer_outputs = decoder_layer(
|
| 624 |
+
hidden_states,
|
| 625 |
+
attention_mask=attention_mask,
|
| 626 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 627 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 628 |
+
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
|
| 629 |
+
cross_attn_layer_head_mask=(
|
| 630 |
+
cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
|
| 631 |
+
),
|
| 632 |
+
past_key_value=past_key_value,
|
| 633 |
+
output_attentions=output_attentions,
|
| 634 |
+
use_cache=use_cache,
|
| 635 |
+
)
|
| 636 |
+
hidden_states = layer_outputs[0]
|
| 637 |
+
|
| 638 |
+
if use_cache:
|
| 639 |
+
next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
|
| 640 |
+
|
| 641 |
+
if output_attentions:
|
| 642 |
+
all_self_attns += (layer_outputs[1],)
|
| 643 |
+
|
| 644 |
+
if encoder_hidden_states is not None:
|
| 645 |
+
all_cross_attentions += (layer_outputs[2],)
|
| 646 |
+
|
| 647 |
+
# add hidden states from the last decoder layer
|
| 648 |
+
if output_hidden_states:
|
| 649 |
+
all_hidden_states += (hidden_states,)
|
| 650 |
+
|
| 651 |
+
next_cache = next_decoder_cache if use_cache else None
|
| 652 |
+
if not return_dict:
|
| 653 |
+
return tuple(
|
| 654 |
+
v
|
| 655 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
|
| 656 |
+
if v is not None
|
| 657 |
+
)
|
| 658 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 659 |
+
last_hidden_state=hidden_states,
|
| 660 |
+
past_key_values=next_cache,
|
| 661 |
+
hidden_states=all_hidden_states,
|
| 662 |
+
attentions=all_self_attns,
|
| 663 |
+
cross_attentions=all_cross_attentions,
|
| 664 |
+
)
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
@add_start_docstrings(
|
| 668 |
+
"The Speech2Text2 Model with a language modeling head. Can be used for summarization.",
|
| 669 |
+
SPEECH_TO_TEXT_2_START_DOCSTRING,
|
| 670 |
+
)
|
| 671 |
+
class Speech2Text2DecoderWrapper(Speech2Text2PreTrainedModel):
|
| 672 |
+
"""
|
| 673 |
+
This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
|
| 674 |
+
used in combination with the [`EncoderDecoderModel`] framework.
|
| 675 |
+
"""
|
| 676 |
+
|
| 677 |
+
def __init__(self, config):
|
| 678 |
+
super().__init__(config)
|
| 679 |
+
self.decoder = Speech2Text2Decoder(config)
|
| 680 |
+
|
| 681 |
+
def forward(self, *args, **kwargs):
|
| 682 |
+
return self.decoder(*args, **kwargs)
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
@add_start_docstrings(
|
| 686 |
+
"The Speech2Text2 Decoder with a language modeling head. Can be used as the decoder part of"
|
| 687 |
+
" [`EncoderDecoderModel`] and [`SpeechEncoderDecoder`].",
|
| 688 |
+
SPEECH_TO_TEXT_2_START_DOCSTRING,
|
| 689 |
+
)
|
| 690 |
+
class Speech2Text2ForCausalLM(Speech2Text2PreTrainedModel):
|
| 691 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 692 |
+
|
| 693 |
+
def __init__(self, config):
|
| 694 |
+
config = copy.deepcopy(config)
|
| 695 |
+
config.is_decoder = True
|
| 696 |
+
config.is_encoder_decoder = False
|
| 697 |
+
super().__init__(config)
|
| 698 |
+
self.model = Speech2Text2DecoderWrapper(config)
|
| 699 |
+
|
| 700 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 701 |
+
|
| 702 |
+
# Initialize weights and apply final processing
|
| 703 |
+
self.post_init()
|
| 704 |
+
|
| 705 |
+
def get_input_embeddings(self):
|
| 706 |
+
return self.model.decoder.embed_tokens
|
| 707 |
+
|
| 708 |
+
def set_input_embeddings(self, value):
|
| 709 |
+
self.model.decoder.embed_tokens = value
|
| 710 |
+
|
| 711 |
+
def get_output_embeddings(self):
|
| 712 |
+
return self.lm_head
|
| 713 |
+
|
| 714 |
+
def set_output_embeddings(self, new_embeddings):
|
| 715 |
+
self.lm_head = new_embeddings
|
| 716 |
+
|
| 717 |
+
def set_decoder(self, decoder):
|
| 718 |
+
self.model.decoder = decoder
|
| 719 |
+
|
| 720 |
+
def get_decoder(self):
|
| 721 |
+
return self.model.decoder
|
| 722 |
+
|
| 723 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
|
| 724 |
+
def forward(
|
| 725 |
+
self,
|
| 726 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 727 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 728 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 729 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 730 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 731 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
| 732 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 733 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 734 |
+
labels: Optional[torch.LongTensor] = None,
|
| 735 |
+
use_cache: Optional[bool] = None,
|
| 736 |
+
output_attentions: Optional[bool] = None,
|
| 737 |
+
output_hidden_states: Optional[bool] = None,
|
| 738 |
+
return_dict: Optional[bool] = None,
|
| 739 |
+
) -> Union[Tuple[torch.FloatTensor], CausalLMOutputWithCrossAttentions]:
|
| 740 |
+
r"""
|
| 741 |
+
Args:
|
| 742 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 743 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 744 |
+
provide it.
|
| 745 |
+
|
| 746 |
+
Indices can be obtained using [`Speech2Text2Tokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 747 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 748 |
+
|
| 749 |
+
[What are input IDs?](../glossary#input-ids)
|
| 750 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 751 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 752 |
+
|
| 753 |
+
- 1 for tokens that are **not masked**,
|
| 754 |
+
- 0 for tokens that are **masked**.
|
| 755 |
+
|
| 756 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 757 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 758 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 759 |
+
if the model is configured as a decoder.
|
| 760 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 761 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
|
| 762 |
+
in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 763 |
+
head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 764 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 765 |
+
|
| 766 |
+
- 1 indicates the head is **not masked**,
|
| 767 |
+
- 0 indicates the head is **masked**.
|
| 768 |
+
|
| 769 |
+
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 770 |
+
Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
|
| 771 |
+
|
| 772 |
+
- 1 indicates the head is **not masked**,
|
| 773 |
+
- 0 indicates the head is **masked**.
|
| 774 |
+
|
| 775 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 776 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 777 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
|
| 778 |
+
shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
|
| 779 |
+
tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
|
| 780 |
+
|
| 781 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
|
| 782 |
+
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 783 |
+
|
| 784 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
|
| 785 |
+
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
|
| 786 |
+
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 787 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 788 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 789 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 790 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 791 |
+
use_cache (`bool`, *optional*):
|
| 792 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 793 |
+
(see `past_key_values`).
|
| 794 |
+
|
| 795 |
+
- 1 for tokens that are **not masked**,
|
| 796 |
+
- 0 for tokens that are **masked**.
|
| 797 |
+
output_attentions (`bool`, *optional*):
|
| 798 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 799 |
+
returned tensors for more detail.
|
| 800 |
+
output_hidden_states (`bool`, *optional*):
|
| 801 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 802 |
+
for more detail.
|
| 803 |
+
return_dict (`bool`, *optional*):
|
| 804 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 805 |
+
|
| 806 |
+
Returns:
|
| 807 |
+
|
| 808 |
+
Example:
|
| 809 |
+
|
| 810 |
+
```python
|
| 811 |
+
>>> from transformers import (
|
| 812 |
+
... SpeechEncoderDecoderModel,
|
| 813 |
+
... Speech2Text2ForCausalLM,
|
| 814 |
+
... Wav2Vec2Model,
|
| 815 |
+
... Speech2Text2Config,
|
| 816 |
+
... Wav2Vec2Config,
|
| 817 |
+
... Wav2Vec2FeatureExtractor,
|
| 818 |
+
... Speech2Text2Tokenizer,
|
| 819 |
+
... )
|
| 820 |
+
>>> from datasets import load_dataset
|
| 821 |
+
|
| 822 |
+
>>> feature_extractor = Wav2Vec2FeatureExtractor()
|
| 823 |
+
>>> tokenizer = Speech2Text2Tokenizer.from_pretrained("facebook/s2t-wav2vec2-large-en-de")
|
| 824 |
+
|
| 825 |
+
>>> encoder = Wav2Vec2Model(Wav2Vec2Config())
|
| 826 |
+
>>> decoder = Speech2Text2ForCausalLM(Speech2Text2Config())
|
| 827 |
+
>>> # init random speech2text model
|
| 828 |
+
|
| 829 |
+
>>> model = SpeechEncoderDecoderModel(encoder=encoder, decoder=decoder)
|
| 830 |
+
>>> model.config.pad_token_id = tokenizer.pad_token_id
|
| 831 |
+
>>> model.config.decoder_start_token_id = tokenizer.bos_token_id
|
| 832 |
+
>>> # pre-process inputs and labels
|
| 833 |
+
|
| 834 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 835 |
+
>>> inputs = feature_extractor(
|
| 836 |
+
... ds[0]["audio"]["array"], sampling_rate=ds[0]["audio"]["sampling_rate"], return_tensors="pt"
|
| 837 |
+
... )
|
| 838 |
+
>>> input_values = inputs.input_values
|
| 839 |
+
>>> decoder_input_ids = tokenizer(ds[0]["text"], return_tensors="pt").input_ids
|
| 840 |
+
>>> # compute loss
|
| 841 |
+
|
| 842 |
+
>>> loss = model(inputs=input_values, labels=decoder_input_ids).loss
|
| 843 |
+
>>> # backprop loss
|
| 844 |
+
|
| 845 |
+
>>> loss.backward() # doctest: +IGNORE_RESULT
|
| 846 |
+
```"""
|
| 847 |
+
|
| 848 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 849 |
+
output_hidden_states = (
|
| 850 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 851 |
+
)
|
| 852 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 853 |
+
|
| 854 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 855 |
+
outputs = self.model.decoder(
|
| 856 |
+
input_ids=input_ids,
|
| 857 |
+
attention_mask=attention_mask,
|
| 858 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 859 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 860 |
+
head_mask=head_mask,
|
| 861 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 862 |
+
past_key_values=past_key_values,
|
| 863 |
+
inputs_embeds=inputs_embeds,
|
| 864 |
+
use_cache=use_cache,
|
| 865 |
+
output_attentions=output_attentions,
|
| 866 |
+
output_hidden_states=output_hidden_states,
|
| 867 |
+
return_dict=return_dict,
|
| 868 |
+
)
|
| 869 |
+
|
| 870 |
+
logits = self.lm_head(outputs[0])
|
| 871 |
+
|
| 872 |
+
loss = None
|
| 873 |
+
if labels is not None:
|
| 874 |
+
loss_fct = CrossEntropyLoss()
|
| 875 |
+
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 876 |
+
|
| 877 |
+
if not return_dict:
|
| 878 |
+
output = (logits,) + outputs[1:]
|
| 879 |
+
return (loss,) + output if loss is not None else output
|
| 880 |
+
|
| 881 |
+
return CausalLMOutputWithCrossAttentions(
|
| 882 |
+
loss=loss,
|
| 883 |
+
logits=logits,
|
| 884 |
+
past_key_values=outputs.past_key_values,
|
| 885 |
+
hidden_states=outputs.hidden_states,
|
| 886 |
+
attentions=outputs.attentions,
|
| 887 |
+
cross_attentions=outputs.cross_attentions,
|
| 888 |
+
)
|
| 889 |
+
|
| 890 |
+
def prepare_inputs_for_generation(
|
| 891 |
+
self, input_ids, past_key_values=None, attention_mask=None, use_cache=None, **kwargs
|
| 892 |
+
):
|
| 893 |
+
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
|
| 894 |
+
if attention_mask is None:
|
| 895 |
+
attention_mask = input_ids.new_ones(input_ids.shape)
|
| 896 |
+
|
| 897 |
+
if past_key_values:
|
| 898 |
+
past_length = past_key_values[0][0].shape[2]
|
| 899 |
+
|
| 900 |
+
# Some generation methods already pass only the last input ID
|
| 901 |
+
if input_ids.shape[1] > past_length:
|
| 902 |
+
remove_prefix_length = past_length
|
| 903 |
+
else:
|
| 904 |
+
# Default to old behavior: keep only final ID
|
| 905 |
+
remove_prefix_length = input_ids.shape[1] - 1
|
| 906 |
+
|
| 907 |
+
input_ids = input_ids[:, remove_prefix_length:]
|
| 908 |
+
# first step, decoder_cached_states are empty
|
| 909 |
+
return {
|
| 910 |
+
"input_ids": input_ids, # encoder_outputs is defined. input_ids not needed
|
| 911 |
+
"attention_mask": attention_mask,
|
| 912 |
+
"past_key_values": past_key_values,
|
| 913 |
+
"use_cache": use_cache,
|
| 914 |
+
}
|
| 915 |
+
|
| 916 |
+
@staticmethod
|
| 917 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 918 |
+
reordered_past = ()
|
| 919 |
+
for layer_past in past_key_values:
|
| 920 |
+
reordered_past += (
|
| 921 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 922 |
+
)
|
| 923 |
+
return reordered_past
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/speech_to_text_2/processing_speech_to_text_2.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Speech processor class for Speech2Text2
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import warnings
|
| 20 |
+
from contextlib import contextmanager
|
| 21 |
+
|
| 22 |
+
from ....processing_utils import ProcessorMixin
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Speech2Text2Processor(ProcessorMixin):
|
| 26 |
+
r"""
|
| 27 |
+
Constructs a Speech2Text2 processor which wraps a Speech2Text2 feature extractor and a Speech2Text2 tokenizer into
|
| 28 |
+
a single processor.
|
| 29 |
+
|
| 30 |
+
[`Speech2Text2Processor`] offers all the functionalities of [`AutoFeatureExtractor`] and [`Speech2Text2Tokenizer`].
|
| 31 |
+
See the [`~Speech2Text2Processor.__call__`] and [`~Speech2Text2Processor.decode`] for more information.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
feature_extractor (`AutoFeatureExtractor`):
|
| 35 |
+
An instance of [`AutoFeatureExtractor`]. The feature extractor is a required input.
|
| 36 |
+
tokenizer (`Speech2Text2Tokenizer`):
|
| 37 |
+
An instance of [`Speech2Text2Tokenizer`]. The tokenizer is a required input.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
feature_extractor_class = "AutoFeatureExtractor"
|
| 41 |
+
tokenizer_class = "Speech2Text2Tokenizer"
|
| 42 |
+
|
| 43 |
+
def __init__(self, feature_extractor, tokenizer):
|
| 44 |
+
super().__init__(feature_extractor, tokenizer)
|
| 45 |
+
self.current_processor = self.feature_extractor
|
| 46 |
+
self._in_target_context_manager = False
|
| 47 |
+
|
| 48 |
+
def __call__(self, *args, **kwargs):
|
| 49 |
+
"""
|
| 50 |
+
When used in normal mode, this method forwards all its arguments to AutoFeatureExtractor's
|
| 51 |
+
[`~AutoFeatureExtractor.__call__`] and returns its output. If used in the context
|
| 52 |
+
[`~Speech2Text2Processor.as_target_processor`] this method forwards all its arguments to
|
| 53 |
+
Speech2Text2Tokenizer's [`~Speech2Text2Tokenizer.__call__`]. Please refer to the doctsring of the above two
|
| 54 |
+
methods for more information.
|
| 55 |
+
"""
|
| 56 |
+
# For backward compatibility
|
| 57 |
+
if self._in_target_context_manager:
|
| 58 |
+
return self.current_processor(*args, **kwargs)
|
| 59 |
+
|
| 60 |
+
if "raw_speech" in kwargs:
|
| 61 |
+
warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.")
|
| 62 |
+
audio = kwargs.pop("raw_speech")
|
| 63 |
+
else:
|
| 64 |
+
audio = kwargs.pop("audio", None)
|
| 65 |
+
sampling_rate = kwargs.pop("sampling_rate", None)
|
| 66 |
+
text = kwargs.pop("text", None)
|
| 67 |
+
if len(args) > 0:
|
| 68 |
+
audio = args[0]
|
| 69 |
+
args = args[1:]
|
| 70 |
+
|
| 71 |
+
if audio is None and text is None:
|
| 72 |
+
raise ValueError("You need to specify either an `audio` or `text` input to process.")
|
| 73 |
+
|
| 74 |
+
if audio is not None:
|
| 75 |
+
inputs = self.feature_extractor(audio, *args, sampling_rate=sampling_rate, **kwargs)
|
| 76 |
+
if text is not None:
|
| 77 |
+
encodings = self.tokenizer(text, **kwargs)
|
| 78 |
+
|
| 79 |
+
if text is None:
|
| 80 |
+
return inputs
|
| 81 |
+
elif audio is None:
|
| 82 |
+
return encodings
|
| 83 |
+
else:
|
| 84 |
+
inputs["labels"] = encodings["input_ids"]
|
| 85 |
+
return inputs
|
| 86 |
+
|
| 87 |
+
def batch_decode(self, *args, **kwargs):
|
| 88 |
+
"""
|
| 89 |
+
This method forwards all its arguments to Speech2Text2Tokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
|
| 90 |
+
refer to the docstring of this method for more information.
|
| 91 |
+
"""
|
| 92 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
| 93 |
+
|
| 94 |
+
def decode(self, *args, **kwargs):
|
| 95 |
+
"""
|
| 96 |
+
This method forwards all its arguments to Speech2Text2Tokenizer's [`~PreTrainedTokenizer.decode`]. Please refer
|
| 97 |
+
to the docstring of this method for more information.
|
| 98 |
+
"""
|
| 99 |
+
return self.tokenizer.decode(*args, **kwargs)
|
| 100 |
+
|
| 101 |
+
@contextmanager
|
| 102 |
+
def as_target_processor(self):
|
| 103 |
+
"""
|
| 104 |
+
Temporarily sets the tokenizer for processing the input. Useful for encoding the labels when fine-tuning
|
| 105 |
+
Speech2Text2.
|
| 106 |
+
"""
|
| 107 |
+
warnings.warn(
|
| 108 |
+
"`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
|
| 109 |
+
"labels by using the argument `text` of the regular `__call__` method (either in the same call as "
|
| 110 |
+
"your audio inputs, or in a separate call."
|
| 111 |
+
)
|
| 112 |
+
self._in_target_context_manager = True
|
| 113 |
+
self.current_processor = self.tokenizer
|
| 114 |
+
yield
|
| 115 |
+
self.current_processor = self.feature_extractor
|
| 116 |
+
self._in_target_context_manager = False
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/speech_to_text_2/tokenization_speech_to_text_2.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Facebook Inc. and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization class for Speech2Text2."""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
from typing import Dict, List, Optional, Tuple
|
| 20 |
+
|
| 21 |
+
from ....tokenization_utils import PreTrainedTokenizer
|
| 22 |
+
from ....utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
VOCAB_FILES_NAMES = {
|
| 29 |
+
"vocab_file": "vocab.json",
|
| 30 |
+
"tokenizer_config_file": "tokenizer_config.json",
|
| 31 |
+
"merges_file": "merges.txt",
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
BPE_TOKEN_MERGES = "</w>"
|
| 36 |
+
BPE_TOKEN_VOCAB = "@@ "
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def get_pairs(word):
|
| 40 |
+
"""
|
| 41 |
+
Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length
|
| 42 |
+
strings)
|
| 43 |
+
"""
|
| 44 |
+
pairs = set()
|
| 45 |
+
prev_char = word[0]
|
| 46 |
+
for char in word[1:]:
|
| 47 |
+
pairs.add((prev_char, char))
|
| 48 |
+
prev_char = char
|
| 49 |
+
return pairs
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# Speech2Text2 has no max input length
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class Speech2Text2Tokenizer(PreTrainedTokenizer):
|
| 56 |
+
"""
|
| 57 |
+
Constructs a Speech2Text2Tokenizer.
|
| 58 |
+
|
| 59 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains some of the main methods. Users should refer to
|
| 60 |
+
the superclass for more information regarding such methods.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
vocab_file (`str`):
|
| 64 |
+
File containing the vocabulary.
|
| 65 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 66 |
+
The beginning of sentence token.
|
| 67 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 68 |
+
The end of sentence token.
|
| 69 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 70 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 71 |
+
token instead.
|
| 72 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 73 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 74 |
+
|
| 75 |
+
**kwargs
|
| 76 |
+
Additional keyword arguments passed along to [`PreTrainedTokenizer`]
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 80 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 81 |
+
|
| 82 |
+
def __init__(
|
| 83 |
+
self,
|
| 84 |
+
vocab_file,
|
| 85 |
+
bos_token="<s>",
|
| 86 |
+
pad_token="<pad>",
|
| 87 |
+
eos_token="</s>",
|
| 88 |
+
unk_token="<unk>",
|
| 89 |
+
do_lower_case=False,
|
| 90 |
+
merges_file=None,
|
| 91 |
+
**kwargs,
|
| 92 |
+
):
|
| 93 |
+
self.do_lower_case = do_lower_case
|
| 94 |
+
|
| 95 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
| 96 |
+
self.encoder = json.load(vocab_handle)
|
| 97 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 98 |
+
|
| 99 |
+
if merges_file is None:
|
| 100 |
+
logger.info(f"No merges files provided. {self.__class__.__name__} can only be used for decoding.")
|
| 101 |
+
|
| 102 |
+
self.bpe_ranks = None
|
| 103 |
+
self.cache = None
|
| 104 |
+
else:
|
| 105 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
| 106 |
+
merges = merges_handle.read().split("\n")[:-1]
|
| 107 |
+
|
| 108 |
+
merges = [tuple(merge.split()[:2]) for merge in merges]
|
| 109 |
+
self.bpe_ranks = dict(zip(merges, range(len(merges))))
|
| 110 |
+
self.cache = {}
|
| 111 |
+
super().__init__(
|
| 112 |
+
unk_token=unk_token,
|
| 113 |
+
bos_token=bos_token,
|
| 114 |
+
eos_token=eos_token,
|
| 115 |
+
pad_token=pad_token,
|
| 116 |
+
do_lower_case=do_lower_case,
|
| 117 |
+
**kwargs,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
@property
|
| 121 |
+
def vocab_size(self) -> int:
|
| 122 |
+
return len(self.decoder)
|
| 123 |
+
|
| 124 |
+
def get_vocab(self) -> Dict:
|
| 125 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
| 126 |
+
|
| 127 |
+
def bpe(self, token):
|
| 128 |
+
word = tuple(token[:-1]) + (token[-1] + BPE_TOKEN_MERGES,)
|
| 129 |
+
if token in self.cache:
|
| 130 |
+
return self.cache[token]
|
| 131 |
+
pairs = get_pairs(word)
|
| 132 |
+
|
| 133 |
+
if not pairs:
|
| 134 |
+
return token
|
| 135 |
+
|
| 136 |
+
while True:
|
| 137 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
| 138 |
+
if bigram not in self.bpe_ranks:
|
| 139 |
+
break
|
| 140 |
+
first, second = bigram
|
| 141 |
+
new_word = []
|
| 142 |
+
i = 0
|
| 143 |
+
while i < len(word):
|
| 144 |
+
try:
|
| 145 |
+
j = word.index(first, i)
|
| 146 |
+
except ValueError:
|
| 147 |
+
new_word.extend(word[i:])
|
| 148 |
+
break
|
| 149 |
+
else:
|
| 150 |
+
new_word.extend(word[i:j])
|
| 151 |
+
i = j
|
| 152 |
+
|
| 153 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
| 154 |
+
new_word.append(first + second)
|
| 155 |
+
i += 2
|
| 156 |
+
else:
|
| 157 |
+
new_word.append(word[i])
|
| 158 |
+
i += 1
|
| 159 |
+
new_word = tuple(new_word)
|
| 160 |
+
word = new_word
|
| 161 |
+
if len(word) == 1:
|
| 162 |
+
break
|
| 163 |
+
else:
|
| 164 |
+
pairs = get_pairs(word)
|
| 165 |
+
word = " ".join(word)
|
| 166 |
+
if word == "\n " + BPE_TOKEN_MERGES:
|
| 167 |
+
word = "\n" + BPE_TOKEN_MERGES
|
| 168 |
+
|
| 169 |
+
if word.endswith(BPE_TOKEN_MERGES):
|
| 170 |
+
word = word.replace(BPE_TOKEN_MERGES, "")
|
| 171 |
+
|
| 172 |
+
word = word.replace(" ", BPE_TOKEN_VOCAB)
|
| 173 |
+
self.cache[token] = word
|
| 174 |
+
return word
|
| 175 |
+
|
| 176 |
+
def _tokenize(self, text):
|
| 177 |
+
"""Tokenize a string."""
|
| 178 |
+
|
| 179 |
+
if self.bpe_ranks is None:
|
| 180 |
+
raise ValueError(
|
| 181 |
+
"This tokenizer was instantiated without a `merges.txt` file, so"
|
| 182 |
+
" that it can only be used for decoding, not for encoding. "
|
| 183 |
+
"Make sure to provide `merges.txt` file at instantiation to enable "
|
| 184 |
+
"encoding."
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
if self.do_lower_case:
|
| 188 |
+
text = text.lower()
|
| 189 |
+
|
| 190 |
+
text = text.split()
|
| 191 |
+
|
| 192 |
+
split_tokens = []
|
| 193 |
+
for token in text:
|
| 194 |
+
if token:
|
| 195 |
+
split_tokens.extend(list(self.bpe(token).split(" ")))
|
| 196 |
+
|
| 197 |
+
return split_tokens
|
| 198 |
+
|
| 199 |
+
def _convert_token_to_id(self, token: str) -> int:
|
| 200 |
+
"""Converts a token (str) in an index (integer) using the vocab."""
|
| 201 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
| 202 |
+
|
| 203 |
+
def _convert_id_to_token(self, index: int) -> str:
|
| 204 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 205 |
+
result = self.decoder.get(index, self.unk_token)
|
| 206 |
+
return result
|
| 207 |
+
|
| 208 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str:
|
| 209 |
+
"""
|
| 210 |
+
Converts a list of output tokens into a single string.
|
| 211 |
+
"""
|
| 212 |
+
# combine tokens
|
| 213 |
+
string = " ".join(tokens)
|
| 214 |
+
|
| 215 |
+
# make sure @@ tokens are concatenated
|
| 216 |
+
string = "".join(string.split(BPE_TOKEN_VOCAB))
|
| 217 |
+
|
| 218 |
+
return string
|
| 219 |
+
|
| 220 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 221 |
+
if not os.path.isdir(save_directory):
|
| 222 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 223 |
+
return
|
| 224 |
+
vocab_file = os.path.join(
|
| 225 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 226 |
+
)
|
| 227 |
+
merges_file = os.path.join(
|
| 228 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
| 232 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
| 233 |
+
|
| 234 |
+
index = 0
|
| 235 |
+
if self.bpe_ranks is None:
|
| 236 |
+
return (vocab_file,)
|
| 237 |
+
|
| 238 |
+
with open(merges_file, "w", encoding="utf-8") as writer:
|
| 239 |
+
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
|
| 240 |
+
if index != token_index:
|
| 241 |
+
logger.warning(
|
| 242 |
+
f"Saving vocabulary to {merges_file}: BPE merge indices are not consecutive."
|
| 243 |
+
" Please check that the tokenizer is not corrupted!"
|
| 244 |
+
)
|
| 245 |
+
index = token_index
|
| 246 |
+
writer.write(" ".join(bpe_tokens) + "\n")
|
| 247 |
+
index += 1
|
| 248 |
+
|
| 249 |
+
return (vocab_file, merges_file)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/tapex/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ....utils import _LazyModule
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_import_structure = {"tokenization_tapex": ["TapexTokenizer"]}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from .tokenization_tapex import TapexTokenizer
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
else:
|
| 27 |
+
import sys
|
| 28 |
+
|
| 29 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/tapex/tokenization_tapex.py
ADDED
|
@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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization classes for TAPEX."""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import random
|
| 20 |
+
from functools import lru_cache
|
| 21 |
+
from typing import Dict, List, Optional, Tuple, Union
|
| 22 |
+
|
| 23 |
+
import regex as re
|
| 24 |
+
|
| 25 |
+
from ....file_utils import ExplicitEnum, PaddingStrategy, TensorType, add_end_docstrings, is_pandas_available
|
| 26 |
+
from ....tokenization_utils import AddedToken, PreTrainedTokenizer
|
| 27 |
+
from ....tokenization_utils_base import ENCODE_KWARGS_DOCSTRING, BatchEncoding, TextInput, TruncationStrategy
|
| 28 |
+
from ....utils import logging
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
if is_pandas_available():
|
| 32 |
+
import pandas as pd
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
logger = logging.get_logger(__name__)
|
| 36 |
+
|
| 37 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class TapexTruncationStrategy(ExplicitEnum):
|
| 41 |
+
"""
|
| 42 |
+
Possible values for the `truncation` argument in [`~TapasTokenizer.__call__`]. Useful for tab-completion in an IDE.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
DROP_ROWS_TO_FIT = "drop_rows_to_fit"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING = r"""
|
| 49 |
+
add_special_tokens (`bool`, *optional*, defaults to `True`):
|
| 50 |
+
Whether or not to encode the sequences with the special tokens relative to their model.
|
| 51 |
+
padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `False`):
|
| 52 |
+
Activates and controls padding. Accepts the following values:
|
| 53 |
+
|
| 54 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
| 55 |
+
sequence if provided).
|
| 56 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
| 57 |
+
acceptable input length for the model if that argument is not provided.
|
| 58 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
| 59 |
+
lengths).
|
| 60 |
+
truncation (`bool`, `str`, [`TapexTruncationStrategy`] or [`~tokenization_utils_base.TruncationStrategy`],
|
| 61 |
+
*optional*, defaults to `False`):
|
| 62 |
+
|
| 63 |
+
Activates and controls truncation. Accepts the following values:
|
| 64 |
+
|
| 65 |
+
- `'drop_rows_to_fit'`: Truncate to a maximum length specified with the argument `max_length` or to the
|
| 66 |
+
maximum acceptable input length for the model if that argument is not provided. This will truncate
|
| 67 |
+
row by row, removing rows from the table.
|
| 68 |
+
- `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or
|
| 69 |
+
to the maximum acceptable input length for the model if that argument is not provided. This will
|
| 70 |
+
truncate token by token, removing a token from the longest sequence in the pair if a pair of
|
| 71 |
+
sequences (or a batch of pairs) is provided.
|
| 72 |
+
- `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
|
| 73 |
+
maximum acceptable input length for the model if that argument is not provided. This will only
|
| 74 |
+
truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
|
| 75 |
+
- `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
|
| 76 |
+
maximum acceptable input length for the model if that argument is not provided. This will only
|
| 77 |
+
truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
|
| 78 |
+
- `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
|
| 79 |
+
greater than the model maximum admissible input size).
|
| 80 |
+
max_length (`int`, *optional*):
|
| 81 |
+
Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to
|
| 82 |
+
`None`, this will use the predefined model maximum length if a maximum length is required by one of the
|
| 83 |
+
truncation/padding parameters. If the model has no specific maximum input length (like XLNet)
|
| 84 |
+
truncation/padding to a maximum length will be deactivated.
|
| 85 |
+
stride (`int`, *optional*, defaults to 0):
|
| 86 |
+
If set to a number along with `max_length`, the overflowing tokens returned when
|
| 87 |
+
`return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence
|
| 88 |
+
returned to provide some overlap between truncated and overflowing sequences. The value of this
|
| 89 |
+
argument defines the number of overlapping tokens.
|
| 90 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 91 |
+
If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
|
| 92 |
+
the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
|
| 93 |
+
return_tensors (`str` or [`~file_utils.TensorType`], *optional*):
|
| 94 |
+
If set, will return tensors instead of list of python integers. Acceptable values are:
|
| 95 |
+
|
| 96 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 97 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 98 |
+
- `'np'`: Return Numpy `np.ndarray` objects.
|
| 99 |
+
"""
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@lru_cache()
|
| 103 |
+
def bytes_to_unicode():
|
| 104 |
+
"""
|
| 105 |
+
Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
|
| 106 |
+
characters the bpe code barfs on. The reversible bpe codes work on unicode strings. This means you need a large #
|
| 107 |
+
of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset
|
| 108 |
+
you end up needing around 5K for decent coverage. This is a significant percentage of your normal, say, 32K bpe
|
| 109 |
+
vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
|
| 110 |
+
"""
|
| 111 |
+
bs = (
|
| 112 |
+
list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
|
| 113 |
+
)
|
| 114 |
+
cs = bs[:]
|
| 115 |
+
n = 0
|
| 116 |
+
for b in range(2**8):
|
| 117 |
+
if b not in bs:
|
| 118 |
+
bs.append(b)
|
| 119 |
+
cs.append(2**8 + n)
|
| 120 |
+
n += 1
|
| 121 |
+
cs = [chr(n) for n in cs]
|
| 122 |
+
return dict(zip(bs, cs))
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def get_pairs(word):
|
| 126 |
+
"""
|
| 127 |
+
Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length
|
| 128 |
+
strings).
|
| 129 |
+
"""
|
| 130 |
+
pairs = set()
|
| 131 |
+
prev_char = word[0]
|
| 132 |
+
for char in word[1:]:
|
| 133 |
+
pairs.add((prev_char, char))
|
| 134 |
+
prev_char = char
|
| 135 |
+
return pairs
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class IndexedRowTableLinearize:
|
| 139 |
+
"""
|
| 140 |
+
FORMAT: col: col1 | col2 | col 3 row 1 : val1 | val2 | val3 row 2 : ...
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
def process_table(self, table_content: Dict):
|
| 144 |
+
"""
|
| 145 |
+
Given a table, TableLinearize aims at converting it into a flatten sequence with special symbols.
|
| 146 |
+
"""
|
| 147 |
+
assert "header" in table_content and "rows" in table_content, self.PROMPT_MESSAGE
|
| 148 |
+
# process header
|
| 149 |
+
table_str = self.process_header(table_content["header"]) + " "
|
| 150 |
+
# process rows
|
| 151 |
+
for i, row_example in enumerate(table_content["rows"]):
|
| 152 |
+
# NOTE: the row should start from row 1 instead of 0
|
| 153 |
+
table_str += self.process_row(row_example, row_index=i + 1) + " "
|
| 154 |
+
return table_str.strip()
|
| 155 |
+
|
| 156 |
+
def process_header(self, headers: List):
|
| 157 |
+
"""
|
| 158 |
+
Given a list of headers, TableLinearize aims at converting it into a flatten sequence with special symbols.
|
| 159 |
+
"""
|
| 160 |
+
return "col : " + " | ".join(headers)
|
| 161 |
+
|
| 162 |
+
def process_row(self, row: List, row_index: int):
|
| 163 |
+
"""
|
| 164 |
+
Given a row, TableLinearize aims at converting it into a flatten sequence with special symbols.
|
| 165 |
+
"""
|
| 166 |
+
row_str = ""
|
| 167 |
+
row_cell_values = []
|
| 168 |
+
for cell_value in row:
|
| 169 |
+
if isinstance(cell_value, int):
|
| 170 |
+
row_cell_values.append(str(cell_value))
|
| 171 |
+
else:
|
| 172 |
+
row_cell_values.append(cell_value)
|
| 173 |
+
row_str += " | ".join(row_cell_values)
|
| 174 |
+
return "row " + str(row_index) + " : " + row_str
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class TapexTokenizer(PreTrainedTokenizer):
|
| 178 |
+
r"""
|
| 179 |
+
Construct a TAPEX tokenizer. Based on byte-level Byte-Pair-Encoding (BPE).
|
| 180 |
+
|
| 181 |
+
This tokenizer can be used to flatten one or more table(s) and concatenate them with one or more related sentences
|
| 182 |
+
to be used by TAPEX models. The format that the TAPEX tokenizer creates is the following:
|
| 183 |
+
|
| 184 |
+
sentence col: col1 | col2 | col 3 row 1 : val1 | val2 | val3 row 2 : ...
|
| 185 |
+
|
| 186 |
+
The tokenizer supports a single table + single query, a single table and multiple queries (in which case the table
|
| 187 |
+
will be duplicated for every query), a single query and multiple tables (in which case the query will be duplicated
|
| 188 |
+
for every table), and multiple tables and queries. In other words, you can provide a batch of tables + questions to
|
| 189 |
+
the tokenizer for instance to prepare them for the model.
|
| 190 |
+
|
| 191 |
+
Tokenization itself is based on the BPE algorithm. It is identical to the one used by BART, RoBERTa and GPT-2.
|
| 192 |
+
|
| 193 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 194 |
+
this superclass for more information regarding those methods.
|
| 195 |
+
|
| 196 |
+
Args:
|
| 197 |
+
vocab_file (`str`):
|
| 198 |
+
Path to the vocabulary file.
|
| 199 |
+
merges_file (`str`):
|
| 200 |
+
Path to the merges file.
|
| 201 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 202 |
+
Whether or not to lowercase the input when tokenizing.
|
| 203 |
+
errors (`str`, *optional*, defaults to `"replace"`):
|
| 204 |
+
Paradigm to follow when decoding bytes to UTF-8. See
|
| 205 |
+
[bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
|
| 206 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 207 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 208 |
+
|
| 209 |
+
<Tip>
|
| 210 |
+
|
| 211 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 212 |
+
sequence. The token used is the `cls_token`.
|
| 213 |
+
|
| 214 |
+
</Tip>
|
| 215 |
+
|
| 216 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 217 |
+
The end of sequence token.
|
| 218 |
+
|
| 219 |
+
<Tip>
|
| 220 |
+
|
| 221 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 222 |
+
The token used is the `sep_token`.
|
| 223 |
+
|
| 224 |
+
</Tip>
|
| 225 |
+
|
| 226 |
+
sep_token (`str`, *optional*, defaults to `"</s>"`):
|
| 227 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 228 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 229 |
+
token of a sequence built with special tokens.
|
| 230 |
+
cls_token (`str`, *optional*, defaults to `"<s>"`):
|
| 231 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 232 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 233 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 234 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 235 |
+
token instead.
|
| 236 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 237 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 238 |
+
mask_token (`str`, *optional*, defaults to `"<mask>"`):
|
| 239 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 240 |
+
modeling. This is the token which the model will try to predict.
|
| 241 |
+
add_prefix_space (`bool`, *optional*, defaults to `False`):
|
| 242 |
+
Whether or not to add an initial space to the input. This allows to treat the leading word just as any
|
| 243 |
+
other word. (BART tokenizer detect beginning of words by the preceding space).
|
| 244 |
+
max_cell_length (`int`, *optional*, defaults to 15):
|
| 245 |
+
Maximum number of characters per cell when linearizing a table. If this number is exceeded, truncation
|
| 246 |
+
takes place.
|
| 247 |
+
"""
|
| 248 |
+
|
| 249 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 250 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 251 |
+
|
| 252 |
+
def __init__(
|
| 253 |
+
self,
|
| 254 |
+
vocab_file,
|
| 255 |
+
merges_file,
|
| 256 |
+
do_lower_case=True,
|
| 257 |
+
errors="replace",
|
| 258 |
+
bos_token="<s>",
|
| 259 |
+
eos_token="</s>",
|
| 260 |
+
sep_token="</s>",
|
| 261 |
+
cls_token="<s>",
|
| 262 |
+
unk_token="<unk>",
|
| 263 |
+
pad_token="<pad>",
|
| 264 |
+
mask_token="<mask>",
|
| 265 |
+
add_prefix_space=False,
|
| 266 |
+
max_cell_length=15,
|
| 267 |
+
**kwargs,
|
| 268 |
+
):
|
| 269 |
+
bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
|
| 270 |
+
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
|
| 271 |
+
sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
|
| 272 |
+
cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
|
| 273 |
+
unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
|
| 274 |
+
pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
|
| 275 |
+
|
| 276 |
+
# Mask token behave like a normal word, i.e. include the space before it
|
| 277 |
+
mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
|
| 278 |
+
|
| 279 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
| 280 |
+
self.encoder = json.load(vocab_handle)
|
| 281 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 282 |
+
self.errors = errors # how to handle errors in decoding
|
| 283 |
+
self.byte_encoder = bytes_to_unicode()
|
| 284 |
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
| 285 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
| 286 |
+
bpe_merges = merges_handle.read().split("\n")[1:-1]
|
| 287 |
+
bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
|
| 288 |
+
self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
|
| 289 |
+
self.cache = {}
|
| 290 |
+
self.add_prefix_space = add_prefix_space
|
| 291 |
+
self.do_lower_case = do_lower_case
|
| 292 |
+
|
| 293 |
+
# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
|
| 294 |
+
self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
|
| 295 |
+
|
| 296 |
+
# additional properties
|
| 297 |
+
|
| 298 |
+
super().__init__(
|
| 299 |
+
vocab_file=vocab_file,
|
| 300 |
+
merges_file=merges_file,
|
| 301 |
+
do_lower_case=do_lower_case,
|
| 302 |
+
errors=errors,
|
| 303 |
+
bos_token=bos_token,
|
| 304 |
+
eos_token=eos_token,
|
| 305 |
+
unk_token=unk_token,
|
| 306 |
+
sep_token=sep_token,
|
| 307 |
+
cls_token=cls_token,
|
| 308 |
+
pad_token=pad_token,
|
| 309 |
+
mask_token=mask_token,
|
| 310 |
+
add_prefix_space=add_prefix_space,
|
| 311 |
+
max_cell_length=max_cell_length,
|
| 312 |
+
**kwargs,
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
self.max_cell_length = max_cell_length
|
| 316 |
+
self.table_linearize = IndexedRowTableLinearize()
|
| 317 |
+
|
| 318 |
+
def build_inputs_with_special_tokens(
|
| 319 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 320 |
+
) -> List[int]:
|
| 321 |
+
"""
|
| 322 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 323 |
+
adding special tokens. A TAPEX sequence has the following format:
|
| 324 |
+
- single sequence: `<s> X </s>`
|
| 325 |
+
- pair of sequences: `<s> A </s></s> B </s>`
|
| 326 |
+
|
| 327 |
+
Args:
|
| 328 |
+
token_ids_0 (`List[int]`):
|
| 329 |
+
List of IDs to which the special tokens will be added.
|
| 330 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 331 |
+
Optional second list of IDs for sequence pairs.
|
| 332 |
+
Returns:
|
| 333 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 334 |
+
"""
|
| 335 |
+
if token_ids_1 is None:
|
| 336 |
+
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
| 337 |
+
cls = [self.cls_token_id]
|
| 338 |
+
sep = [self.sep_token_id]
|
| 339 |
+
return cls + token_ids_0 + sep + sep + token_ids_1 + sep
|
| 340 |
+
|
| 341 |
+
def get_special_tokens_mask(
|
| 342 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 343 |
+
) -> List[int]:
|
| 344 |
+
"""
|
| 345 |
+
Args:
|
| 346 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 347 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 348 |
+
token_ids_0 (`List[int]`):
|
| 349 |
+
List of IDs.
|
| 350 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 351 |
+
Optional second list of IDs for sequence pairs.
|
| 352 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 353 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 354 |
+
Returns:
|
| 355 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 356 |
+
"""
|
| 357 |
+
if already_has_special_tokens:
|
| 358 |
+
return super().get_special_tokens_mask(
|
| 359 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
if token_ids_1 is None:
|
| 363 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
| 364 |
+
return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
|
| 365 |
+
|
| 366 |
+
def create_token_type_ids_from_sequences(
|
| 367 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 368 |
+
) -> List[int]:
|
| 369 |
+
"""
|
| 370 |
+
Args:
|
| 371 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. TAPEX does not:
|
| 372 |
+
make use of token type ids, therefore a list of zeros is returned.
|
| 373 |
+
token_ids_0 (`List[int]`):
|
| 374 |
+
List of IDs.
|
| 375 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 376 |
+
Optional second list of IDs for sequence pairs.
|
| 377 |
+
Returns:
|
| 378 |
+
`List[int]`: List of zeros.
|
| 379 |
+
"""
|
| 380 |
+
sep = [self.sep_token_id]
|
| 381 |
+
cls = [self.cls_token_id]
|
| 382 |
+
|
| 383 |
+
if token_ids_1 is None:
|
| 384 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 385 |
+
return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
|
| 386 |
+
|
| 387 |
+
def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
|
| 388 |
+
add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
|
| 389 |
+
if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
|
| 390 |
+
text = " " + text
|
| 391 |
+
return (text, kwargs)
|
| 392 |
+
|
| 393 |
+
@property
|
| 394 |
+
def vocab_size(self):
|
| 395 |
+
return len(self.encoder)
|
| 396 |
+
|
| 397 |
+
def get_vocab(self):
|
| 398 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
| 399 |
+
|
| 400 |
+
def bpe(self, token):
|
| 401 |
+
if token in self.cache:
|
| 402 |
+
return self.cache[token]
|
| 403 |
+
word = tuple(token)
|
| 404 |
+
pairs = get_pairs(word)
|
| 405 |
+
|
| 406 |
+
if not pairs:
|
| 407 |
+
return token
|
| 408 |
+
|
| 409 |
+
while True:
|
| 410 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
| 411 |
+
if bigram not in self.bpe_ranks:
|
| 412 |
+
break
|
| 413 |
+
first, second = bigram
|
| 414 |
+
new_word = []
|
| 415 |
+
i = 0
|
| 416 |
+
while i < len(word):
|
| 417 |
+
try:
|
| 418 |
+
j = word.index(first, i)
|
| 419 |
+
except ValueError:
|
| 420 |
+
new_word.extend(word[i:])
|
| 421 |
+
break
|
| 422 |
+
else:
|
| 423 |
+
new_word.extend(word[i:j])
|
| 424 |
+
i = j
|
| 425 |
+
|
| 426 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
| 427 |
+
new_word.append(first + second)
|
| 428 |
+
i += 2
|
| 429 |
+
else:
|
| 430 |
+
new_word.append(word[i])
|
| 431 |
+
i += 1
|
| 432 |
+
new_word = tuple(new_word)
|
| 433 |
+
word = new_word
|
| 434 |
+
if len(word) == 1:
|
| 435 |
+
break
|
| 436 |
+
else:
|
| 437 |
+
pairs = get_pairs(word)
|
| 438 |
+
word = " ".join(word)
|
| 439 |
+
self.cache[token] = word
|
| 440 |
+
return word
|
| 441 |
+
|
| 442 |
+
def _tokenize(self, text):
|
| 443 |
+
"""Tokenize a string."""
|
| 444 |
+
bpe_tokens = []
|
| 445 |
+
for token in re.findall(self.pat, text):
|
| 446 |
+
token = "".join(
|
| 447 |
+
self.byte_encoder[b] for b in token.encode("utf-8")
|
| 448 |
+
) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
|
| 449 |
+
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
|
| 450 |
+
return bpe_tokens
|
| 451 |
+
|
| 452 |
+
def _convert_token_to_id(self, token):
|
| 453 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 454 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
| 455 |
+
|
| 456 |
+
def _convert_id_to_token(self, index):
|
| 457 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 458 |
+
return self.decoder.get(index)
|
| 459 |
+
|
| 460 |
+
def convert_tokens_to_string(self, tokens):
|
| 461 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 462 |
+
text = "".join(tokens)
|
| 463 |
+
text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
|
| 464 |
+
return text
|
| 465 |
+
|
| 466 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 467 |
+
if not os.path.isdir(save_directory):
|
| 468 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 469 |
+
return
|
| 470 |
+
vocab_file = os.path.join(
|
| 471 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 472 |
+
)
|
| 473 |
+
merge_file = os.path.join(
|
| 474 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
| 478 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
| 479 |
+
|
| 480 |
+
index = 0
|
| 481 |
+
with open(merge_file, "w", encoding="utf-8") as writer:
|
| 482 |
+
writer.write("#version: 0.2\n")
|
| 483 |
+
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
|
| 484 |
+
if index != token_index:
|
| 485 |
+
logger.warning(
|
| 486 |
+
f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
|
| 487 |
+
" Please check that the tokenizer is not corrupted!"
|
| 488 |
+
)
|
| 489 |
+
index = token_index
|
| 490 |
+
writer.write(" ".join(bpe_tokens) + "\n")
|
| 491 |
+
index += 1
|
| 492 |
+
|
| 493 |
+
return vocab_file, merge_file
|
| 494 |
+
|
| 495 |
+
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
|
| 496 |
+
def __call__(
|
| 497 |
+
self,
|
| 498 |
+
table: Union["pd.DataFrame", List["pd.DataFrame"]] = None,
|
| 499 |
+
query: Optional[Union[TextInput, List[TextInput]]] = None,
|
| 500 |
+
answer: Union[str, List[str]] = None,
|
| 501 |
+
add_special_tokens: bool = True,
|
| 502 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 503 |
+
truncation: Union[bool, str, TruncationStrategy] = None,
|
| 504 |
+
max_length: Optional[int] = None,
|
| 505 |
+
stride: int = 0,
|
| 506 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 507 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 508 |
+
return_token_type_ids: Optional[bool] = None,
|
| 509 |
+
return_attention_mask: Optional[bool] = None,
|
| 510 |
+
return_overflowing_tokens: bool = False,
|
| 511 |
+
return_special_tokens_mask: bool = False,
|
| 512 |
+
return_offsets_mapping: bool = False,
|
| 513 |
+
return_length: bool = False,
|
| 514 |
+
verbose: bool = True,
|
| 515 |
+
**kwargs,
|
| 516 |
+
) -> BatchEncoding:
|
| 517 |
+
"""
|
| 518 |
+
Main method to tokenize and prepare for the model one or several table-sequence pair(s).
|
| 519 |
+
|
| 520 |
+
Args:
|
| 521 |
+
table (`pd.DataFrame`, `List[pd.DataFrame]`):
|
| 522 |
+
Table(s) containing tabular data.
|
| 523 |
+
query (`str` or `List[str]`, *optional*):
|
| 524 |
+
Sentence or batch of sentences related to one or more table(s) to be encoded. Note that the number of
|
| 525 |
+
sentences must match the number of tables.
|
| 526 |
+
answer (`str` or `List[str]`, *optional*):
|
| 527 |
+
Optionally, the corresponding answer to the questions as supervision.
|
| 528 |
+
"""
|
| 529 |
+
|
| 530 |
+
if table is not None:
|
| 531 |
+
return self.source_call_func(
|
| 532 |
+
table=table,
|
| 533 |
+
query=query,
|
| 534 |
+
answer=answer,
|
| 535 |
+
add_special_tokens=add_special_tokens,
|
| 536 |
+
padding=padding,
|
| 537 |
+
truncation=truncation,
|
| 538 |
+
max_length=max_length,
|
| 539 |
+
stride=stride,
|
| 540 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 541 |
+
return_tensors=return_tensors,
|
| 542 |
+
return_token_type_ids=return_token_type_ids,
|
| 543 |
+
return_attention_mask=return_attention_mask,
|
| 544 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 545 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 546 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 547 |
+
return_length=return_length,
|
| 548 |
+
verbose=verbose,
|
| 549 |
+
**kwargs,
|
| 550 |
+
)
|
| 551 |
+
elif answer is not None:
|
| 552 |
+
return self.target_call_func(
|
| 553 |
+
answer=answer,
|
| 554 |
+
add_special_tokens=add_special_tokens,
|
| 555 |
+
padding=padding,
|
| 556 |
+
truncation=truncation,
|
| 557 |
+
max_length=max_length,
|
| 558 |
+
stride=stride,
|
| 559 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 560 |
+
return_tensors=return_tensors,
|
| 561 |
+
return_token_type_ids=return_token_type_ids,
|
| 562 |
+
return_attention_mask=return_attention_mask,
|
| 563 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 564 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 565 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 566 |
+
return_length=return_length,
|
| 567 |
+
verbose=verbose,
|
| 568 |
+
**kwargs,
|
| 569 |
+
)
|
| 570 |
+
else:
|
| 571 |
+
raise ValueError("You need to provide either a `table` or an `answer`.")
|
| 572 |
+
|
| 573 |
+
def source_call_func(
|
| 574 |
+
self,
|
| 575 |
+
table: Union["pd.DataFrame", List["pd.DataFrame"]],
|
| 576 |
+
query: Optional[Union[TextInput, List[TextInput]]] = None,
|
| 577 |
+
answer: Union[str, List[str]] = None,
|
| 578 |
+
add_special_tokens: bool = True,
|
| 579 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 580 |
+
truncation: Union[bool, str, TruncationStrategy] = None,
|
| 581 |
+
max_length: Optional[int] = None,
|
| 582 |
+
stride: int = 0,
|
| 583 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 584 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 585 |
+
return_token_type_ids: Optional[bool] = None,
|
| 586 |
+
return_attention_mask: Optional[bool] = None,
|
| 587 |
+
return_overflowing_tokens: bool = False,
|
| 588 |
+
return_special_tokens_mask: bool = False,
|
| 589 |
+
return_offsets_mapping: bool = False,
|
| 590 |
+
return_length: bool = False,
|
| 591 |
+
verbose: bool = True,
|
| 592 |
+
**kwargs,
|
| 593 |
+
) -> BatchEncoding:
|
| 594 |
+
# Input type checking for clearer error
|
| 595 |
+
valid_table = False
|
| 596 |
+
valid_query = False
|
| 597 |
+
|
| 598 |
+
# Check that table have a valid type
|
| 599 |
+
if isinstance(table, pd.DataFrame):
|
| 600 |
+
valid_table = True
|
| 601 |
+
elif isinstance(table, (list, tuple)) and isinstance(table[0], pd.DataFrame):
|
| 602 |
+
valid_table = True
|
| 603 |
+
|
| 604 |
+
# Check that query have a valid type
|
| 605 |
+
if query is None or isinstance(query, str):
|
| 606 |
+
valid_query = True
|
| 607 |
+
elif isinstance(query, (list, tuple)):
|
| 608 |
+
if len(query) == 0 or isinstance(query[0], str):
|
| 609 |
+
valid_query = True
|
| 610 |
+
|
| 611 |
+
if not valid_table:
|
| 612 |
+
raise ValueError(
|
| 613 |
+
"table input must of type `pd.DataFrame` (single example), `List[pd.DataFrame]` (batch of examples). "
|
| 614 |
+
)
|
| 615 |
+
if not valid_query:
|
| 616 |
+
raise ValueError("query input must of type `str` (single example), `List[str]` (batch of examples). ")
|
| 617 |
+
is_batched = isinstance(table, (list, tuple)) or isinstance(query, (list, tuple))
|
| 618 |
+
|
| 619 |
+
if is_batched:
|
| 620 |
+
return self.batch_encode_plus(
|
| 621 |
+
table=table,
|
| 622 |
+
query=query,
|
| 623 |
+
answer=answer,
|
| 624 |
+
add_special_tokens=add_special_tokens,
|
| 625 |
+
padding=padding,
|
| 626 |
+
truncation=truncation,
|
| 627 |
+
max_length=max_length,
|
| 628 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 629 |
+
return_tensors=return_tensors,
|
| 630 |
+
return_token_type_ids=return_token_type_ids,
|
| 631 |
+
return_attention_mask=return_attention_mask,
|
| 632 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 633 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 634 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 635 |
+
return_length=return_length,
|
| 636 |
+
verbose=verbose,
|
| 637 |
+
**kwargs,
|
| 638 |
+
)
|
| 639 |
+
else:
|
| 640 |
+
return self.encode_plus(
|
| 641 |
+
table=table,
|
| 642 |
+
query=query,
|
| 643 |
+
answer=answer,
|
| 644 |
+
add_special_tokens=add_special_tokens,
|
| 645 |
+
padding=padding,
|
| 646 |
+
truncation=truncation,
|
| 647 |
+
max_length=max_length,
|
| 648 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 649 |
+
return_tensors=return_tensors,
|
| 650 |
+
return_token_type_ids=return_token_type_ids,
|
| 651 |
+
return_attention_mask=return_attention_mask,
|
| 652 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 653 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 654 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 655 |
+
return_length=return_length,
|
| 656 |
+
verbose=verbose,
|
| 657 |
+
**kwargs,
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
|
| 661 |
+
def batch_encode_plus(
|
| 662 |
+
self,
|
| 663 |
+
table: Union["pd.DataFrame", List["pd.DataFrame"]],
|
| 664 |
+
query: Optional[List[TextInput]] = None,
|
| 665 |
+
answer: List[str] = None,
|
| 666 |
+
add_special_tokens: bool = True,
|
| 667 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 668 |
+
truncation: Union[bool, str] = None,
|
| 669 |
+
max_length: Optional[int] = None,
|
| 670 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 671 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 672 |
+
return_token_type_ids: Optional[bool] = None,
|
| 673 |
+
return_attention_mask: Optional[bool] = None,
|
| 674 |
+
return_overflowing_tokens: bool = False,
|
| 675 |
+
return_special_tokens_mask: bool = False,
|
| 676 |
+
return_offsets_mapping: bool = False,
|
| 677 |
+
return_length: bool = False,
|
| 678 |
+
verbose: bool = True,
|
| 679 |
+
**kwargs,
|
| 680 |
+
) -> BatchEncoding:
|
| 681 |
+
"""
|
| 682 |
+
<Tip warning={true}>
|
| 683 |
+
|
| 684 |
+
This method is deprecated, `__call__` should be used instead.
|
| 685 |
+
|
| 686 |
+
</Tip>
|
| 687 |
+
"""
|
| 688 |
+
# Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
|
| 689 |
+
padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
|
| 690 |
+
padding=padding,
|
| 691 |
+
truncation=truncation,
|
| 692 |
+
max_length=max_length,
|
| 693 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 694 |
+
verbose=verbose,
|
| 695 |
+
**kwargs,
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
return self._batch_encode_plus(
|
| 699 |
+
table=table,
|
| 700 |
+
query=query,
|
| 701 |
+
answer=answer,
|
| 702 |
+
add_special_tokens=add_special_tokens,
|
| 703 |
+
padding_strategy=padding_strategy,
|
| 704 |
+
truncation_strategy=truncation_strategy,
|
| 705 |
+
max_length=max_length,
|
| 706 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 707 |
+
return_tensors=return_tensors,
|
| 708 |
+
return_token_type_ids=return_token_type_ids,
|
| 709 |
+
return_attention_mask=return_attention_mask,
|
| 710 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 711 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 712 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 713 |
+
return_length=return_length,
|
| 714 |
+
verbose=verbose,
|
| 715 |
+
**kwargs,
|
| 716 |
+
)
|
| 717 |
+
|
| 718 |
+
def _batch_encode_plus(
|
| 719 |
+
self,
|
| 720 |
+
table: Union["pd.DataFrame", List["pd.DataFrame"]],
|
| 721 |
+
query: Optional[List[TextInput]] = None,
|
| 722 |
+
answer: Optional[List[str]] = None,
|
| 723 |
+
add_special_tokens: bool = True,
|
| 724 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
| 725 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
| 726 |
+
max_length: Optional[int] = None,
|
| 727 |
+
stride: int = 0,
|
| 728 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 729 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 730 |
+
return_token_type_ids: Optional[bool] = None,
|
| 731 |
+
return_attention_mask: Optional[bool] = None,
|
| 732 |
+
return_overflowing_tokens: bool = False,
|
| 733 |
+
return_special_tokens_mask: bool = False,
|
| 734 |
+
return_offsets_mapping: bool = False,
|
| 735 |
+
return_length: bool = False,
|
| 736 |
+
verbose: bool = True,
|
| 737 |
+
**kwargs,
|
| 738 |
+
) -> BatchEncoding:
|
| 739 |
+
if return_offsets_mapping:
|
| 740 |
+
raise NotImplementedError(
|
| 741 |
+
"return_offset_mapping is not available when using Python tokenizers. "
|
| 742 |
+
"To use this feature, change your tokenizer to one deriving from "
|
| 743 |
+
"transformers.PreTrainedTokenizerFast."
|
| 744 |
+
)
|
| 745 |
+
|
| 746 |
+
if isinstance(table, pd.DataFrame) and isinstance(query, (list, tuple)):
|
| 747 |
+
# single table, many queries case
|
| 748 |
+
# duplicate table for every query
|
| 749 |
+
table = [table] * len(query)
|
| 750 |
+
if isinstance(table, (list, tuple)) and isinstance(query, str):
|
| 751 |
+
# many tables, single query case
|
| 752 |
+
# duplicate query for every table
|
| 753 |
+
query = [query] * len(table)
|
| 754 |
+
|
| 755 |
+
batch_outputs = self._batch_prepare_for_model(
|
| 756 |
+
table=table,
|
| 757 |
+
query=query,
|
| 758 |
+
answer=answer,
|
| 759 |
+
add_special_tokens=add_special_tokens,
|
| 760 |
+
padding_strategy=padding_strategy,
|
| 761 |
+
truncation_strategy=truncation_strategy,
|
| 762 |
+
max_length=max_length,
|
| 763 |
+
stride=stride,
|
| 764 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 765 |
+
return_attention_mask=return_attention_mask,
|
| 766 |
+
return_token_type_ids=return_token_type_ids,
|
| 767 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 768 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 769 |
+
return_length=return_length,
|
| 770 |
+
return_tensors=return_tensors,
|
| 771 |
+
verbose=verbose,
|
| 772 |
+
)
|
| 773 |
+
|
| 774 |
+
return BatchEncoding(batch_outputs)
|
| 775 |
+
|
| 776 |
+
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
|
| 777 |
+
def _batch_prepare_for_model(
|
| 778 |
+
self,
|
| 779 |
+
table: Union["pd.DataFrame", List["pd.DataFrame"]],
|
| 780 |
+
query: Optional[Union[TextInput, List[TextInput]]] = None,
|
| 781 |
+
answer: Optional[Union[str, List[str]]] = None,
|
| 782 |
+
add_special_tokens: bool = True,
|
| 783 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
| 784 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
| 785 |
+
max_length: Optional[int] = None,
|
| 786 |
+
stride: int = 0,
|
| 787 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 788 |
+
return_tensors: Optional[str] = None,
|
| 789 |
+
return_token_type_ids: Optional[bool] = None,
|
| 790 |
+
return_attention_mask: Optional[bool] = None,
|
| 791 |
+
return_overflowing_tokens: bool = False,
|
| 792 |
+
return_special_tokens_mask: bool = False,
|
| 793 |
+
return_length: bool = False,
|
| 794 |
+
verbose: bool = True,
|
| 795 |
+
) -> BatchEncoding:
|
| 796 |
+
"""
|
| 797 |
+
This method adds special tokens, truncates sequences if overflowing while taking into account the special
|
| 798 |
+
tokens and manages a moving window (with user defined stride) for overflowing tokens.
|
| 799 |
+
"""
|
| 800 |
+
batch_outputs = {}
|
| 801 |
+
if answer is None:
|
| 802 |
+
answer = [None] * len(table)
|
| 803 |
+
for _table, _query, _answer in zip(table, query, answer):
|
| 804 |
+
text = self.prepare_table_query(
|
| 805 |
+
_table, _query, _answer, truncation_strategy=truncation_strategy, max_length=max_length
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
if self.do_lower_case:
|
| 809 |
+
text = text.lower()
|
| 810 |
+
|
| 811 |
+
tokens = self.tokenize(text)
|
| 812 |
+
outputs = self.prepare_for_model(
|
| 813 |
+
ids=self.convert_tokens_to_ids(tokens),
|
| 814 |
+
add_special_tokens=add_special_tokens,
|
| 815 |
+
padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterwards
|
| 816 |
+
truncation=truncation_strategy.value,
|
| 817 |
+
max_length=max_length,
|
| 818 |
+
stride=stride,
|
| 819 |
+
pad_to_multiple_of=None, # we pad in batch afterwards
|
| 820 |
+
return_attention_mask=False, # we pad in batch afterwards
|
| 821 |
+
return_token_type_ids=return_token_type_ids,
|
| 822 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 823 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 824 |
+
return_length=return_length,
|
| 825 |
+
return_tensors=None, # We convert the whole batch to tensors at the end
|
| 826 |
+
prepend_batch_axis=False,
|
| 827 |
+
verbose=verbose,
|
| 828 |
+
)
|
| 829 |
+
|
| 830 |
+
for key, value in outputs.items():
|
| 831 |
+
if key not in batch_outputs:
|
| 832 |
+
batch_outputs[key] = []
|
| 833 |
+
batch_outputs[key].append(value)
|
| 834 |
+
|
| 835 |
+
batch_outputs = self.pad(
|
| 836 |
+
batch_outputs,
|
| 837 |
+
padding=padding_strategy.value,
|
| 838 |
+
max_length=max_length,
|
| 839 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 840 |
+
return_attention_mask=return_attention_mask,
|
| 841 |
+
)
|
| 842 |
+
|
| 843 |
+
batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
|
| 844 |
+
|
| 845 |
+
return batch_outputs
|
| 846 |
+
|
| 847 |
+
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING)
|
| 848 |
+
def encode(
|
| 849 |
+
self,
|
| 850 |
+
table: "pd.DataFrame",
|
| 851 |
+
query: Optional[TextInput] = None,
|
| 852 |
+
answer: Optional[str] = None,
|
| 853 |
+
add_special_tokens: bool = True,
|
| 854 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 855 |
+
truncation: Union[bool, str, TruncationStrategy, TapexTruncationStrategy] = None,
|
| 856 |
+
max_length: Optional[int] = None,
|
| 857 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 858 |
+
**kwargs,
|
| 859 |
+
) -> List[int]:
|
| 860 |
+
"""
|
| 861 |
+
Prepare a table, a string and possible answer for the model. This method does not return token type IDs,
|
| 862 |
+
attention masks, etc. which are necessary for the model to work correctly. Use this method if you want to build
|
| 863 |
+
your processing on your own, otherwise refer to `__call__`.
|
| 864 |
+
"""
|
| 865 |
+
encoded_inputs = self.encode_plus(
|
| 866 |
+
table,
|
| 867 |
+
query=query,
|
| 868 |
+
answer=answer,
|
| 869 |
+
add_special_tokens=add_special_tokens,
|
| 870 |
+
padding=padding,
|
| 871 |
+
truncation=truncation,
|
| 872 |
+
max_length=max_length,
|
| 873 |
+
return_tensors=return_tensors,
|
| 874 |
+
**kwargs,
|
| 875 |
+
)
|
| 876 |
+
|
| 877 |
+
return encoded_inputs["input_ids"]
|
| 878 |
+
|
| 879 |
+
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
|
| 880 |
+
def encode_plus(
|
| 881 |
+
self,
|
| 882 |
+
table: "pd.DataFrame",
|
| 883 |
+
query: Optional[TextInput] = None,
|
| 884 |
+
answer: Optional[str] = None,
|
| 885 |
+
add_special_tokens: bool = True,
|
| 886 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 887 |
+
truncation: Union[bool, str] = None,
|
| 888 |
+
max_length: Optional[int] = None,
|
| 889 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 890 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 891 |
+
return_token_type_ids: Optional[bool] = None,
|
| 892 |
+
return_attention_mask: Optional[bool] = None,
|
| 893 |
+
return_special_tokens_mask: bool = False,
|
| 894 |
+
return_offsets_mapping: bool = False,
|
| 895 |
+
return_length: bool = False,
|
| 896 |
+
verbose: bool = True,
|
| 897 |
+
**kwargs,
|
| 898 |
+
) -> BatchEncoding:
|
| 899 |
+
# Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
|
| 900 |
+
padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
|
| 901 |
+
padding=padding,
|
| 902 |
+
truncation=truncation,
|
| 903 |
+
max_length=max_length,
|
| 904 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 905 |
+
verbose=verbose,
|
| 906 |
+
**kwargs,
|
| 907 |
+
)
|
| 908 |
+
|
| 909 |
+
return self._encode_plus(
|
| 910 |
+
table=table,
|
| 911 |
+
query=query,
|
| 912 |
+
answer=answer,
|
| 913 |
+
add_special_tokens=add_special_tokens,
|
| 914 |
+
padding_strategy=padding_strategy,
|
| 915 |
+
truncation_strategy=truncation_strategy,
|
| 916 |
+
max_length=max_length,
|
| 917 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 918 |
+
return_tensors=return_tensors,
|
| 919 |
+
return_token_type_ids=return_token_type_ids,
|
| 920 |
+
return_attention_mask=return_attention_mask,
|
| 921 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 922 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 923 |
+
return_length=return_length,
|
| 924 |
+
verbose=verbose,
|
| 925 |
+
**kwargs,
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
def _encode_plus(
|
| 929 |
+
self,
|
| 930 |
+
table: "pd.DataFrame",
|
| 931 |
+
query: Optional[TextInput] = None,
|
| 932 |
+
answer: Optional[str] = None,
|
| 933 |
+
add_special_tokens: bool = True,
|
| 934 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
| 935 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
| 936 |
+
max_length: Optional[int] = None,
|
| 937 |
+
stride: int = 0,
|
| 938 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 939 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 940 |
+
return_token_type_ids: Optional[bool] = None,
|
| 941 |
+
return_attention_mask: Optional[bool] = None,
|
| 942 |
+
return_overflowing_tokens: bool = False,
|
| 943 |
+
return_special_tokens_mask: bool = False,
|
| 944 |
+
return_offsets_mapping: bool = False,
|
| 945 |
+
return_length: bool = False,
|
| 946 |
+
verbose: bool = True,
|
| 947 |
+
**kwargs,
|
| 948 |
+
) -> BatchEncoding:
|
| 949 |
+
if return_offsets_mapping:
|
| 950 |
+
raise NotImplementedError(
|
| 951 |
+
"return_offset_mapping is not available when using Python tokenizers. "
|
| 952 |
+
"To use this feature, change your tokenizer to one deriving from "
|
| 953 |
+
"transformers.PreTrainedTokenizerFast. "
|
| 954 |
+
"More information on available tokenizers at "
|
| 955 |
+
"https://github.com/huggingface/transformers/pull/2674"
|
| 956 |
+
)
|
| 957 |
+
|
| 958 |
+
text = self.prepare_table_query(
|
| 959 |
+
table, query, answer, truncation_strategy=truncation_strategy, max_length=max_length
|
| 960 |
+
)
|
| 961 |
+
|
| 962 |
+
# if necessary, perform lower case
|
| 963 |
+
if self.do_lower_case:
|
| 964 |
+
text = text.lower()
|
| 965 |
+
|
| 966 |
+
tokens = self.tokenize(text)
|
| 967 |
+
|
| 968 |
+
return self.prepare_for_model(
|
| 969 |
+
ids=self.convert_tokens_to_ids(tokens),
|
| 970 |
+
add_special_tokens=add_special_tokens,
|
| 971 |
+
padding=padding_strategy.value,
|
| 972 |
+
truncation=truncation_strategy.value,
|
| 973 |
+
max_length=max_length,
|
| 974 |
+
stride=stride,
|
| 975 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 976 |
+
return_tensors=return_tensors,
|
| 977 |
+
prepend_batch_axis=True,
|
| 978 |
+
return_attention_mask=return_attention_mask,
|
| 979 |
+
return_token_type_ids=return_token_type_ids,
|
| 980 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 981 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 982 |
+
return_length=return_length,
|
| 983 |
+
verbose=verbose,
|
| 984 |
+
)
|
| 985 |
+
|
| 986 |
+
def target_call_func(
|
| 987 |
+
self,
|
| 988 |
+
answer: Union[str, List[str]],
|
| 989 |
+
add_special_tokens: bool = True,
|
| 990 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 991 |
+
truncation: Union[bool, str, TruncationStrategy] = None,
|
| 992 |
+
max_length: Optional[int] = None,
|
| 993 |
+
stride: int = 0,
|
| 994 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 995 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 996 |
+
return_token_type_ids: Optional[bool] = None,
|
| 997 |
+
return_attention_mask: Optional[bool] = None,
|
| 998 |
+
return_overflowing_tokens: bool = False,
|
| 999 |
+
return_special_tokens_mask: bool = False,
|
| 1000 |
+
return_offsets_mapping: bool = False,
|
| 1001 |
+
return_length: bool = False,
|
| 1002 |
+
verbose: bool = True,
|
| 1003 |
+
**kwargs,
|
| 1004 |
+
) -> BatchEncoding:
|
| 1005 |
+
"""
|
| 1006 |
+
The method tokenizes and prepares the answer label for the model.
|
| 1007 |
+
|
| 1008 |
+
Args:
|
| 1009 |
+
answer (`str` or `List[str]`):
|
| 1010 |
+
Corresponding answer supervision to the queries for training the model.
|
| 1011 |
+
"""
|
| 1012 |
+
is_batched = isinstance(answer, (list, tuple))
|
| 1013 |
+
|
| 1014 |
+
if is_batched:
|
| 1015 |
+
return self.target_batch_encode_plus(
|
| 1016 |
+
answer=answer,
|
| 1017 |
+
add_special_tokens=add_special_tokens,
|
| 1018 |
+
padding=padding,
|
| 1019 |
+
truncation=truncation,
|
| 1020 |
+
max_length=max_length,
|
| 1021 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 1022 |
+
return_tensors=return_tensors,
|
| 1023 |
+
return_token_type_ids=return_token_type_ids,
|
| 1024 |
+
return_attention_mask=return_attention_mask,
|
| 1025 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 1026 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 1027 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 1028 |
+
return_length=return_length,
|
| 1029 |
+
verbose=verbose,
|
| 1030 |
+
**kwargs,
|
| 1031 |
+
)
|
| 1032 |
+
else:
|
| 1033 |
+
return self.target_encode_plus(
|
| 1034 |
+
answer=answer,
|
| 1035 |
+
add_special_tokens=add_special_tokens,
|
| 1036 |
+
padding=padding,
|
| 1037 |
+
truncation=truncation,
|
| 1038 |
+
max_length=max_length,
|
| 1039 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 1040 |
+
return_tensors=return_tensors,
|
| 1041 |
+
return_token_type_ids=return_token_type_ids,
|
| 1042 |
+
return_attention_mask=return_attention_mask,
|
| 1043 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 1044 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 1045 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 1046 |
+
return_length=return_length,
|
| 1047 |
+
verbose=verbose,
|
| 1048 |
+
**kwargs,
|
| 1049 |
+
)
|
| 1050 |
+
|
| 1051 |
+
def target_batch_encode_plus(
|
| 1052 |
+
self,
|
| 1053 |
+
answer: List[str],
|
| 1054 |
+
add_special_tokens: bool = True,
|
| 1055 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 1056 |
+
truncation: Union[bool, str] = None,
|
| 1057 |
+
max_length: Optional[int] = None,
|
| 1058 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 1059 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 1060 |
+
return_token_type_ids: Optional[bool] = None,
|
| 1061 |
+
return_attention_mask: Optional[bool] = None,
|
| 1062 |
+
return_overflowing_tokens: bool = False,
|
| 1063 |
+
return_special_tokens_mask: bool = False,
|
| 1064 |
+
return_offsets_mapping: bool = False,
|
| 1065 |
+
return_length: bool = False,
|
| 1066 |
+
verbose: bool = True,
|
| 1067 |
+
**kwargs,
|
| 1068 |
+
) -> BatchEncoding:
|
| 1069 |
+
"""
|
| 1070 |
+
Prepare answer strings for the model.
|
| 1071 |
+
|
| 1072 |
+
Args:
|
| 1073 |
+
answer `List[str]`:
|
| 1074 |
+
Corresponding answer supervision to the queries for training the model.
|
| 1075 |
+
"""
|
| 1076 |
+
# Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
|
| 1077 |
+
padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
|
| 1078 |
+
padding=padding,
|
| 1079 |
+
truncation=truncation,
|
| 1080 |
+
max_length=max_length,
|
| 1081 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 1082 |
+
verbose=verbose,
|
| 1083 |
+
**kwargs,
|
| 1084 |
+
)
|
| 1085 |
+
|
| 1086 |
+
return self._target_batch_encode_plus(
|
| 1087 |
+
answer=answer,
|
| 1088 |
+
add_special_tokens=add_special_tokens,
|
| 1089 |
+
padding_strategy=padding_strategy,
|
| 1090 |
+
truncation_strategy=truncation_strategy,
|
| 1091 |
+
max_length=max_length,
|
| 1092 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 1093 |
+
return_tensors=return_tensors,
|
| 1094 |
+
return_token_type_ids=return_token_type_ids,
|
| 1095 |
+
return_attention_mask=return_attention_mask,
|
| 1096 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 1097 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 1098 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 1099 |
+
return_length=return_length,
|
| 1100 |
+
verbose=verbose,
|
| 1101 |
+
**kwargs,
|
| 1102 |
+
)
|
| 1103 |
+
|
| 1104 |
+
def _target_batch_encode_plus(
|
| 1105 |
+
self,
|
| 1106 |
+
answer: List[str],
|
| 1107 |
+
add_special_tokens: bool = True,
|
| 1108 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
| 1109 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
| 1110 |
+
max_length: Optional[int] = None,
|
| 1111 |
+
stride: int = 0,
|
| 1112 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 1113 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 1114 |
+
return_token_type_ids: Optional[bool] = None,
|
| 1115 |
+
return_attention_mask: Optional[bool] = None,
|
| 1116 |
+
return_overflowing_tokens: bool = False,
|
| 1117 |
+
return_special_tokens_mask: bool = False,
|
| 1118 |
+
return_offsets_mapping: bool = False,
|
| 1119 |
+
return_length: bool = False,
|
| 1120 |
+
verbose: bool = True,
|
| 1121 |
+
**kwargs,
|
| 1122 |
+
) -> BatchEncoding:
|
| 1123 |
+
batch_outputs = {}
|
| 1124 |
+
for text in answer:
|
| 1125 |
+
if self.do_lower_case:
|
| 1126 |
+
text = text.lower()
|
| 1127 |
+
|
| 1128 |
+
tokens = self.tokenize(text)
|
| 1129 |
+
outputs = self.prepare_for_model(
|
| 1130 |
+
ids=self.convert_tokens_to_ids(tokens),
|
| 1131 |
+
add_special_tokens=add_special_tokens,
|
| 1132 |
+
padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterwards
|
| 1133 |
+
truncation=truncation_strategy.value,
|
| 1134 |
+
max_length=max_length,
|
| 1135 |
+
stride=stride,
|
| 1136 |
+
pad_to_multiple_of=None, # we pad in batch afterwards
|
| 1137 |
+
return_attention_mask=False, # we pad in batch afterwards
|
| 1138 |
+
return_token_type_ids=return_token_type_ids,
|
| 1139 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 1140 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 1141 |
+
return_length=return_length,
|
| 1142 |
+
return_tensors=None, # We convert the whole batch to tensors at the end
|
| 1143 |
+
prepend_batch_axis=False,
|
| 1144 |
+
verbose=verbose,
|
| 1145 |
+
)
|
| 1146 |
+
|
| 1147 |
+
for key, value in outputs.items():
|
| 1148 |
+
if key not in batch_outputs:
|
| 1149 |
+
batch_outputs[key] = []
|
| 1150 |
+
batch_outputs[key].append(value)
|
| 1151 |
+
|
| 1152 |
+
batch_outputs = self.pad(
|
| 1153 |
+
batch_outputs,
|
| 1154 |
+
padding=padding_strategy.value,
|
| 1155 |
+
max_length=max_length,
|
| 1156 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 1157 |
+
return_attention_mask=return_attention_mask,
|
| 1158 |
+
)
|
| 1159 |
+
|
| 1160 |
+
batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
|
| 1161 |
+
|
| 1162 |
+
return BatchEncoding(batch_outputs)
|
| 1163 |
+
|
| 1164 |
+
def target_encode(
|
| 1165 |
+
self,
|
| 1166 |
+
answer: str,
|
| 1167 |
+
add_special_tokens: bool = True,
|
| 1168 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 1169 |
+
truncation: Union[bool, str, TruncationStrategy, TapexTruncationStrategy] = None,
|
| 1170 |
+
max_length: Optional[int] = None,
|
| 1171 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 1172 |
+
**kwargs,
|
| 1173 |
+
) -> List[int]:
|
| 1174 |
+
"""
|
| 1175 |
+
Prepare the answer string for the model. This method does not return token type IDs, attention masks, etc.
|
| 1176 |
+
which are necessary for the model to work correctly. Use this method if you want to build your processing on
|
| 1177 |
+
your own, otherwise refer to `__call__`.
|
| 1178 |
+
|
| 1179 |
+
Args:
|
| 1180 |
+
answer `str`:
|
| 1181 |
+
Corresponding answer supervision to the queries for training the model
|
| 1182 |
+
"""
|
| 1183 |
+
encoded_outputs = self.target_encode_plus(
|
| 1184 |
+
answer=answer,
|
| 1185 |
+
add_special_tokens=add_special_tokens,
|
| 1186 |
+
padding=padding,
|
| 1187 |
+
truncation=truncation,
|
| 1188 |
+
max_length=max_length,
|
| 1189 |
+
return_tensors=return_tensors,
|
| 1190 |
+
**kwargs,
|
| 1191 |
+
)
|
| 1192 |
+
|
| 1193 |
+
return encoded_outputs["input_ids"]
|
| 1194 |
+
|
| 1195 |
+
def target_encode_plus(
|
| 1196 |
+
self,
|
| 1197 |
+
answer: str,
|
| 1198 |
+
add_special_tokens: bool = True,
|
| 1199 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 1200 |
+
truncation: Union[bool, str] = None,
|
| 1201 |
+
max_length: Optional[int] = None,
|
| 1202 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 1203 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 1204 |
+
return_token_type_ids: Optional[bool] = None,
|
| 1205 |
+
return_attention_mask: Optional[bool] = None,
|
| 1206 |
+
return_special_tokens_mask: bool = False,
|
| 1207 |
+
return_offsets_mapping: bool = False,
|
| 1208 |
+
return_length: bool = False,
|
| 1209 |
+
verbose: bool = True,
|
| 1210 |
+
**kwargs,
|
| 1211 |
+
) -> BatchEncoding:
|
| 1212 |
+
"""
|
| 1213 |
+
Prepare a answer string for the model.
|
| 1214 |
+
|
| 1215 |
+
Args:
|
| 1216 |
+
answer `str`:
|
| 1217 |
+
Corresponding answer supervision to the queries for training the model.
|
| 1218 |
+
"""
|
| 1219 |
+
# Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
|
| 1220 |
+
padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
|
| 1221 |
+
padding=padding,
|
| 1222 |
+
truncation=truncation,
|
| 1223 |
+
max_length=max_length,
|
| 1224 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 1225 |
+
verbose=verbose,
|
| 1226 |
+
**kwargs,
|
| 1227 |
+
)
|
| 1228 |
+
|
| 1229 |
+
return self._target_encode_plus(
|
| 1230 |
+
answer=answer,
|
| 1231 |
+
add_special_tokens=add_special_tokens,
|
| 1232 |
+
padding_strategy=padding_strategy,
|
| 1233 |
+
truncation_strategy=truncation_strategy,
|
| 1234 |
+
max_length=max_length,
|
| 1235 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 1236 |
+
return_tensors=return_tensors,
|
| 1237 |
+
return_token_type_ids=return_token_type_ids,
|
| 1238 |
+
return_attention_mask=return_attention_mask,
|
| 1239 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 1240 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 1241 |
+
return_length=return_length,
|
| 1242 |
+
verbose=verbose,
|
| 1243 |
+
**kwargs,
|
| 1244 |
+
)
|
| 1245 |
+
|
| 1246 |
+
def _target_encode_plus(
|
| 1247 |
+
self,
|
| 1248 |
+
answer: str,
|
| 1249 |
+
add_special_tokens: bool = True,
|
| 1250 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
| 1251 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
| 1252 |
+
max_length: Optional[int] = None,
|
| 1253 |
+
stride: int = 0,
|
| 1254 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 1255 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 1256 |
+
return_token_type_ids: Optional[bool] = None,
|
| 1257 |
+
return_attention_mask: Optional[bool] = None,
|
| 1258 |
+
return_overflowing_tokens: bool = False,
|
| 1259 |
+
return_special_tokens_mask: bool = False,
|
| 1260 |
+
return_offsets_mapping: bool = False,
|
| 1261 |
+
return_length: bool = False,
|
| 1262 |
+
verbose: bool = True,
|
| 1263 |
+
**kwargs,
|
| 1264 |
+
) -> BatchEncoding:
|
| 1265 |
+
if return_offsets_mapping:
|
| 1266 |
+
raise NotImplementedError(
|
| 1267 |
+
"return_offset_mapping is not available when using Python tokenizers. "
|
| 1268 |
+
"To use this feature, change your tokenizer to one deriving from "
|
| 1269 |
+
"transformers.PreTrainedTokenizerFast. "
|
| 1270 |
+
"More information on available tokenizers at "
|
| 1271 |
+
"https://github.com/huggingface/transformers/pull/2674"
|
| 1272 |
+
)
|
| 1273 |
+
|
| 1274 |
+
text = answer
|
| 1275 |
+
|
| 1276 |
+
# if necessary, perform lower case
|
| 1277 |
+
if self.do_lower_case:
|
| 1278 |
+
text = text.lower()
|
| 1279 |
+
|
| 1280 |
+
tokens = self.tokenize(text)
|
| 1281 |
+
|
| 1282 |
+
return self.prepare_for_model(
|
| 1283 |
+
ids=self.convert_tokens_to_ids(tokens),
|
| 1284 |
+
add_special_tokens=add_special_tokens,
|
| 1285 |
+
padding=padding_strategy.value,
|
| 1286 |
+
truncation=truncation_strategy.value,
|
| 1287 |
+
max_length=max_length,
|
| 1288 |
+
stride=stride,
|
| 1289 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 1290 |
+
return_tensors=return_tensors,
|
| 1291 |
+
prepend_batch_axis=True,
|
| 1292 |
+
return_attention_mask=return_attention_mask,
|
| 1293 |
+
return_token_type_ids=return_token_type_ids,
|
| 1294 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 1295 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 1296 |
+
return_length=return_length,
|
| 1297 |
+
verbose=verbose,
|
| 1298 |
+
)
|
| 1299 |
+
|
| 1300 |
+
def prepare_table_query(
|
| 1301 |
+
self,
|
| 1302 |
+
table,
|
| 1303 |
+
query,
|
| 1304 |
+
answer=None,
|
| 1305 |
+
truncation_strategy=Union[str, TruncationStrategy, TapexTruncationStrategy],
|
| 1306 |
+
max_length=None,
|
| 1307 |
+
):
|
| 1308 |
+
"""
|
| 1309 |
+
This method can be used to linearize a table and add a corresponding query.
|
| 1310 |
+
|
| 1311 |
+
Optionally, it also handles truncation of the table (cells).
|
| 1312 |
+
|
| 1313 |
+
An answer can be provided for more precise truncation.
|
| 1314 |
+
"""
|
| 1315 |
+
if not table.empty:
|
| 1316 |
+
# step 1: create table dictionary
|
| 1317 |
+
table_content = {"header": list(table.columns), "rows": [list(row.values) for i, row in table.iterrows()]}
|
| 1318 |
+
|
| 1319 |
+
# step 2: modify table internally
|
| 1320 |
+
# always truncate table cells based on self.max_cell_length
|
| 1321 |
+
# optionally truncate rows if truncation_strategy is set to it
|
| 1322 |
+
self.truncate_table_cells(table_content, query, answer)
|
| 1323 |
+
if truncation_strategy == TapexTruncationStrategy.DROP_ROWS_TO_FIT:
|
| 1324 |
+
self.truncate_table_rows(table_content, query, answer, max_length=max_length)
|
| 1325 |
+
|
| 1326 |
+
# step 3: linearize table
|
| 1327 |
+
linear_table = self.table_linearize.process_table(table_content)
|
| 1328 |
+
else:
|
| 1329 |
+
linear_table = ""
|
| 1330 |
+
|
| 1331 |
+
if linear_table == "":
|
| 1332 |
+
logger.warning(
|
| 1333 |
+
"You provide an empty table, or all cells contain much tokens (e.g., >= 1024 tokens). "
|
| 1334 |
+
+ f"Please carefully check the corresponding table with the query : {query}."
|
| 1335 |
+
)
|
| 1336 |
+
if query == "":
|
| 1337 |
+
logger.warning("You provide nothing to query with respect to the table.")
|
| 1338 |
+
# step 4: concatenate query with linear_table
|
| 1339 |
+
separator = " " if query and linear_table else ""
|
| 1340 |
+
joint_input = (query + separator + linear_table) if query else linear_table
|
| 1341 |
+
|
| 1342 |
+
return joint_input
|
| 1343 |
+
|
| 1344 |
+
def truncate_table_cells(self, table_content: Dict, question: str, answer: List):
|
| 1345 |
+
# TODO (Qian): is it possible to revert the original cell if it is in the final answer?
|
| 1346 |
+
cell_mapping = {}
|
| 1347 |
+
for row in table_content["rows"]:
|
| 1348 |
+
for i, cell in enumerate(row):
|
| 1349 |
+
truncate_cell = self.truncate_cell(cell)
|
| 1350 |
+
if truncate_cell is not None:
|
| 1351 |
+
cell_mapping[cell] = truncate_cell
|
| 1352 |
+
row[i] = truncate_cell
|
| 1353 |
+
|
| 1354 |
+
# modify the answer list
|
| 1355 |
+
if answer is not None:
|
| 1356 |
+
for i, case in enumerate(answer):
|
| 1357 |
+
if case in cell_mapping.keys():
|
| 1358 |
+
answer[i] = cell_mapping[case]
|
| 1359 |
+
|
| 1360 |
+
def truncate_cell(self, cell_value):
|
| 1361 |
+
# do not process on these cases
|
| 1362 |
+
if isinstance(cell_value, int) or isinstance(cell_value, float):
|
| 1363 |
+
return cell_value
|
| 1364 |
+
if cell_value.strip() != "":
|
| 1365 |
+
try_tokens = self.tokenize(cell_value)
|
| 1366 |
+
if len(try_tokens) >= self.max_cell_length:
|
| 1367 |
+
retain_tokens = try_tokens[: self.max_cell_length]
|
| 1368 |
+
retain_cell_value = self.convert_tokens_to_string(retain_tokens)
|
| 1369 |
+
return retain_cell_value
|
| 1370 |
+
else:
|
| 1371 |
+
return None
|
| 1372 |
+
else:
|
| 1373 |
+
return cell_value
|
| 1374 |
+
|
| 1375 |
+
def truncate_table_rows(
|
| 1376 |
+
self, table_content: Dict, question: str, answer: Optional[Union[str, List[str]]] = None, max_length=None
|
| 1377 |
+
):
|
| 1378 |
+
"""
|
| 1379 |
+
Args:
|
| 1380 |
+
table_content:
|
| 1381 |
+
{"header": xxx, "rows": xxx, "id" (Optionally): xxx}
|
| 1382 |
+
|
| 1383 |
+
question:
|
| 1384 |
+
natural language sentence
|
| 1385 |
+
|
| 1386 |
+
answer:
|
| 1387 |
+
if for training, is the supervision; otherwise will be empty
|
| 1388 |
+
"""
|
| 1389 |
+
delete_ratio, remain_token_len = self.estimate_delete_ratio(table_content, question, max_length)
|
| 1390 |
+
# randomly delete unrelated rows
|
| 1391 |
+
self.delete_unrelated_rows(table_content, question, answer, delete_ratio)
|
| 1392 |
+
# guarantee the result < max_length
|
| 1393 |
+
maximum_keep_rows = 0
|
| 1394 |
+
for ind, row_example in enumerate(table_content["rows"]):
|
| 1395 |
+
value_string = self.table_linearize.process_row(row_example, ind + 1)
|
| 1396 |
+
value_token_len = len(self.tokenize(value_string))
|
| 1397 |
+
# over the size limit, and take action
|
| 1398 |
+
if value_token_len > remain_token_len:
|
| 1399 |
+
break
|
| 1400 |
+
remain_token_len -= value_token_len
|
| 1401 |
+
maximum_keep_rows += 1
|
| 1402 |
+
del table_content["rows"][maximum_keep_rows:]
|
| 1403 |
+
|
| 1404 |
+
def estimate_delete_ratio(self, table_content: Dict, question: str, max_length=None):
|
| 1405 |
+
if "header" not in table_content or "rows" not in table_content:
|
| 1406 |
+
raise ValueError("The table content should contain both 'header' and 'rows' keys.")
|
| 1407 |
+
# calculate the tokens of header, special tokens will only be pre-prepended into question
|
| 1408 |
+
question_tokens = self.tokenize(question, add_special_tokens=True)
|
| 1409 |
+
# calculate the tokens of header
|
| 1410 |
+
header_string = self.table_linearize.process_header(table_content["header"])
|
| 1411 |
+
header_tokens = self.tokenize(header_string, add_special_tokens=False)
|
| 1412 |
+
# split all cell values into tokens and see how many can be accommodated
|
| 1413 |
+
used_token_len = len(question_tokens) + len(header_tokens)
|
| 1414 |
+
# remaining token space for rows
|
| 1415 |
+
remain_token_len = max_length - used_token_len
|
| 1416 |
+
|
| 1417 |
+
value_string = ""
|
| 1418 |
+
for _, row_example in enumerate(table_content["rows"]):
|
| 1419 |
+
# use a general index to roughly estimate the overall token len
|
| 1420 |
+
value_string += self.table_linearize.process_row(row_example, 100) + " "
|
| 1421 |
+
value_token_len = len(self.tokenize(value_string))
|
| 1422 |
+
|
| 1423 |
+
if value_token_len < remain_token_len:
|
| 1424 |
+
# no row will be deleted
|
| 1425 |
+
return 0.0, remain_token_len
|
| 1426 |
+
else:
|
| 1427 |
+
# calc a roughly delete rate
|
| 1428 |
+
return 1.0 - remain_token_len / value_token_len, remain_token_len
|
| 1429 |
+
|
| 1430 |
+
def delete_unrelated_rows(self, table_content: Dict, question: str, answer: List, delete_ratio: float):
|
| 1431 |
+
"""
|
| 1432 |
+
The argument answer is used only during training.
|
| 1433 |
+
"""
|
| 1434 |
+
truncated_unrelated_indices = []
|
| 1435 |
+
related_indices = []
|
| 1436 |
+
if answer is None or len(answer) == 0:
|
| 1437 |
+
answer_set = set()
|
| 1438 |
+
else:
|
| 1439 |
+
answer_set = {ans_ex.lower() for ans_ex in answer}
|
| 1440 |
+
# add question key words into answer set
|
| 1441 |
+
if question is not None:
|
| 1442 |
+
answer_set.update(question.split())
|
| 1443 |
+
question_set = set(question.strip("?!.,").split(" "))
|
| 1444 |
+
row_max_len = len(table_content["rows"])
|
| 1445 |
+
for _row_idx, row in enumerate(table_content["rows"]):
|
| 1446 |
+
lower_row = {str(cell).lower() for cell in row}
|
| 1447 |
+
if len(lower_row & answer_set) == 0 and len(lower_row & question_set) == 0:
|
| 1448 |
+
truncated_unrelated_indices.append(_row_idx)
|
| 1449 |
+
else:
|
| 1450 |
+
# add neighbours to preserve information aggressively
|
| 1451 |
+
related_indices.extend([_row_idx - 2, _row_idx - 1, _row_idx, _row_idx + 1, _row_idx + 2])
|
| 1452 |
+
|
| 1453 |
+
# remove the neighbours
|
| 1454 |
+
truncated_unrelated_indices = [
|
| 1455 |
+
_row_idx for _row_idx in truncated_unrelated_indices if _row_idx not in related_indices
|
| 1456 |
+
]
|
| 1457 |
+
# select some cases to drop
|
| 1458 |
+
drop_items = min(len(truncated_unrelated_indices), int(len(table_content["rows"]) * delete_ratio))
|
| 1459 |
+
drop_row_indices = random.choices(truncated_unrelated_indices, k=drop_items)
|
| 1460 |
+
|
| 1461 |
+
for _row_idx in reversed(range(row_max_len)):
|
| 1462 |
+
if _row_idx in drop_row_indices:
|
| 1463 |
+
del table_content["rows"][_row_idx]
|
| 1464 |
+
|
| 1465 |
+
# only when the drop ratio is too large, logging for warning.
|
| 1466 |
+
if "id" in table_content and len(drop_row_indices) > 0:
|
| 1467 |
+
logger.warning("Delete {:.2f} rows in table {}".format(len(drop_row_indices), table_content["id"]))
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/trajectory_transformer/__init__.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_import_structure = {
|
| 20 |
+
"configuration_trajectory_transformer": ["TrajectoryTransformerConfig"],
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
if not is_torch_available():
|
| 25 |
+
raise OptionalDependencyNotAvailable()
|
| 26 |
+
except OptionalDependencyNotAvailable:
|
| 27 |
+
pass
|
| 28 |
+
else:
|
| 29 |
+
_import_structure["modeling_trajectory_transformer"] = [
|
| 30 |
+
"TrajectoryTransformerModel",
|
| 31 |
+
"TrajectoryTransformerPreTrainedModel",
|
| 32 |
+
"load_tf_weights_in_trajectory_transformer",
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if TYPE_CHECKING:
|
| 37 |
+
from .configuration_trajectory_transformer import (
|
| 38 |
+
TrajectoryTransformerConfig,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
if not is_torch_available():
|
| 43 |
+
raise OptionalDependencyNotAvailable()
|
| 44 |
+
except OptionalDependencyNotAvailable:
|
| 45 |
+
pass
|
| 46 |
+
else:
|
| 47 |
+
from .modeling_trajectory_transformer import (
|
| 48 |
+
TrajectoryTransformerModel,
|
| 49 |
+
TrajectoryTransformerPreTrainedModel,
|
| 50 |
+
load_tf_weights_in_trajectory_transformer,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
else:
|
| 55 |
+
import sys
|
| 56 |
+
|
| 57 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
tasks/tasksmith-e0f68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2022 The Trajectory Transformers paper authors and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""TrajectoryTransformer model configuration"""
|
| 16 |
+
|
| 17 |
+
from ....configuration_utils import PretrainedConfig
|
| 18 |
+
from ....utils import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class TrajectoryTransformerConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`TrajectoryTransformerModel`]. It is used to
|
| 27 |
+
instantiate an TrajectoryTransformer model according to the specified arguments, defining the model architecture.
|
| 28 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the
|
| 29 |
+
TrajectoryTransformer
|
| 30 |
+
[CarlCochet/trajectory-transformer-halfcheetah-medium-v2](https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2)
|
| 31 |
+
architecture.
|
| 32 |
+
|
| 33 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 34 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
vocab_size (`int`, *optional*, defaults to 100):
|
| 39 |
+
Vocabulary size of the TrajectoryTransformer model. Defines the number of different tokens that can be
|
| 40 |
+
represented by the `trajectories` passed when calling [`TrajectoryTransformerModel`]
|
| 41 |
+
action_weight (`int`, *optional*, defaults to 5):
|
| 42 |
+
Weight of the action in the loss function
|
| 43 |
+
reward_weight (`int`, *optional*, defaults to 1):
|
| 44 |
+
Weight of the reward in the loss function
|
| 45 |
+
value_weight (`int`, *optional*, defaults to 1):
|
| 46 |
+
Weight of the value in the loss function
|
| 47 |
+
block_size (`int`, *optional*, defaults to 249):
|
| 48 |
+
Size of the blocks in the trajectory transformer.
|
| 49 |
+
action_dim (`int`, *optional*, defaults to 6):
|
| 50 |
+
Dimension of the action space.
|
| 51 |
+
observation_dim (`int`, *optional*, defaults to 17):
|
| 52 |
+
Dimension of the observation space.
|
| 53 |
+
transition_dim (`int`, *optional*, defaults to 25):
|
| 54 |
+
Dimension of the transition space.
|
| 55 |
+
n_layer (`int`, *optional*, defaults to 4):
|
| 56 |
+
Number of hidden layers in the Transformer encoder.
|
| 57 |
+
n_head (`int`, *optional*, defaults to 4):
|
| 58 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 59 |
+
n_embd (`int`, *optional*, defaults to 128):
|
| 60 |
+
Dimensionality of the embeddings and hidden states.
|
| 61 |
+
resid_pdrop (`float`, *optional*, defaults to 0.1):
|
| 62 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 63 |
+
embd_pdrop (`int`, *optional*, defaults to 0.1):
|
| 64 |
+
The dropout ratio for the embeddings.
|
| 65 |
+
attn_pdrop (`float`, *optional*, defaults to 0.1):
|
| 66 |
+
The dropout ratio for the attention.
|
| 67 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 68 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 69 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 70 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 71 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 72 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 73 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 74 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 75 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 76 |
+
The epsilon used by the layer normalization layers.
|
| 77 |
+
kaiming_initializer_range (`float, *optional*, defaults to 1):
|
| 78 |
+
A coefficient scaling the negative slope of the kaiming initializer rectifier for EinLinear layers.
|
| 79 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 80 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 81 |
+
relevant if `config.is_decoder=True`.
|
| 82 |
+
Example:
|
| 83 |
+
|
| 84 |
+
```python
|
| 85 |
+
>>> from transformers import TrajectoryTransformerConfig, TrajectoryTransformerModel
|
| 86 |
+
|
| 87 |
+
>>> # Initializing a TrajectoryTransformer CarlCochet/trajectory-transformer-halfcheetah-medium-v2 style configuration
|
| 88 |
+
>>> configuration = TrajectoryTransformerConfig()
|
| 89 |
+
|
| 90 |
+
>>> # Initializing a model (with random weights) from the CarlCochet/trajectory-transformer-halfcheetah-medium-v2 style configuration
|
| 91 |
+
>>> model = TrajectoryTransformerModel(configuration)
|
| 92 |
+
|
| 93 |
+
>>> # Accessing the model configuration
|
| 94 |
+
>>> configuration = model.config
|
| 95 |
+
```"""
|
| 96 |
+
|
| 97 |
+
model_type = "trajectory_transformer"
|
| 98 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 99 |
+
attribute_map = {
|
| 100 |
+
"hidden_size": "n_embd",
|
| 101 |
+
"num_attention_heads": "n_head",
|
| 102 |
+
"num_hidden_layers": "n_layer",
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
def __init__(
|
| 106 |
+
self,
|
| 107 |
+
vocab_size=100,
|
| 108 |
+
action_weight=5,
|
| 109 |
+
reward_weight=1,
|
| 110 |
+
value_weight=1,
|
| 111 |
+
block_size=249,
|
| 112 |
+
action_dim=6,
|
| 113 |
+
observation_dim=17,
|
| 114 |
+
transition_dim=25,
|
| 115 |
+
n_layer=4,
|
| 116 |
+
n_head=4,
|
| 117 |
+
n_embd=128,
|
| 118 |
+
embd_pdrop=0.1,
|
| 119 |
+
attn_pdrop=0.1,
|
| 120 |
+
resid_pdrop=0.1,
|
| 121 |
+
learning_rate=0.0006,
|
| 122 |
+
max_position_embeddings=512,
|
| 123 |
+
initializer_range=0.02,
|
| 124 |
+
layer_norm_eps=1e-12,
|
| 125 |
+
kaiming_initializer_range=1,
|
| 126 |
+
use_cache=True,
|
| 127 |
+
pad_token_id=1,
|
| 128 |
+
bos_token_id=50256,
|
| 129 |
+
eos_token_id=50256,
|
| 130 |
+
**kwargs,
|
| 131 |
+
):
|
| 132 |
+
self.vocab_size = vocab_size
|
| 133 |
+
self.action_weight = action_weight
|
| 134 |
+
self.reward_weight = reward_weight
|
| 135 |
+
self.value_weight = value_weight
|
| 136 |
+
self.max_position_embeddings = max_position_embeddings
|
| 137 |
+
self.block_size = block_size
|
| 138 |
+
self.action_dim = action_dim
|
| 139 |
+
self.observation_dim = observation_dim
|
| 140 |
+
self.transition_dim = transition_dim
|
| 141 |
+
self.learning_rate = learning_rate
|
| 142 |
+
self.n_layer = n_layer
|
| 143 |
+
self.n_head = n_head
|
| 144 |
+
self.n_embd = n_embd
|
| 145 |
+
self.embd_pdrop = embd_pdrop
|
| 146 |
+
self.attn_pdrop = attn_pdrop
|
| 147 |
+
self.resid_pdrop = resid_pdrop
|
| 148 |
+
self.initializer_range = initializer_range
|
| 149 |
+
self.layer_norm_eps = layer_norm_eps
|
| 150 |
+
self.kaiming_initializer_range = kaiming_initializer_range
|
| 151 |
+
self.use_cache = use_cache
|
| 152 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/trajectory_transformer/convert_trajectory_transformer_original_pytorch_checkpoint_to_pytorch.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The Trajectory Transformers paper authors and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""TrajectoryTransformer pytorch checkpoint conversion"""
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import trajectory.utils as utils
|
| 19 |
+
|
| 20 |
+
from transformers import TrajectoryTransformerModel
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Parser(utils.Parser):
|
| 24 |
+
dataset: str = "halfcheetah-medium-expert-v2"
|
| 25 |
+
config: str = "config.offline"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def convert_trajectory_transformer_original_pytorch_checkpoint_to_pytorch(logbase, dataset, loadpath, epoch, device):
|
| 29 |
+
"""Converting Sequential blocks to ModuleList"""
|
| 30 |
+
|
| 31 |
+
gpt, gpt_epoch = utils.load_model(logbase, dataset, loadpath, epoch=epoch, device=device)
|
| 32 |
+
trajectory_transformer = TrajectoryTransformerModel(gpt.config)
|
| 33 |
+
|
| 34 |
+
trajectory_transformer.tok_emb.load_state_dict(gpt.tok_emb.state_dict())
|
| 35 |
+
trajectory_transformer.pos_emb = gpt.pos_emb
|
| 36 |
+
trajectory_transformer.drop.load_state_dict(gpt.drop.state_dict())
|
| 37 |
+
trajectory_transformer.ln_f.load_state_dict(gpt.ln_f.state_dict())
|
| 38 |
+
trajectory_transformer.head.load_state_dict(gpt.head.state_dict())
|
| 39 |
+
|
| 40 |
+
for i, block in enumerate(gpt.blocks):
|
| 41 |
+
trajectory_transformer.blocks[i].ln1.load_state_dict(gpt.blocks[i].ln1.state_dict())
|
| 42 |
+
trajectory_transformer.blocks[i].ln2.load_state_dict(gpt.blocks[i].ln2.state_dict())
|
| 43 |
+
trajectory_transformer.blocks[i].attn.load_state_dict(gpt.blocks[i].attn.state_dict())
|
| 44 |
+
|
| 45 |
+
trajectory_transformer.blocks[i].l1.load_state_dict(gpt.blocks[i].mlp[0].state_dict())
|
| 46 |
+
trajectory_transformer.blocks[i].act.load_state_dict(gpt.blocks[i].mlp[1].state_dict())
|
| 47 |
+
trajectory_transformer.blocks[i].l2.load_state_dict(gpt.blocks[i].mlp[2].state_dict())
|
| 48 |
+
trajectory_transformer.blocks[i].drop.load_state_dict(gpt.blocks[i].mlp[3].state_dict())
|
| 49 |
+
|
| 50 |
+
torch.save(trajectory_transformer.state_dict(), "pytorch_model.bin")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
"""
|
| 55 |
+
To run this script you will need to install the original repository to run the original model. You can find it
|
| 56 |
+
here: https://github.com/jannerm/trajectory-transformer From this repository code you can also download the
|
| 57 |
+
original pytorch checkpoints.
|
| 58 |
+
|
| 59 |
+
Run with the command:
|
| 60 |
+
|
| 61 |
+
```sh
|
| 62 |
+
>>> python convert_trajectory_transformer_original_pytorch_checkpoint_to_pytorch.py --dataset <dataset_name>
|
| 63 |
+
... --gpt_loadpath <path_to_original_pytorch_checkpoint>
|
| 64 |
+
```
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
args = Parser().parse_args("plan")
|
| 68 |
+
convert_trajectory_transformer_original_pytorch_checkpoint_to_pytorch(
|
| 69 |
+
args.logbase, args.dataset, args.gpt_loadpath, args.gpt_epoch, args.device
|
| 70 |
+
)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/trajectory_transformer/modeling_trajectory_transformer.py
ADDED
|
@@ -0,0 +1,603 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The Trajectory Transformers paper authors and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch TrajectoryTransformer model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
import os
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from typing import Optional, Tuple, Union
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import torch
|
| 24 |
+
import torch.utils.checkpoint
|
| 25 |
+
from torch import nn
|
| 26 |
+
from torch.nn import functional as F
|
| 27 |
+
|
| 28 |
+
from ....modeling_utils import PreTrainedModel
|
| 29 |
+
from ....utils import (
|
| 30 |
+
ModelOutput,
|
| 31 |
+
add_start_docstrings,
|
| 32 |
+
add_start_docstrings_to_model_forward,
|
| 33 |
+
logging,
|
| 34 |
+
replace_return_docstrings,
|
| 35 |
+
)
|
| 36 |
+
from .configuration_trajectory_transformer import TrajectoryTransformerConfig
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
logger = logging.get_logger(__name__)
|
| 40 |
+
|
| 41 |
+
_CHECKPOINT_FOR_DOC = "CarlCochet/trajectory-transformer-halfcheetah-medium-v2"
|
| 42 |
+
_CONFIG_FOR_DOC = "TrajectoryTransformerConfig"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def load_tf_weights_in_trajectory_transformer(model, config, tf_checkpoint_path):
|
| 46 |
+
"""Load tf checkpoints in a pytorch model."""
|
| 47 |
+
try:
|
| 48 |
+
import re
|
| 49 |
+
|
| 50 |
+
import numpy as np
|
| 51 |
+
import tensorflow as tf
|
| 52 |
+
except ImportError:
|
| 53 |
+
logger.error(
|
| 54 |
+
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
|
| 55 |
+
"https://www.tensorflow.org/install/ for installation instructions."
|
| 56 |
+
)
|
| 57 |
+
raise
|
| 58 |
+
tf_path = os.path.abspath(tf_checkpoint_path)
|
| 59 |
+
logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
|
| 60 |
+
# Load weights from TF model
|
| 61 |
+
init_vars = tf.train.list_variables(tf_path)
|
| 62 |
+
names = []
|
| 63 |
+
arrays = []
|
| 64 |
+
for name, shape in init_vars:
|
| 65 |
+
logger.info(f"Loading TF weight {name} with shape {shape}")
|
| 66 |
+
array = tf.train.load_variable(tf_path, name)
|
| 67 |
+
names.append(name)
|
| 68 |
+
arrays.append(array)
|
| 69 |
+
|
| 70 |
+
for name, array in zip(names, arrays):
|
| 71 |
+
name = name.split("/")
|
| 72 |
+
# adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
|
| 73 |
+
# which are not required for using pretrained model
|
| 74 |
+
if any(
|
| 75 |
+
n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
|
| 76 |
+
for n in name
|
| 77 |
+
):
|
| 78 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
| 79 |
+
continue
|
| 80 |
+
pointer = model
|
| 81 |
+
for m_name in name:
|
| 82 |
+
if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
|
| 83 |
+
scope_names = re.split(r"_(\d+)", m_name)
|
| 84 |
+
else:
|
| 85 |
+
scope_names = [m_name]
|
| 86 |
+
if scope_names[0] == "kernel" or scope_names[0] == "gamma":
|
| 87 |
+
pointer = getattr(pointer, "weight")
|
| 88 |
+
elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
|
| 89 |
+
pointer = getattr(pointer, "bias")
|
| 90 |
+
elif scope_names[0] == "output_weights":
|
| 91 |
+
pointer = getattr(pointer, "weight")
|
| 92 |
+
elif scope_names[0] == "squad":
|
| 93 |
+
pointer = getattr(pointer, "classifier")
|
| 94 |
+
else:
|
| 95 |
+
try:
|
| 96 |
+
pointer = getattr(pointer, scope_names[0])
|
| 97 |
+
except AttributeError:
|
| 98 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
| 99 |
+
continue
|
| 100 |
+
if len(scope_names) >= 2:
|
| 101 |
+
num = int(scope_names[1])
|
| 102 |
+
pointer = pointer[num]
|
| 103 |
+
if m_name[-11:] == "_embeddings":
|
| 104 |
+
pointer = getattr(pointer, "weight")
|
| 105 |
+
elif m_name == "kernel":
|
| 106 |
+
array = np.transpose(array)
|
| 107 |
+
try:
|
| 108 |
+
if pointer.shape != array.shape:
|
| 109 |
+
raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
|
| 110 |
+
except AssertionError as e:
|
| 111 |
+
e.args += (pointer.shape, array.shape)
|
| 112 |
+
raise
|
| 113 |
+
logger.info(f"Initialize PyTorch weight {name}")
|
| 114 |
+
pointer.data = torch.from_numpy(array)
|
| 115 |
+
return model
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@dataclass
|
| 119 |
+
class TrajectoryTransformerOutput(ModelOutput):
|
| 120 |
+
"""
|
| 121 |
+
Base class for model's outputs that also contains a pooling of the last hidden states.
|
| 122 |
+
|
| 123 |
+
Args:
|
| 124 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 125 |
+
Language modeling loss.
|
| 126 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 127 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 128 |
+
past_key_values (`Tuple[Tuple[torch.Tensor]]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 129 |
+
Tuple of length `config.n_layers`, containing tuples of tensors of shape `(batch_size, num_heads,
|
| 130 |
+
sequence_length, embed_size_per_head)`). Contains pre-computed hidden-states (key and values in the
|
| 131 |
+
attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 132 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 133 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 134 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 135 |
+
plus the initial embedding outputs.
|
| 136 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 137 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 138 |
+
sequence_length)`. GPT2Attentions weights after the attention softmax, used to compute the weighted average
|
| 139 |
+
in the self-attention heads.
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
loss: Optional[torch.FloatTensor] = None
|
| 143 |
+
logits: torch.FloatTensor = None
|
| 144 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
|
| 145 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 146 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class TrajectoryTransformerPreTrainedModel(PreTrainedModel):
|
| 150 |
+
"""
|
| 151 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 152 |
+
models.
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
config_class = TrajectoryTransformerConfig
|
| 156 |
+
load_tf_weights = load_tf_weights_in_trajectory_transformer
|
| 157 |
+
base_model_prefix = "trajectory_transformer"
|
| 158 |
+
main_input_name = "trajectories"
|
| 159 |
+
supports_gradient_checkpointing = True
|
| 160 |
+
|
| 161 |
+
def _init_weights(self, module):
|
| 162 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
| 163 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 164 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
| 165 |
+
module.bias.data.zero_()
|
| 166 |
+
elif isinstance(module, nn.LayerNorm):
|
| 167 |
+
module.bias.data.zero_()
|
| 168 |
+
module.weight.data.fill_(1.0)
|
| 169 |
+
elif isinstance(module, EinLinear):
|
| 170 |
+
for i in range(module.n_models):
|
| 171 |
+
nn.init.kaiming_uniform_(module.weight[i], a=math.sqrt(5) / self.config.kaiming_initializer_range)
|
| 172 |
+
if module.bias is not None:
|
| 173 |
+
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(module.weight[i])
|
| 174 |
+
bound = (1 / math.sqrt(fan_in)) * self.config.initializer_range
|
| 175 |
+
nn.init.uniform_(module.bias[i], -bound, bound)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
TRAJECTORY_TRANSFORMER_START_DOCSTRING = r"""
|
| 179 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
|
| 180 |
+
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 181 |
+
behavior.
|
| 182 |
+
|
| 183 |
+
Parameters:
|
| 184 |
+
config ([`TrajectoryTransformerConfig`]): Model configuration class with all the parameters of the model.
|
| 185 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 186 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
TRAJECTORY_TRANSFORMER_INPUTS_DOCSTRING = r"""
|
| 190 |
+
Args:
|
| 191 |
+
trajectories (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 192 |
+
Batch of trajectories, where a trajectory is a sequence of states, actions and rewards.
|
| 193 |
+
past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`, *optional*):
|
| 194 |
+
Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
|
| 195 |
+
`past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
|
| 196 |
+
their past given to this model should not be passed as `input_ids` as they have already been computed.
|
| 197 |
+
targets (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 198 |
+
Desired targets used to compute the loss.
|
| 199 |
+
attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 200 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 201 |
+
|
| 202 |
+
- 1 for tokens that are **not masked**,
|
| 203 |
+
- 0 for tokens that are **masked**.
|
| 204 |
+
|
| 205 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 206 |
+
use_cache (`bool`, *optional*):
|
| 207 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 208 |
+
`past_key_values`).
|
| 209 |
+
output_attentions (`bool`, *optional*):
|
| 210 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 211 |
+
tensors for more detail.
|
| 212 |
+
output_hidden_states (`bool`, *optional*):
|
| 213 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 214 |
+
more detail.
|
| 215 |
+
return_dict (`bool`, *optional*):
|
| 216 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 217 |
+
"""
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class EinLinear(nn.Module):
|
| 221 |
+
def __init__(self, n_models, in_features, out_features, bias):
|
| 222 |
+
super().__init__()
|
| 223 |
+
self.n_models = n_models
|
| 224 |
+
self.out_features = out_features
|
| 225 |
+
self.in_features = in_features
|
| 226 |
+
self.weight = nn.Parameter(torch.Tensor(n_models, out_features, in_features))
|
| 227 |
+
if bias:
|
| 228 |
+
self.bias = nn.Parameter(torch.Tensor(n_models, out_features))
|
| 229 |
+
else:
|
| 230 |
+
self.register_parameter("bias", None)
|
| 231 |
+
|
| 232 |
+
def reset_parameters(self):
|
| 233 |
+
for i in range(self.n_models):
|
| 234 |
+
nn.init.kaiming_uniform_(self.weight[i], a=math.sqrt(5))
|
| 235 |
+
if self.bias is not None:
|
| 236 |
+
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight[i])
|
| 237 |
+
bound = 1 / math.sqrt(fan_in)
|
| 238 |
+
nn.init.uniform_(self.bias[i], -bound, bound)
|
| 239 |
+
|
| 240 |
+
def forward(self, input):
|
| 241 |
+
"""
|
| 242 |
+
Args:
|
| 243 |
+
input (`torch.FloatTensor` of shape `(B, n_models, input_dim)`):
|
| 244 |
+
The input to the layer.
|
| 245 |
+
"""
|
| 246 |
+
# [ batch_size x n_models x output_dim ]
|
| 247 |
+
output = torch.einsum("eoi,bei->beo", self.weight, input)
|
| 248 |
+
if self.bias is not None:
|
| 249 |
+
raise RuntimeError()
|
| 250 |
+
return output
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
class CausalSelfAttention(nn.Module):
|
| 254 |
+
def __init__(self, config):
|
| 255 |
+
super().__init__()
|
| 256 |
+
|
| 257 |
+
if config.n_embd % config.n_head != 0:
|
| 258 |
+
raise ValueError(f"n_head ({config.n_head}) should be a divisor of n_embd ({config.n_embd})")
|
| 259 |
+
|
| 260 |
+
# key, query, value projections for all heads
|
| 261 |
+
self.key = nn.Linear(config.n_embd, config.n_embd)
|
| 262 |
+
self.query = nn.Linear(config.n_embd, config.n_embd)
|
| 263 |
+
self.value = nn.Linear(config.n_embd, config.n_embd)
|
| 264 |
+
|
| 265 |
+
# regularization
|
| 266 |
+
self.attn_drop = nn.Dropout(config.attn_pdrop)
|
| 267 |
+
self.resid_drop = nn.Dropout(config.resid_pdrop)
|
| 268 |
+
|
| 269 |
+
# output projection
|
| 270 |
+
self.proj = nn.Linear(config.n_embd, config.n_embd)
|
| 271 |
+
|
| 272 |
+
# causal mask to ensure that attention is only applied to the left in the input sequence
|
| 273 |
+
self.register_buffer(
|
| 274 |
+
"mask",
|
| 275 |
+
torch.tril(torch.ones(config.block_size, config.block_size)).view(
|
| 276 |
+
1, 1, config.block_size, config.block_size
|
| 277 |
+
),
|
| 278 |
+
persistent=False,
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
# mask previous value estimates
|
| 282 |
+
joined_dim = config.observation_dim + config.action_dim + 2
|
| 283 |
+
self.mask.squeeze()[:, joined_dim - 1 :: joined_dim] = 0
|
| 284 |
+
|
| 285 |
+
self.n_head = config.n_head
|
| 286 |
+
|
| 287 |
+
def forward(
|
| 288 |
+
self,
|
| 289 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]],
|
| 290 |
+
layer_past: Optional[Tuple[torch.Tensor]] = None,
|
| 291 |
+
use_cache: Optional[bool] = False,
|
| 292 |
+
output_attentions: Optional[bool] = False,
|
| 293 |
+
):
|
| 294 |
+
batch_size, sequence_length, embedding_dim = hidden_states.size()
|
| 295 |
+
|
| 296 |
+
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
|
| 297 |
+
# [ batch_size x n_heads x sequence_length x head_dim ]
|
| 298 |
+
key = (
|
| 299 |
+
self.key(hidden_states)
|
| 300 |
+
.view(batch_size, sequence_length, self.n_head, embedding_dim // self.n_head)
|
| 301 |
+
.transpose(1, 2)
|
| 302 |
+
)
|
| 303 |
+
query = (
|
| 304 |
+
self.query(hidden_states)
|
| 305 |
+
.view(batch_size, sequence_length, self.n_head, embedding_dim // self.n_head)
|
| 306 |
+
.transpose(1, 2)
|
| 307 |
+
)
|
| 308 |
+
value = (
|
| 309 |
+
self.value(hidden_states)
|
| 310 |
+
.view(batch_size, sequence_length, self.n_head, embedding_dim // self.n_head)
|
| 311 |
+
.transpose(1, 2)
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
if layer_past is not None:
|
| 315 |
+
past_key, past_value = layer_past
|
| 316 |
+
key = torch.cat((past_key, key), dim=-2)
|
| 317 |
+
value = torch.cat((past_value, value), dim=-2)
|
| 318 |
+
|
| 319 |
+
if use_cache is True:
|
| 320 |
+
present = (key, value)
|
| 321 |
+
else:
|
| 322 |
+
present = None
|
| 323 |
+
|
| 324 |
+
# causal self-attention
|
| 325 |
+
# [ batch_size x n_heads x sequence_length x sequence_length ]
|
| 326 |
+
attn_weights = (torch.matmul(query, key.transpose(-2, -1))) * (1.0 / math.sqrt(key.size(-1)))
|
| 327 |
+
attn_weights = attn_weights.masked_fill(
|
| 328 |
+
self.mask[:, :, :sequence_length, :sequence_length] == 0, torch.finfo(attn_weights.dtype).min
|
| 329 |
+
)
|
| 330 |
+
attn_weights = F.softmax(attn_weights, dim=-1)
|
| 331 |
+
self._attn_map = attn_weights.clone()
|
| 332 |
+
attn_weights = self.attn_drop(attn_weights)
|
| 333 |
+
|
| 334 |
+
output = torch.matmul(attn_weights, value)
|
| 335 |
+
# [ batch_size x sequence_length x embedding_dim ]
|
| 336 |
+
# re-assemble all head outputs side by side
|
| 337 |
+
output = output.transpose(1, 2).contiguous().view(batch_size, sequence_length, embedding_dim)
|
| 338 |
+
|
| 339 |
+
# output projection
|
| 340 |
+
output = self.resid_drop(self.proj(output))
|
| 341 |
+
|
| 342 |
+
outputs = (output, present)
|
| 343 |
+
if output_attentions:
|
| 344 |
+
outputs += (attn_weights,)
|
| 345 |
+
|
| 346 |
+
return outputs
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
class Block(nn.Module):
|
| 350 |
+
def __init__(self, config):
|
| 351 |
+
super().__init__()
|
| 352 |
+
self.ln1 = nn.LayerNorm(config.n_embd)
|
| 353 |
+
self.ln2 = nn.LayerNorm(config.n_embd)
|
| 354 |
+
self.attn = CausalSelfAttention(config)
|
| 355 |
+
|
| 356 |
+
# MLP
|
| 357 |
+
self.l1 = nn.Linear(config.n_embd, 4 * config.n_embd)
|
| 358 |
+
self.act = nn.GELU()
|
| 359 |
+
self.l2 = nn.Linear(4 * config.n_embd, config.n_embd)
|
| 360 |
+
self.drop = nn.Dropout(config.resid_pdrop)
|
| 361 |
+
|
| 362 |
+
def forward(
|
| 363 |
+
self,
|
| 364 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]],
|
| 365 |
+
layer_past: Optional[Tuple[torch.Tensor]] = None,
|
| 366 |
+
use_cache: Optional[bool] = False,
|
| 367 |
+
output_attentions: Optional[bool] = False,
|
| 368 |
+
):
|
| 369 |
+
residual = hidden_states
|
| 370 |
+
hidden_states = self.ln1(hidden_states)
|
| 371 |
+
|
| 372 |
+
attn_outputs = self.attn(
|
| 373 |
+
hidden_states, layer_past=layer_past, use_cache=use_cache, output_attentions=output_attentions
|
| 374 |
+
)
|
| 375 |
+
attn_output = attn_outputs[0]
|
| 376 |
+
outputs = attn_outputs[1:]
|
| 377 |
+
hidden_states = attn_output + residual
|
| 378 |
+
|
| 379 |
+
residual = hidden_states
|
| 380 |
+
hidden_states = self.ln2(hidden_states)
|
| 381 |
+
hidden_states = self.l1(hidden_states)
|
| 382 |
+
hidden_states = self.act(hidden_states)
|
| 383 |
+
hidden_states = self.l2(hidden_states)
|
| 384 |
+
hidden_states = residual + self.drop(hidden_states)
|
| 385 |
+
|
| 386 |
+
if use_cache:
|
| 387 |
+
outputs = (hidden_states,) + outputs
|
| 388 |
+
else:
|
| 389 |
+
outputs = (hidden_states,) + outputs[1:]
|
| 390 |
+
|
| 391 |
+
return outputs
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
@add_start_docstrings(
|
| 395 |
+
"The bare TrajectoryTransformer Model transformer outputting raw hidden-states without any specific head on top.",
|
| 396 |
+
TRAJECTORY_TRANSFORMER_START_DOCSTRING,
|
| 397 |
+
)
|
| 398 |
+
class TrajectoryTransformerModel(TrajectoryTransformerPreTrainedModel):
|
| 399 |
+
"""the full GPT language model, with a context size of block_size"""
|
| 400 |
+
|
| 401 |
+
def __init__(self, config):
|
| 402 |
+
super().__init__(config)
|
| 403 |
+
|
| 404 |
+
# input embedding stem (+1 for stop token)
|
| 405 |
+
self.tok_emb = nn.Embedding(config.vocab_size * config.transition_dim + 1, config.n_embd)
|
| 406 |
+
|
| 407 |
+
self.pos_emb = nn.Parameter(torch.zeros(1, config.block_size, config.n_embd))
|
| 408 |
+
self.drop = nn.Dropout(config.embd_pdrop)
|
| 409 |
+
# transformer
|
| 410 |
+
self.blocks = nn.ModuleList([Block(config) for _ in range(config.n_layer)])
|
| 411 |
+
# decoder head
|
| 412 |
+
self.ln_f = nn.LayerNorm(config.n_embd)
|
| 413 |
+
self.head = EinLinear(config.transition_dim, config.n_embd, config.vocab_size + 1, bias=False)
|
| 414 |
+
|
| 415 |
+
self.vocab_size = config.vocab_size
|
| 416 |
+
self.stop_token = config.vocab_size * config.transition_dim
|
| 417 |
+
self.block_size = config.block_size
|
| 418 |
+
|
| 419 |
+
self.observation_dim = config.observation_dim
|
| 420 |
+
self.action_dim = config.action_dim
|
| 421 |
+
self.transition_dim = config.transition_dim
|
| 422 |
+
self.embedding_dim = config.n_embd
|
| 423 |
+
|
| 424 |
+
self.action_weight = config.action_weight
|
| 425 |
+
self.reward_weight = config.reward_weight
|
| 426 |
+
self.value_weight = config.value_weight
|
| 427 |
+
|
| 428 |
+
self.gradient_checkpointing = False
|
| 429 |
+
|
| 430 |
+
self.post_init()
|
| 431 |
+
|
| 432 |
+
def get_block_size(self):
|
| 433 |
+
return self.block_size
|
| 434 |
+
|
| 435 |
+
def offset_tokens(self, trajectories):
|
| 436 |
+
_, sequence_length = trajectories.shape
|
| 437 |
+
|
| 438 |
+
n_states = int(np.ceil(sequence_length / self.transition_dim))
|
| 439 |
+
|
| 440 |
+
offsets = torch.arange(self.transition_dim) * self.vocab_size
|
| 441 |
+
offsets = offsets.repeat(n_states).to(trajectories.device)
|
| 442 |
+
|
| 443 |
+
offset_trajectories = trajectories + offsets[:sequence_length]
|
| 444 |
+
offset_trajectories[trajectories == self.vocab_size] = self.stop_token
|
| 445 |
+
return offset_trajectories
|
| 446 |
+
|
| 447 |
+
def pad_to_full_observation(self, hidden_states):
|
| 448 |
+
batch_size, sequence_length, _ = hidden_states.shape
|
| 449 |
+
|
| 450 |
+
n_pad = (self.transition_dim - sequence_length % self.transition_dim) % self.transition_dim
|
| 451 |
+
padding = torch.zeros(batch_size, n_pad, self.embedding_dim, device=hidden_states.device)
|
| 452 |
+
|
| 453 |
+
# [ batch_size x padded_sequence_length' x embedding_dim ]
|
| 454 |
+
hidden_states_pad = torch.cat([hidden_states, padding], dim=1)
|
| 455 |
+
hidden_states_pad = hidden_states_pad.view(-1, self.transition_dim, self.embedding_dim)
|
| 456 |
+
|
| 457 |
+
return hidden_states_pad, n_pad
|
| 458 |
+
|
| 459 |
+
@add_start_docstrings_to_model_forward(
|
| 460 |
+
TRAJECTORY_TRANSFORMER_INPUTS_DOCSTRING.format("batch_size, sequence_length")
|
| 461 |
+
)
|
| 462 |
+
@replace_return_docstrings(output_type=TrajectoryTransformerOutput, config_class=_CONFIG_FOR_DOC)
|
| 463 |
+
def forward(
|
| 464 |
+
self,
|
| 465 |
+
trajectories: Optional[torch.LongTensor] = None,
|
| 466 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
| 467 |
+
targets: Optional[torch.FloatTensor] = None,
|
| 468 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 469 |
+
use_cache: Optional[bool] = None,
|
| 470 |
+
output_attentions: Optional[bool] = None,
|
| 471 |
+
output_hidden_states: Optional[bool] = None,
|
| 472 |
+
return_dict: Optional[bool] = None,
|
| 473 |
+
) -> Union[Tuple[torch.Tensor], TrajectoryTransformerOutput]:
|
| 474 |
+
r"""
|
| 475 |
+
Returns:
|
| 476 |
+
|
| 477 |
+
Examples:
|
| 478 |
+
|
| 479 |
+
```python
|
| 480 |
+
>>> from transformers import TrajectoryTransformerModel
|
| 481 |
+
>>> import torch
|
| 482 |
+
|
| 483 |
+
>>> model = TrajectoryTransformerModel.from_pretrained(
|
| 484 |
+
... "CarlCochet/trajectory-transformer-halfcheetah-medium-v2"
|
| 485 |
+
... )
|
| 486 |
+
>>> model.to(device)
|
| 487 |
+
>>> model.eval()
|
| 488 |
+
|
| 489 |
+
>>> observations_dim, action_dim, batch_size = 17, 6, 256
|
| 490 |
+
>>> seq_length = observations_dim + action_dim + 1
|
| 491 |
+
|
| 492 |
+
>>> trajectories = torch.LongTensor([np.random.permutation(self.seq_length) for _ in range(batch_size)]).to(
|
| 493 |
+
... device
|
| 494 |
+
... )
|
| 495 |
+
>>> targets = torch.LongTensor([np.random.permutation(self.seq_length) for _ in range(batch_size)]).to(device)
|
| 496 |
+
|
| 497 |
+
>>> outputs = model(
|
| 498 |
+
... trajectories,
|
| 499 |
+
... targets=targets,
|
| 500 |
+
... use_cache=True,
|
| 501 |
+
... output_attentions=True,
|
| 502 |
+
... output_hidden_states=True,
|
| 503 |
+
... return_dict=True,
|
| 504 |
+
... )
|
| 505 |
+
```
|
| 506 |
+
"""
|
| 507 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 508 |
+
output_hidden_states = (
|
| 509 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
if past_key_values is None:
|
| 513 |
+
past_key_values = tuple([None] * len(self.blocks))
|
| 514 |
+
|
| 515 |
+
batch_size, sequence_length = trajectories.size()
|
| 516 |
+
|
| 517 |
+
if sequence_length > self.block_size:
|
| 518 |
+
raise ValueError("Cannot forward, model block size is exhausted.")
|
| 519 |
+
|
| 520 |
+
offset_trajectories = self.offset_tokens(trajectories)
|
| 521 |
+
# [ batch_size x sequence_length x embedding_dim ]
|
| 522 |
+
# forward the GPT model
|
| 523 |
+
token_embeddings = self.tok_emb(offset_trajectories) # each index maps to a (learnable) vector
|
| 524 |
+
position_embeddings = self.pos_emb[:, :sequence_length, :] # each position maps to a (learnable) vector
|
| 525 |
+
|
| 526 |
+
hidden_states = self.drop(token_embeddings + position_embeddings)
|
| 527 |
+
|
| 528 |
+
if self.gradient_checkpointing and self.training:
|
| 529 |
+
if use_cache:
|
| 530 |
+
logger.warning_once(
|
| 531 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 532 |
+
)
|
| 533 |
+
use_cache = False
|
| 534 |
+
|
| 535 |
+
presents = () if use_cache else None
|
| 536 |
+
all_self_attentions = () if output_attentions else None
|
| 537 |
+
all_hidden_states = () if output_hidden_states else None
|
| 538 |
+
|
| 539 |
+
for i, (block, layer_past) in enumerate(zip(self.blocks, past_key_values)):
|
| 540 |
+
if output_hidden_states:
|
| 541 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 542 |
+
|
| 543 |
+
if self.gradient_checkpointing and self.training:
|
| 544 |
+
outputs = self._gradient_checkpointing_func(
|
| 545 |
+
block.__call__,
|
| 546 |
+
hidden_states,
|
| 547 |
+
layer_past,
|
| 548 |
+
use_cache,
|
| 549 |
+
output_attentions,
|
| 550 |
+
)
|
| 551 |
+
else:
|
| 552 |
+
outputs = block(hidden_states, layer_past, use_cache, output_attentions)
|
| 553 |
+
|
| 554 |
+
hidden_states = outputs[0]
|
| 555 |
+
if use_cache is True:
|
| 556 |
+
presents = presents + (outputs[1],)
|
| 557 |
+
|
| 558 |
+
if output_attentions:
|
| 559 |
+
all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
|
| 560 |
+
|
| 561 |
+
# [ batch_size x sequence_length x embedding_dim ]
|
| 562 |
+
hidden_state = self.ln_f(hidden_states)
|
| 563 |
+
|
| 564 |
+
if output_hidden_states:
|
| 565 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 566 |
+
|
| 567 |
+
hidden_states_pad, n_pad = self.pad_to_full_observation(hidden_state)
|
| 568 |
+
|
| 569 |
+
logits = self.head(hidden_states_pad)
|
| 570 |
+
logits = logits.reshape(batch_size, sequence_length + n_pad, self.vocab_size + 1)
|
| 571 |
+
logits = logits[:, :sequence_length]
|
| 572 |
+
|
| 573 |
+
# if we are given some desired targets also calculate the loss
|
| 574 |
+
if targets is not None:
|
| 575 |
+
loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), targets.view(-1), reduction="none")
|
| 576 |
+
if self.action_weight != 1 or self.reward_weight != 1 or self.value_weight != 1:
|
| 577 |
+
# make weights
|
| 578 |
+
n_states = int(np.ceil(sequence_length / self.transition_dim))
|
| 579 |
+
weights = torch.cat(
|
| 580 |
+
[
|
| 581 |
+
torch.ones(self.observation_dim, device=trajectories.device),
|
| 582 |
+
torch.ones(self.action_dim, device=trajectories.device) * self.action_weight,
|
| 583 |
+
torch.ones(1, device=trajectories.device) * self.reward_weight,
|
| 584 |
+
torch.ones(1, device=trajectories.device) * self.value_weight,
|
| 585 |
+
]
|
| 586 |
+
)
|
| 587 |
+
weights = weights.repeat(n_states)
|
| 588 |
+
weights = weights[1:].repeat(batch_size, 1)
|
| 589 |
+
loss = loss * weights.view(-1)
|
| 590 |
+
loss = (loss * attention_mask.view(-1)).mean()
|
| 591 |
+
else:
|
| 592 |
+
loss = None
|
| 593 |
+
|
| 594 |
+
if not return_dict:
|
| 595 |
+
return tuple(v for v in [loss, logits, presents, all_hidden_states, all_self_attentions] if v is not None)
|
| 596 |
+
|
| 597 |
+
return TrajectoryTransformerOutput(
|
| 598 |
+
loss=loss,
|
| 599 |
+
logits=logits,
|
| 600 |
+
past_key_values=presents,
|
| 601 |
+
hidden_states=all_hidden_states,
|
| 602 |
+
attentions=all_self_attentions,
|
| 603 |
+
)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/transfo_xl/__init__.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 15 |
+
from typing import TYPE_CHECKING
|
| 16 |
+
|
| 17 |
+
from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
_import_structure = {
|
| 21 |
+
"configuration_transfo_xl": ["TransfoXLConfig"],
|
| 22 |
+
"tokenization_transfo_xl": ["TransfoXLCorpus", "TransfoXLTokenizer"],
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
if not is_torch_available():
|
| 27 |
+
raise OptionalDependencyNotAvailable()
|
| 28 |
+
except OptionalDependencyNotAvailable:
|
| 29 |
+
pass
|
| 30 |
+
else:
|
| 31 |
+
_import_structure["modeling_transfo_xl"] = [
|
| 32 |
+
"AdaptiveEmbedding",
|
| 33 |
+
"TransfoXLForSequenceClassification",
|
| 34 |
+
"TransfoXLLMHeadModel",
|
| 35 |
+
"TransfoXLModel",
|
| 36 |
+
"TransfoXLPreTrainedModel",
|
| 37 |
+
"load_tf_weights_in_transfo_xl",
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
if not is_tf_available():
|
| 42 |
+
raise OptionalDependencyNotAvailable()
|
| 43 |
+
except OptionalDependencyNotAvailable:
|
| 44 |
+
pass
|
| 45 |
+
else:
|
| 46 |
+
_import_structure["modeling_tf_transfo_xl"] = [
|
| 47 |
+
"TFAdaptiveEmbedding",
|
| 48 |
+
"TFTransfoXLForSequenceClassification",
|
| 49 |
+
"TFTransfoXLLMHeadModel",
|
| 50 |
+
"TFTransfoXLMainLayer",
|
| 51 |
+
"TFTransfoXLModel",
|
| 52 |
+
"TFTransfoXLPreTrainedModel",
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
if TYPE_CHECKING:
|
| 57 |
+
from .configuration_transfo_xl import TransfoXLConfig
|
| 58 |
+
from .tokenization_transfo_xl import TransfoXLCorpus, TransfoXLTokenizer
|
| 59 |
+
|
| 60 |
+
try:
|
| 61 |
+
if not is_torch_available():
|
| 62 |
+
raise OptionalDependencyNotAvailable()
|
| 63 |
+
except OptionalDependencyNotAvailable:
|
| 64 |
+
pass
|
| 65 |
+
else:
|
| 66 |
+
from .modeling_transfo_xl import (
|
| 67 |
+
AdaptiveEmbedding,
|
| 68 |
+
TransfoXLForSequenceClassification,
|
| 69 |
+
TransfoXLLMHeadModel,
|
| 70 |
+
TransfoXLModel,
|
| 71 |
+
TransfoXLPreTrainedModel,
|
| 72 |
+
load_tf_weights_in_transfo_xl,
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
if not is_tf_available():
|
| 77 |
+
raise OptionalDependencyNotAvailable()
|
| 78 |
+
except OptionalDependencyNotAvailable:
|
| 79 |
+
pass
|
| 80 |
+
else:
|
| 81 |
+
from .modeling_tf_transfo_xl import (
|
| 82 |
+
TFAdaptiveEmbedding,
|
| 83 |
+
TFTransfoXLForSequenceClassification,
|
| 84 |
+
TFTransfoXLLMHeadModel,
|
| 85 |
+
TFTransfoXLMainLayer,
|
| 86 |
+
TFTransfoXLModel,
|
| 87 |
+
TFTransfoXLPreTrainedModel,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
else:
|
| 91 |
+
import sys
|
| 92 |
+
|
| 93 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/transfo_xl/configuration_transfo_xl.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""Transformer XL configuration"""
|
| 17 |
+
|
| 18 |
+
from ....configuration_utils import PretrainedConfig
|
| 19 |
+
from ....utils import logging
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class TransfoXLConfig(PretrainedConfig):
|
| 26 |
+
"""
|
| 27 |
+
This is the configuration class to store the configuration of a [`TransfoXLModel`] or a [`TFTransfoXLModel`]. It is
|
| 28 |
+
used to instantiate a Transformer-XL model according to the specified arguments, defining the model architecture.
|
| 29 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the TransfoXL
|
| 30 |
+
[transfo-xl/transfo-xl-wt103](https://huggingface.co/transfo-xl/transfo-xl-wt103) architecture.
|
| 31 |
+
|
| 32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 33 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
vocab_size (`int`, *optional*, defaults to 267735):
|
| 37 |
+
Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
|
| 38 |
+
`inputs_ids` passed when calling [`TransfoXLModel`] or [`TFTransfoXLModel`].
|
| 39 |
+
cutoffs (`List[int]`, *optional*, defaults to `[20000, 40000, 200000]`):
|
| 40 |
+
Cutoffs for the adaptive softmax.
|
| 41 |
+
d_model (`int`, *optional*, defaults to 1024):
|
| 42 |
+
Dimensionality of the model's hidden states.
|
| 43 |
+
d_embed (`int`, *optional*, defaults to 1024):
|
| 44 |
+
Dimensionality of the embeddings
|
| 45 |
+
n_head (`int`, *optional*, defaults to 16):
|
| 46 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 47 |
+
d_head (`int`, *optional*, defaults to 64):
|
| 48 |
+
Dimensionality of the model's heads.
|
| 49 |
+
d_inner (`int`, *optional*, defaults to 4096):
|
| 50 |
+
Inner dimension in FF
|
| 51 |
+
div_val (`int`, *optional*, defaults to 4):
|
| 52 |
+
Divident value for adapative input and softmax
|
| 53 |
+
pre_lnorm (`boolean`, *optional*, defaults to `False`):
|
| 54 |
+
Whether or not to apply LayerNorm to the input instead of the output in the blocks.
|
| 55 |
+
n_layer (`int`, *optional*, defaults to 18):
|
| 56 |
+
Number of hidden layers in the Transformer encoder.
|
| 57 |
+
mem_len (`int`, *optional*, defaults to 1600):
|
| 58 |
+
Length of the retained previous heads.
|
| 59 |
+
clamp_len (`int`, *optional*, defaults to 1000):
|
| 60 |
+
Use the same pos embeddings after clamp_len.
|
| 61 |
+
same_length (`boolean`, *optional*, defaults to `True`):
|
| 62 |
+
Whether or not to use the same attn length for all tokens
|
| 63 |
+
proj_share_all_but_first (`boolean`, *optional*, defaults to `True`):
|
| 64 |
+
True to share all but first projs, False not to share.
|
| 65 |
+
attn_type (`int`, *optional*, defaults to 0):
|
| 66 |
+
Attention type. 0 for Transformer-XL, 1 for Shaw et al, 2 for Vaswani et al, 3 for Al Rfou et al.
|
| 67 |
+
sample_softmax (`int`, *optional*, defaults to -1):
|
| 68 |
+
Number of samples in the sampled softmax.
|
| 69 |
+
adaptive (`boolean`, *optional*, defaults to `True`):
|
| 70 |
+
Whether or not to use adaptive softmax.
|
| 71 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 72 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 73 |
+
dropatt (`float`, *optional*, defaults to 0.0):
|
| 74 |
+
The dropout ratio for the attention probabilities.
|
| 75 |
+
untie_r (`boolean`, *optional*, defaults to `True`):
|
| 76 |
+
Whether ot not to untie relative position biases.
|
| 77 |
+
init (`str`, *optional*, defaults to `"normal"`):
|
| 78 |
+
Parameter initializer to use.
|
| 79 |
+
init_range (`float`, *optional*, defaults to 0.01):
|
| 80 |
+
Parameters initialized by U(-init_range, init_range).
|
| 81 |
+
proj_init_std (`float`, *optional*, defaults to 0.01):
|
| 82 |
+
Parameters initialized by N(0, init_std)
|
| 83 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 84 |
+
Parameters initialized by N(0, init_std)
|
| 85 |
+
layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
|
| 86 |
+
The epsilon to use in the layer normalization layers
|
| 87 |
+
eos_token_id (`int`, *optional*, defaults to 0):
|
| 88 |
+
End of stream token id.
|
| 89 |
+
|
| 90 |
+
Examples:
|
| 91 |
+
|
| 92 |
+
```python
|
| 93 |
+
>>> from transformers import TransfoXLConfig, TransfoXLModel
|
| 94 |
+
|
| 95 |
+
>>> # Initializing a Transformer XL configuration
|
| 96 |
+
>>> configuration = TransfoXLConfig()
|
| 97 |
+
|
| 98 |
+
>>> # Initializing a model (with random weights) from the configuration
|
| 99 |
+
>>> model = TransfoXLModel(configuration)
|
| 100 |
+
|
| 101 |
+
>>> # Accessing the model configuration
|
| 102 |
+
>>> configuration = model.config
|
| 103 |
+
```"""
|
| 104 |
+
|
| 105 |
+
model_type = "transfo-xl"
|
| 106 |
+
keys_to_ignore_at_inference = ["mems"]
|
| 107 |
+
attribute_map = {
|
| 108 |
+
"n_token": "vocab_size",
|
| 109 |
+
"hidden_size": "d_model",
|
| 110 |
+
"num_attention_heads": "n_head",
|
| 111 |
+
"num_hidden_layers": "n_layer",
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
def __init__(
|
| 115 |
+
self,
|
| 116 |
+
vocab_size=267735,
|
| 117 |
+
cutoffs=[20000, 40000, 200000],
|
| 118 |
+
d_model=1024,
|
| 119 |
+
d_embed=1024,
|
| 120 |
+
n_head=16,
|
| 121 |
+
d_head=64,
|
| 122 |
+
d_inner=4096,
|
| 123 |
+
div_val=4,
|
| 124 |
+
pre_lnorm=False,
|
| 125 |
+
n_layer=18,
|
| 126 |
+
mem_len=1600,
|
| 127 |
+
clamp_len=1000,
|
| 128 |
+
same_length=True,
|
| 129 |
+
proj_share_all_but_first=True,
|
| 130 |
+
attn_type=0,
|
| 131 |
+
sample_softmax=-1,
|
| 132 |
+
adaptive=True,
|
| 133 |
+
dropout=0.1,
|
| 134 |
+
dropatt=0.0,
|
| 135 |
+
untie_r=True,
|
| 136 |
+
init="normal",
|
| 137 |
+
init_range=0.01,
|
| 138 |
+
proj_init_std=0.01,
|
| 139 |
+
init_std=0.02,
|
| 140 |
+
layer_norm_epsilon=1e-5,
|
| 141 |
+
eos_token_id=0,
|
| 142 |
+
**kwargs,
|
| 143 |
+
):
|
| 144 |
+
self.vocab_size = vocab_size
|
| 145 |
+
self.cutoffs = []
|
| 146 |
+
self.cutoffs.extend(cutoffs)
|
| 147 |
+
if proj_share_all_but_first:
|
| 148 |
+
self.tie_projs = [False] + [True] * len(self.cutoffs)
|
| 149 |
+
else:
|
| 150 |
+
self.tie_projs = [False] + [False] * len(self.cutoffs)
|
| 151 |
+
self.d_model = d_model
|
| 152 |
+
self.d_embed = d_embed
|
| 153 |
+
self.d_head = d_head
|
| 154 |
+
self.d_inner = d_inner
|
| 155 |
+
self.div_val = div_val
|
| 156 |
+
self.pre_lnorm = pre_lnorm
|
| 157 |
+
self.n_layer = n_layer
|
| 158 |
+
self.n_head = n_head
|
| 159 |
+
self.mem_len = mem_len
|
| 160 |
+
self.same_length = same_length
|
| 161 |
+
self.attn_type = attn_type
|
| 162 |
+
self.clamp_len = clamp_len
|
| 163 |
+
self.sample_softmax = sample_softmax
|
| 164 |
+
self.adaptive = adaptive
|
| 165 |
+
self.dropout = dropout
|
| 166 |
+
self.dropatt = dropatt
|
| 167 |
+
self.untie_r = untie_r
|
| 168 |
+
self.init = init
|
| 169 |
+
self.init_range = init_range
|
| 170 |
+
self.proj_init_std = proj_init_std
|
| 171 |
+
self.init_std = init_std
|
| 172 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
| 173 |
+
super().__init__(eos_token_id=eos_token_id, **kwargs)
|
| 174 |
+
|
| 175 |
+
@property
|
| 176 |
+
def max_position_embeddings(self):
|
| 177 |
+
# Message copied from Transformer-XL documentation
|
| 178 |
+
logger.info(f"The model {self.model_type} is one of the few models that has no sequence length limit.")
|
| 179 |
+
return -1
|
| 180 |
+
|
| 181 |
+
@max_position_embeddings.setter
|
| 182 |
+
def max_position_embeddings(self, value):
|
| 183 |
+
# Message copied from Transformer-XL documentation
|
| 184 |
+
raise NotImplementedError(
|
| 185 |
+
f"The model {self.model_type} is one of the few models that has no sequence length limit."
|
| 186 |
+
)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/transfo_xl/convert_transfo_xl_original_tf_checkpoint_to_pytorch.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert Transformer XL checkpoint and datasets."""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import os
|
| 19 |
+
import pickle
|
| 20 |
+
import sys
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
|
| 24 |
+
from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl
|
| 25 |
+
from transformers.models.deprecated.transfo_xl import tokenization_transfo_xl as data_utils
|
| 26 |
+
from transformers.models.deprecated.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES
|
| 27 |
+
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logging.set_verbosity_info()
|
| 31 |
+
|
| 32 |
+
# We do this to be able to load python 2 datasets pickles
|
| 33 |
+
# See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918
|
| 34 |
+
data_utils.Vocab = data_utils.TransfoXLTokenizer
|
| 35 |
+
data_utils.Corpus = data_utils.TransfoXLCorpus
|
| 36 |
+
sys.modules["data_utils"] = data_utils
|
| 37 |
+
sys.modules["vocabulary"] = data_utils
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def convert_transfo_xl_checkpoint_to_pytorch(
|
| 41 |
+
tf_checkpoint_path, transfo_xl_config_file, pytorch_dump_folder_path, transfo_xl_dataset_file
|
| 42 |
+
):
|
| 43 |
+
if transfo_xl_dataset_file:
|
| 44 |
+
# Convert a pre-processed corpus (see original TensorFlow repo)
|
| 45 |
+
with open(transfo_xl_dataset_file, "rb") as fp:
|
| 46 |
+
corpus = pickle.load(fp, encoding="latin1")
|
| 47 |
+
# Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
|
| 48 |
+
pytorch_vocab_dump_path = pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"]
|
| 49 |
+
print(f"Save vocabulary to {pytorch_vocab_dump_path}")
|
| 50 |
+
corpus_vocab_dict = corpus.vocab.__dict__
|
| 51 |
+
torch.save(corpus_vocab_dict, pytorch_vocab_dump_path)
|
| 52 |
+
|
| 53 |
+
corpus_dict_no_vocab = corpus.__dict__
|
| 54 |
+
corpus_dict_no_vocab.pop("vocab", None)
|
| 55 |
+
pytorch_dataset_dump_path = pytorch_dump_folder_path + "/" + CORPUS_NAME
|
| 56 |
+
print(f"Save dataset to {pytorch_dataset_dump_path}")
|
| 57 |
+
torch.save(corpus_dict_no_vocab, pytorch_dataset_dump_path)
|
| 58 |
+
|
| 59 |
+
if tf_checkpoint_path:
|
| 60 |
+
# Convert a pre-trained TensorFlow model
|
| 61 |
+
config_path = os.path.abspath(transfo_xl_config_file)
|
| 62 |
+
tf_path = os.path.abspath(tf_checkpoint_path)
|
| 63 |
+
|
| 64 |
+
print(f"Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.")
|
| 65 |
+
# Initialise PyTorch model
|
| 66 |
+
if transfo_xl_config_file == "":
|
| 67 |
+
config = TransfoXLConfig()
|
| 68 |
+
else:
|
| 69 |
+
config = TransfoXLConfig.from_json_file(transfo_xl_config_file)
|
| 70 |
+
print(f"Building PyTorch model from configuration: {config}")
|
| 71 |
+
model = TransfoXLLMHeadModel(config)
|
| 72 |
+
|
| 73 |
+
model = load_tf_weights_in_transfo_xl(model, config, tf_path)
|
| 74 |
+
# Save pytorch-model
|
| 75 |
+
pytorch_weights_dump_path = os.path.join(pytorch_dump_folder_path, WEIGHTS_NAME)
|
| 76 |
+
pytorch_config_dump_path = os.path.join(pytorch_dump_folder_path, CONFIG_NAME)
|
| 77 |
+
print(f"Save PyTorch model to {os.path.abspath(pytorch_weights_dump_path)}")
|
| 78 |
+
torch.save(model.state_dict(), pytorch_weights_dump_path)
|
| 79 |
+
print(f"Save configuration file to {os.path.abspath(pytorch_config_dump_path)}")
|
| 80 |
+
with open(pytorch_config_dump_path, "w", encoding="utf-8") as f:
|
| 81 |
+
f.write(config.to_json_string())
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
if __name__ == "__main__":
|
| 85 |
+
parser = argparse.ArgumentParser()
|
| 86 |
+
parser.add_argument(
|
| 87 |
+
"--pytorch_dump_folder_path",
|
| 88 |
+
default=None,
|
| 89 |
+
type=str,
|
| 90 |
+
required=True,
|
| 91 |
+
help="Path to the folder to store the PyTorch model or dataset/vocab.",
|
| 92 |
+
)
|
| 93 |
+
parser.add_argument(
|
| 94 |
+
"--tf_checkpoint_path",
|
| 95 |
+
default="",
|
| 96 |
+
type=str,
|
| 97 |
+
help="An optional path to a TensorFlow checkpoint path to be converted.",
|
| 98 |
+
)
|
| 99 |
+
parser.add_argument(
|
| 100 |
+
"--transfo_xl_config_file",
|
| 101 |
+
default="",
|
| 102 |
+
type=str,
|
| 103 |
+
help=(
|
| 104 |
+
"An optional config json file corresponding to the pre-trained BERT model. \n"
|
| 105 |
+
"This specifies the model architecture."
|
| 106 |
+
),
|
| 107 |
+
)
|
| 108 |
+
parser.add_argument(
|
| 109 |
+
"--transfo_xl_dataset_file",
|
| 110 |
+
default="",
|
| 111 |
+
type=str,
|
| 112 |
+
help="An optional dataset file to be converted in a vocabulary.\n"
|
| 113 |
+
"Given the files are in the pickle format, please be wary of passing it files you trust.",
|
| 114 |
+
)
|
| 115 |
+
args = parser.parse_args()
|
| 116 |
+
convert_transfo_xl_checkpoint_to_pytorch(
|
| 117 |
+
args.tf_checkpoint_path,
|
| 118 |
+
args.transfo_xl_config_file,
|
| 119 |
+
args.pytorch_dump_folder_path,
|
| 120 |
+
args.transfo_xl_dataset_file,
|
| 121 |
+
)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl.py
ADDED
|
@@ -0,0 +1,1119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""
|
| 17 |
+
TF 2.0 Transformer XL model.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from typing import List, Optional, Tuple, Union
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
import tensorflow as tf
|
| 27 |
+
|
| 28 |
+
from ....modeling_tf_utils import (
|
| 29 |
+
TFModelInputType,
|
| 30 |
+
TFPreTrainedModel,
|
| 31 |
+
TFSequenceClassificationLoss,
|
| 32 |
+
get_initializer,
|
| 33 |
+
keras,
|
| 34 |
+
keras_serializable,
|
| 35 |
+
unpack_inputs,
|
| 36 |
+
)
|
| 37 |
+
from ....tf_utils import shape_list, stable_softmax
|
| 38 |
+
from ....utils import (
|
| 39 |
+
ModelOutput,
|
| 40 |
+
add_code_sample_docstrings,
|
| 41 |
+
add_start_docstrings,
|
| 42 |
+
add_start_docstrings_to_model_forward,
|
| 43 |
+
logging,
|
| 44 |
+
)
|
| 45 |
+
from .configuration_transfo_xl import TransfoXLConfig
|
| 46 |
+
from .modeling_tf_transfo_xl_utilities import TFAdaptiveSoftmaxMask
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
logger = logging.get_logger(__name__)
|
| 50 |
+
|
| 51 |
+
_CHECKPOINT_FOR_DOC = "transfo-xl/transfo-xl-wt103"
|
| 52 |
+
_CONFIG_FOR_DOC = "TransfoXLConfig"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class TFPositionalEmbedding(keras.layers.Layer):
|
| 56 |
+
def __init__(self, demb, **kwargs):
|
| 57 |
+
super().__init__(**kwargs)
|
| 58 |
+
|
| 59 |
+
self.inv_freq = 1 / (10000 ** (tf.range(0, demb, 2.0) / demb))
|
| 60 |
+
|
| 61 |
+
def call(self, pos_seq, bsz=None):
|
| 62 |
+
self.inv_freq = tf.cast(self.inv_freq, dtype=pos_seq.dtype)
|
| 63 |
+
sinusoid_inp = tf.einsum("i,j->ij", pos_seq, self.inv_freq)
|
| 64 |
+
pos_emb = tf.concat([tf.sin(sinusoid_inp), tf.cos(sinusoid_inp)], -1)
|
| 65 |
+
|
| 66 |
+
if bsz is not None:
|
| 67 |
+
return tf.tile(pos_emb[:, None, :], [1, bsz, 1])
|
| 68 |
+
else:
|
| 69 |
+
return pos_emb[:, None, :]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class TFPositionwiseFF(keras.layers.Layer):
|
| 73 |
+
def __init__(self, d_model, d_inner, dropout, pre_lnorm=False, layer_norm_epsilon=1e-5, init_std=0.02, **kwargs):
|
| 74 |
+
super().__init__(**kwargs)
|
| 75 |
+
|
| 76 |
+
self.d_model = d_model
|
| 77 |
+
self.d_inner = d_inner
|
| 78 |
+
self.dropout = dropout
|
| 79 |
+
|
| 80 |
+
self.layer_1 = keras.layers.Dense(
|
| 81 |
+
d_inner, kernel_initializer=get_initializer(init_std), activation=tf.nn.relu, name="CoreNet_._0"
|
| 82 |
+
)
|
| 83 |
+
self.drop_1 = keras.layers.Dropout(dropout)
|
| 84 |
+
self.layer_2 = keras.layers.Dense(d_model, kernel_initializer=get_initializer(init_std), name="CoreNet_._3")
|
| 85 |
+
self.drop_2 = keras.layers.Dropout(dropout)
|
| 86 |
+
|
| 87 |
+
self.layer_norm = keras.layers.LayerNormalization(epsilon=layer_norm_epsilon, name="layer_norm")
|
| 88 |
+
|
| 89 |
+
self.pre_lnorm = pre_lnorm
|
| 90 |
+
|
| 91 |
+
def call(self, inp, training=False):
|
| 92 |
+
if self.pre_lnorm:
|
| 93 |
+
# layer normalization + positionwise feed-forward
|
| 94 |
+
core_out = self.layer_norm(inp)
|
| 95 |
+
core_out = self.layer_1(core_out)
|
| 96 |
+
core_out = self.drop_1(core_out, training=training)
|
| 97 |
+
core_out = self.layer_2(core_out)
|
| 98 |
+
core_out = self.drop_2(core_out, training=training)
|
| 99 |
+
|
| 100 |
+
# residual connection
|
| 101 |
+
output = core_out + inp
|
| 102 |
+
else:
|
| 103 |
+
# positionwise feed-forward
|
| 104 |
+
core_out = self.layer_1(inp)
|
| 105 |
+
core_out = self.drop_1(core_out, training=training)
|
| 106 |
+
core_out = self.layer_2(core_out)
|
| 107 |
+
core_out = self.drop_2(core_out, training=training)
|
| 108 |
+
|
| 109 |
+
# residual connection + layer normalization
|
| 110 |
+
output = self.layer_norm(inp + core_out)
|
| 111 |
+
|
| 112 |
+
return output
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class TFRelPartialLearnableMultiHeadAttn(keras.layers.Layer):
|
| 116 |
+
def __init__(
|
| 117 |
+
self,
|
| 118 |
+
n_head,
|
| 119 |
+
d_model,
|
| 120 |
+
d_head,
|
| 121 |
+
dropout,
|
| 122 |
+
dropatt=0.0,
|
| 123 |
+
pre_lnorm=False,
|
| 124 |
+
r_r_bias=None,
|
| 125 |
+
r_w_bias=None,
|
| 126 |
+
layer_norm_epsilon=1e-5,
|
| 127 |
+
init_std=0.02,
|
| 128 |
+
output_attentions=False,
|
| 129 |
+
**kwargs,
|
| 130 |
+
):
|
| 131 |
+
super().__init__(**kwargs)
|
| 132 |
+
|
| 133 |
+
self.n_head = n_head
|
| 134 |
+
self.d_model = d_model
|
| 135 |
+
self.d_head = d_head
|
| 136 |
+
self.dropout = dropout
|
| 137 |
+
self.output_attentions = output_attentions
|
| 138 |
+
|
| 139 |
+
self.qkv_net = keras.layers.Dense(
|
| 140 |
+
3 * n_head * d_head, kernel_initializer=get_initializer(init_std), use_bias=False, name="qkv_net"
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
self.drop = keras.layers.Dropout(dropout)
|
| 144 |
+
self.dropatt = keras.layers.Dropout(dropatt)
|
| 145 |
+
self.o_net = keras.layers.Dense(
|
| 146 |
+
d_model, kernel_initializer=get_initializer(init_std), use_bias=False, name="o_net"
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
self.layer_norm = keras.layers.LayerNormalization(epsilon=layer_norm_epsilon, name="layer_norm")
|
| 150 |
+
|
| 151 |
+
self.scale = 1 / (d_head**0.5)
|
| 152 |
+
|
| 153 |
+
self.pre_lnorm = pre_lnorm
|
| 154 |
+
|
| 155 |
+
if r_r_bias is not None and r_w_bias is not None: # Biases are shared
|
| 156 |
+
self.r_r_bias = r_r_bias
|
| 157 |
+
self.r_w_bias = r_w_bias
|
| 158 |
+
else:
|
| 159 |
+
self.r_r_bias = None
|
| 160 |
+
self.r_w_bias = None
|
| 161 |
+
|
| 162 |
+
self.r_net = keras.layers.Dense(
|
| 163 |
+
self.n_head * self.d_head, kernel_initializer=get_initializer(init_std), use_bias=False, name="r_net"
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
def build(self, input_shape):
|
| 167 |
+
if self.r_r_bias is None or self.r_w_bias is None: # Biases are not shared
|
| 168 |
+
self.r_r_bias = self.add_weight(
|
| 169 |
+
shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_r_bias"
|
| 170 |
+
)
|
| 171 |
+
self.r_w_bias = self.add_weight(
|
| 172 |
+
shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_w_bias"
|
| 173 |
+
)
|
| 174 |
+
super().build(input_shape)
|
| 175 |
+
|
| 176 |
+
def _rel_shift(self, x):
|
| 177 |
+
x_size = shape_list(x)
|
| 178 |
+
|
| 179 |
+
x = tf.pad(x, [[0, 0], [1, 0], [0, 0], [0, 0]])
|
| 180 |
+
x = tf.reshape(x, [x_size[1] + 1, x_size[0], x_size[2], x_size[3]])
|
| 181 |
+
x = tf.slice(x, [1, 0, 0, 0], [-1, -1, -1, -1])
|
| 182 |
+
x = tf.reshape(x, x_size)
|
| 183 |
+
|
| 184 |
+
return x
|
| 185 |
+
|
| 186 |
+
def call(self, w, r, attn_mask, mems, head_mask, output_attentions, training=False):
|
| 187 |
+
qlen, rlen, bsz = shape_list(w)[0], shape_list(r)[0], shape_list(w)[1]
|
| 188 |
+
|
| 189 |
+
if mems is not None:
|
| 190 |
+
mems = tf.cast(mems, dtype=w.dtype)
|
| 191 |
+
cat = tf.concat([mems, w], 0)
|
| 192 |
+
if self.pre_lnorm:
|
| 193 |
+
w_heads = self.qkv_net(self.layer_norm(cat))
|
| 194 |
+
else:
|
| 195 |
+
w_heads = self.qkv_net(cat)
|
| 196 |
+
r_head_k = self.r_net(r)
|
| 197 |
+
|
| 198 |
+
w_head_q, w_head_k, w_head_v = tf.split(w_heads, 3, axis=-1)
|
| 199 |
+
w_head_q = w_head_q[-qlen:]
|
| 200 |
+
else:
|
| 201 |
+
if self.pre_lnorm:
|
| 202 |
+
w_heads = self.qkv_net(self.layer_norm(w))
|
| 203 |
+
else:
|
| 204 |
+
w_heads = self.qkv_net(w)
|
| 205 |
+
r_head_k = self.r_net(r)
|
| 206 |
+
|
| 207 |
+
w_head_q, w_head_k, w_head_v = tf.split(w_heads, 3, axis=-1)
|
| 208 |
+
|
| 209 |
+
klen = shape_list(w_head_k)[0]
|
| 210 |
+
|
| 211 |
+
w_head_q = tf.reshape(w_head_q, (qlen, bsz, self.n_head, self.d_head)) # qlen x bsz x n_head x d_head
|
| 212 |
+
w_head_k = tf.reshape(w_head_k, (klen, bsz, self.n_head, self.d_head)) # qlen x bsz x n_head x d_head
|
| 213 |
+
w_head_v = tf.reshape(w_head_v, (klen, bsz, self.n_head, self.d_head)) # qlen x bsz x n_head x d_head
|
| 214 |
+
|
| 215 |
+
r_head_k = tf.reshape(r_head_k, (rlen, self.n_head, self.d_head)) # qlen x n_head x d_head
|
| 216 |
+
|
| 217 |
+
# compute attention score
|
| 218 |
+
rw_head_q = w_head_q + self.r_w_bias # qlen x bsz x n_head x d_head
|
| 219 |
+
AC = tf.einsum("ibnd,jbnd->ijbn", rw_head_q, w_head_k) # qlen x klen x bsz x n_head
|
| 220 |
+
|
| 221 |
+
rr_head_q = w_head_q + self.r_r_bias
|
| 222 |
+
BD = tf.einsum("ibnd,jnd->ijbn", rr_head_q, r_head_k) # qlen x klen x bsz x n_head
|
| 223 |
+
BD = self._rel_shift(BD)
|
| 224 |
+
|
| 225 |
+
# [qlen x klen x bsz x n_head]
|
| 226 |
+
attn_score = AC + BD
|
| 227 |
+
attn_score = attn_score * self.scale
|
| 228 |
+
|
| 229 |
+
# compute attention probability
|
| 230 |
+
if attn_mask is not None:
|
| 231 |
+
attn_mask_t = attn_mask[:, :, None, None]
|
| 232 |
+
attn_mask_t = tf.cast(attn_mask_t, dtype=attn_score.dtype)
|
| 233 |
+
attn_score = attn_score * (1.0 - attn_mask_t) - 1e30 * attn_mask_t
|
| 234 |
+
|
| 235 |
+
# [qlen x klen x bsz x n_head]
|
| 236 |
+
attn_prob = stable_softmax(attn_score, axis=1)
|
| 237 |
+
attn_prob = self.dropatt(attn_prob, training=training)
|
| 238 |
+
|
| 239 |
+
# Mask heads if we want to
|
| 240 |
+
if head_mask is not None:
|
| 241 |
+
attn_prob = attn_prob * head_mask
|
| 242 |
+
|
| 243 |
+
# compute attention vector
|
| 244 |
+
attn_vec = tf.einsum("ijbn,jbnd->ibnd", attn_prob, w_head_v)
|
| 245 |
+
|
| 246 |
+
# [qlen x bsz x n_head x d_head]
|
| 247 |
+
attn_vec_sizes = shape_list(attn_vec)
|
| 248 |
+
attn_vec = tf.reshape(attn_vec, (attn_vec_sizes[0], attn_vec_sizes[1], self.n_head * self.d_head))
|
| 249 |
+
|
| 250 |
+
# linear projection
|
| 251 |
+
attn_out = self.o_net(attn_vec)
|
| 252 |
+
attn_out = self.drop(attn_out, training=training)
|
| 253 |
+
|
| 254 |
+
if self.pre_lnorm:
|
| 255 |
+
# residual connection
|
| 256 |
+
outputs = [w + attn_out]
|
| 257 |
+
else:
|
| 258 |
+
# residual connection + layer normalization
|
| 259 |
+
outputs = [self.layer_norm(w + attn_out)]
|
| 260 |
+
|
| 261 |
+
if output_attentions:
|
| 262 |
+
outputs.append(attn_prob)
|
| 263 |
+
|
| 264 |
+
return outputs
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class TFRelPartialLearnableDecoderLayer(keras.layers.Layer):
|
| 268 |
+
def __init__(
|
| 269 |
+
self,
|
| 270 |
+
n_head,
|
| 271 |
+
d_model,
|
| 272 |
+
d_head,
|
| 273 |
+
d_inner,
|
| 274 |
+
dropout,
|
| 275 |
+
dropatt=0.0,
|
| 276 |
+
pre_lnorm=False,
|
| 277 |
+
r_w_bias=None,
|
| 278 |
+
r_r_bias=None,
|
| 279 |
+
layer_norm_epsilon=1e-5,
|
| 280 |
+
init_std=0.02,
|
| 281 |
+
output_attentions=False,
|
| 282 |
+
**kwargs,
|
| 283 |
+
):
|
| 284 |
+
super().__init__(**kwargs)
|
| 285 |
+
|
| 286 |
+
self.dec_attn = TFRelPartialLearnableMultiHeadAttn(
|
| 287 |
+
n_head,
|
| 288 |
+
d_model,
|
| 289 |
+
d_head,
|
| 290 |
+
dropout,
|
| 291 |
+
dropatt=dropatt,
|
| 292 |
+
pre_lnorm=pre_lnorm,
|
| 293 |
+
r_w_bias=r_w_bias,
|
| 294 |
+
r_r_bias=r_r_bias,
|
| 295 |
+
init_std=init_std,
|
| 296 |
+
layer_norm_epsilon=layer_norm_epsilon,
|
| 297 |
+
output_attentions=output_attentions,
|
| 298 |
+
name="dec_attn",
|
| 299 |
+
)
|
| 300 |
+
self.pos_ff = TFPositionwiseFF(
|
| 301 |
+
d_model,
|
| 302 |
+
d_inner,
|
| 303 |
+
dropout,
|
| 304 |
+
pre_lnorm=pre_lnorm,
|
| 305 |
+
init_std=init_std,
|
| 306 |
+
layer_norm_epsilon=layer_norm_epsilon,
|
| 307 |
+
name="pos_ff",
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
def call(self, dec_inp, r, dec_attn_mask, mems, head_mask, output_attentions, training=False):
|
| 311 |
+
attn_outputs = self.dec_attn(dec_inp, r, dec_attn_mask, mems, head_mask, output_attentions, training=training)
|
| 312 |
+
ff_output = self.pos_ff(attn_outputs[0], training=training)
|
| 313 |
+
|
| 314 |
+
outputs = [ff_output] + attn_outputs[1:]
|
| 315 |
+
|
| 316 |
+
return outputs
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class TFTransfoEmbeddings(keras.layers.Layer):
|
| 320 |
+
def __init__(self, vocab_size, emb_size, init_std, **kwargs):
|
| 321 |
+
super().__init__(**kwargs)
|
| 322 |
+
|
| 323 |
+
self.vocab_size = vocab_size
|
| 324 |
+
self.emb_size = emb_size
|
| 325 |
+
self.init_std = init_std
|
| 326 |
+
|
| 327 |
+
def build(self, input_shape):
|
| 328 |
+
self.weight = self.add_weight(
|
| 329 |
+
shape=(self.vocab_size, self.emb_size),
|
| 330 |
+
initializer=get_initializer(self.init_std),
|
| 331 |
+
name="embeddings",
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
super().build(input_shape)
|
| 335 |
+
|
| 336 |
+
def call(self, inputs):
|
| 337 |
+
return tf.gather(self.weight, inputs)
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
class TFAdaptiveEmbedding(keras.layers.Layer):
|
| 341 |
+
def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, init_std=0.02, sample_softmax=False, **kwargs):
|
| 342 |
+
super().__init__(**kwargs)
|
| 343 |
+
|
| 344 |
+
self.n_token = n_token
|
| 345 |
+
self.d_embed = d_embed
|
| 346 |
+
self.init_std = init_std
|
| 347 |
+
|
| 348 |
+
self.cutoffs = cutoffs + [n_token]
|
| 349 |
+
self.div_val = div_val
|
| 350 |
+
self.d_proj = d_proj
|
| 351 |
+
|
| 352 |
+
self.emb_scale = d_proj**0.5
|
| 353 |
+
|
| 354 |
+
self.cutoff_ends = [0] + self.cutoffs
|
| 355 |
+
|
| 356 |
+
self.emb_layers = []
|
| 357 |
+
self.emb_projs = []
|
| 358 |
+
|
| 359 |
+
if div_val == 1:
|
| 360 |
+
raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
|
| 361 |
+
else:
|
| 362 |
+
for i in range(len(self.cutoffs)):
|
| 363 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 364 |
+
d_emb_i = d_embed // (div_val**i)
|
| 365 |
+
self.emb_layers.append(
|
| 366 |
+
TFTransfoEmbeddings(
|
| 367 |
+
r_idx - l_idx,
|
| 368 |
+
d_emb_i,
|
| 369 |
+
init_std,
|
| 370 |
+
name=f"emb_layers_._{i}",
|
| 371 |
+
)
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
def build(self, input_shape):
|
| 375 |
+
for i in range(len(self.cutoffs)):
|
| 376 |
+
d_emb_i = self.d_embed // (self.div_val**i)
|
| 377 |
+
self.emb_projs.append(
|
| 378 |
+
self.add_weight(
|
| 379 |
+
shape=(d_emb_i, self.d_proj),
|
| 380 |
+
initializer=get_initializer(self.init_std),
|
| 381 |
+
trainable=True,
|
| 382 |
+
name=f"emb_projs_._{i}",
|
| 383 |
+
)
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
super().build(input_shape)
|
| 387 |
+
|
| 388 |
+
def call(self, inp):
|
| 389 |
+
if self.div_val == 1:
|
| 390 |
+
raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
|
| 391 |
+
else:
|
| 392 |
+
inp_flat = tf.reshape(inp, (-1,))
|
| 393 |
+
emb_flat = tf.zeros([shape_list(inp_flat)[0], self.d_proj])
|
| 394 |
+
for i in range(len(self.cutoffs)):
|
| 395 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 396 |
+
|
| 397 |
+
mask_i = (inp_flat >= l_idx) & (inp_flat < r_idx)
|
| 398 |
+
|
| 399 |
+
inp_i = tf.boolean_mask(inp_flat, mask_i) - l_idx
|
| 400 |
+
emb_i = self.emb_layers[i](inp_i)
|
| 401 |
+
emb_i = tf.einsum("id,de->ie", emb_i, self.emb_projs[i])
|
| 402 |
+
|
| 403 |
+
mask_idx = tf.where(mask_i)
|
| 404 |
+
scatter = tf.scatter_nd(mask_idx, emb_i, shape_list(emb_flat))
|
| 405 |
+
emb_flat = tf.cast(emb_flat, dtype=scatter.dtype)
|
| 406 |
+
emb_flat += scatter
|
| 407 |
+
|
| 408 |
+
embed_shape = shape_list(inp) + [self.d_proj]
|
| 409 |
+
embed = tf.reshape(emb_flat, embed_shape)
|
| 410 |
+
|
| 411 |
+
embed *= self.emb_scale
|
| 412 |
+
|
| 413 |
+
return embed
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
@keras_serializable
|
| 417 |
+
class TFTransfoXLMainLayer(keras.layers.Layer):
|
| 418 |
+
config_class = TransfoXLConfig
|
| 419 |
+
|
| 420 |
+
def __init__(self, config, **kwargs):
|
| 421 |
+
super().__init__(**kwargs)
|
| 422 |
+
|
| 423 |
+
self.config = config
|
| 424 |
+
self.output_hidden_states = config.output_hidden_states
|
| 425 |
+
self.output_attentions = config.output_attentions
|
| 426 |
+
self.return_dict = config.use_return_dict
|
| 427 |
+
|
| 428 |
+
self.n_token = config.vocab_size
|
| 429 |
+
|
| 430 |
+
self.d_embed = config.d_embed
|
| 431 |
+
self.d_model = config.d_model
|
| 432 |
+
self.n_head = config.n_head
|
| 433 |
+
self.d_head = config.d_head
|
| 434 |
+
self.untie_r = config.untie_r
|
| 435 |
+
|
| 436 |
+
self.word_emb = TFAdaptiveEmbedding(
|
| 437 |
+
config.vocab_size,
|
| 438 |
+
config.d_embed,
|
| 439 |
+
config.d_model,
|
| 440 |
+
config.cutoffs,
|
| 441 |
+
div_val=config.div_val,
|
| 442 |
+
init_std=config.init_std,
|
| 443 |
+
name="word_emb",
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
self.drop = keras.layers.Dropout(config.dropout)
|
| 447 |
+
|
| 448 |
+
self.n_layer = config.n_layer
|
| 449 |
+
self.mem_len = config.mem_len
|
| 450 |
+
self.attn_type = config.attn_type
|
| 451 |
+
|
| 452 |
+
self.layers = []
|
| 453 |
+
if config.attn_type == 0: # the default attention
|
| 454 |
+
for i in range(config.n_layer):
|
| 455 |
+
self.layers.append(
|
| 456 |
+
TFRelPartialLearnableDecoderLayer(
|
| 457 |
+
config.n_head,
|
| 458 |
+
config.d_model,
|
| 459 |
+
config.d_head,
|
| 460 |
+
config.d_inner,
|
| 461 |
+
config.dropout,
|
| 462 |
+
dropatt=config.dropatt,
|
| 463 |
+
pre_lnorm=config.pre_lnorm,
|
| 464 |
+
r_w_bias=None if self.untie_r else self.r_w_bias,
|
| 465 |
+
r_r_bias=None if self.untie_r else self.r_r_bias,
|
| 466 |
+
layer_norm_epsilon=config.layer_norm_epsilon,
|
| 467 |
+
init_std=config.init_std,
|
| 468 |
+
output_attentions=self.output_attentions,
|
| 469 |
+
name=f"layers_._{i}",
|
| 470 |
+
)
|
| 471 |
+
)
|
| 472 |
+
else: # learnable embeddings and absolute embeddings
|
| 473 |
+
raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
|
| 474 |
+
|
| 475 |
+
self.same_length = config.same_length
|
| 476 |
+
self.clamp_len = config.clamp_len
|
| 477 |
+
|
| 478 |
+
if self.attn_type == 0: # default attention
|
| 479 |
+
self.pos_emb = TFPositionalEmbedding(self.d_model, name="pos_emb")
|
| 480 |
+
else: # learnable embeddings and absolute embeddings
|
| 481 |
+
raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
|
| 482 |
+
|
| 483 |
+
def build(self, input_shape):
|
| 484 |
+
if not self.untie_r:
|
| 485 |
+
self.r_w_bias = self.add_weight(
|
| 486 |
+
shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_w_bias"
|
| 487 |
+
)
|
| 488 |
+
self.r_r_bias = self.add_weight(
|
| 489 |
+
shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_r_bias"
|
| 490 |
+
)
|
| 491 |
+
super().build(input_shape)
|
| 492 |
+
|
| 493 |
+
def get_input_embeddings(self):
|
| 494 |
+
return self.word_emb
|
| 495 |
+
|
| 496 |
+
def set_input_embeddings(self, value):
|
| 497 |
+
raise NotImplementedError
|
| 498 |
+
|
| 499 |
+
def backward_compatible(self):
|
| 500 |
+
self.sample_softmax = -1
|
| 501 |
+
|
| 502 |
+
def reset_memory_length(self, mem_len):
|
| 503 |
+
self.mem_len = mem_len
|
| 504 |
+
|
| 505 |
+
def _prune_heads(self, heads):
|
| 506 |
+
raise NotImplementedError
|
| 507 |
+
|
| 508 |
+
def init_mems(self, bsz):
|
| 509 |
+
if self.mem_len > 0:
|
| 510 |
+
mems = []
|
| 511 |
+
for i in range(self.n_layer):
|
| 512 |
+
empty = tf.zeros([self.mem_len, bsz, self.d_model])
|
| 513 |
+
mems.append(empty)
|
| 514 |
+
|
| 515 |
+
return mems
|
| 516 |
+
else:
|
| 517 |
+
return None
|
| 518 |
+
|
| 519 |
+
def _update_mems(self, hids, mems, mlen, qlen):
|
| 520 |
+
# does not deal with None
|
| 521 |
+
if mems is None:
|
| 522 |
+
return None
|
| 523 |
+
|
| 524 |
+
# mems is not None
|
| 525 |
+
assert len(hids) == len(mems), "len(hids) != len(mems)"
|
| 526 |
+
|
| 527 |
+
# There are `mlen + qlen` steps that can be cached into mems
|
| 528 |
+
new_mems = []
|
| 529 |
+
end_idx = mlen + tf.math.maximum(0, qlen)
|
| 530 |
+
beg_idx = tf.math.maximum(0, end_idx - tf.convert_to_tensor(self.mem_len))
|
| 531 |
+
for i in range(len(hids)):
|
| 532 |
+
mems[i] = tf.cast(mems[i], dtype=hids[i].dtype)
|
| 533 |
+
cat = tf.concat([mems[i], hids[i]], axis=0)
|
| 534 |
+
tf.stop_gradient(cat)
|
| 535 |
+
new_mems.append(cat[beg_idx:end_idx])
|
| 536 |
+
|
| 537 |
+
return new_mems
|
| 538 |
+
|
| 539 |
+
@unpack_inputs
|
| 540 |
+
def call(
|
| 541 |
+
self,
|
| 542 |
+
input_ids: TFModelInputType | None = None,
|
| 543 |
+
mems: List[tf.Tensor] | None = None,
|
| 544 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 545 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 546 |
+
output_attentions: Optional[bool] = None,
|
| 547 |
+
output_hidden_states: Optional[bool] = None,
|
| 548 |
+
return_dict: Optional[bool] = None,
|
| 549 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 550 |
+
training: bool = False,
|
| 551 |
+
):
|
| 552 |
+
# the original code for Transformer-XL used shapes [len, bsz] but we want a unified interface in the library
|
| 553 |
+
# so we transpose here from shape [bsz, len] to shape [len, bsz]
|
| 554 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 555 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 556 |
+
elif input_ids is not None:
|
| 557 |
+
input_ids = tf.transpose(input_ids, perm=(1, 0))
|
| 558 |
+
qlen, bsz = shape_list(input_ids)
|
| 559 |
+
elif inputs_embeds is not None:
|
| 560 |
+
inputs_embeds = tf.transpose(inputs_embeds, perm=(1, 0, 2))
|
| 561 |
+
qlen, bsz = shape_list(inputs_embeds)[:2]
|
| 562 |
+
else:
|
| 563 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 564 |
+
|
| 565 |
+
if mems is None:
|
| 566 |
+
mems = self.init_mems(bsz)
|
| 567 |
+
|
| 568 |
+
# Prepare head mask if needed
|
| 569 |
+
# 1.0 in head_mask indicate we keep the head
|
| 570 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 571 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] (a head_mask for each layer)
|
| 572 |
+
# and head_mask is converted to shape [num_hidden_layers x qlen x klen x bsz x n_head]
|
| 573 |
+
if head_mask is not None:
|
| 574 |
+
raise NotImplementedError
|
| 575 |
+
else:
|
| 576 |
+
head_mask = [None] * self.n_layer
|
| 577 |
+
|
| 578 |
+
if inputs_embeds is not None:
|
| 579 |
+
word_emb = inputs_embeds
|
| 580 |
+
else:
|
| 581 |
+
word_emb = self.word_emb(input_ids)
|
| 582 |
+
|
| 583 |
+
mlen = shape_list(mems[0])[0] if mems is not None else 0
|
| 584 |
+
klen = mlen + qlen
|
| 585 |
+
|
| 586 |
+
# Compute decoder attention mask
|
| 587 |
+
all_ones = tf.ones([qlen, klen], dtype=tf.int32)
|
| 588 |
+
upper_mask = 1 - tf.linalg.band_part(tf.ones([qlen, klen], dtype=tf.int32), -1, mlen)
|
| 589 |
+
if self.same_length:
|
| 590 |
+
mask_len = klen - self.mem_len
|
| 591 |
+
mask_shift_len = qlen - tf.nn.relu(mask_len) # Lazy clamping of negatives to zero
|
| 592 |
+
|
| 593 |
+
# Use an indicator variable instead of a conditional to keep the compiler happy
|
| 594 |
+
lower_mask = tf.linalg.band_part(all_ones, -1, 0) - (
|
| 595 |
+
tf.linalg.band_part(all_ones, mask_shift_len - 1, 0) * tf.cast(mask_shift_len != 0, tf.int32)
|
| 596 |
+
)
|
| 597 |
+
dec_attn_mask = upper_mask + lower_mask
|
| 598 |
+
else:
|
| 599 |
+
dec_attn_mask = upper_mask
|
| 600 |
+
|
| 601 |
+
hids = []
|
| 602 |
+
attentions = [] if output_attentions else None
|
| 603 |
+
if self.attn_type == 0: # default
|
| 604 |
+
pos_seq = tf.range(klen - 1, -1, -1.0)
|
| 605 |
+
if self.clamp_len > 0:
|
| 606 |
+
pos_seq = tf.minimum(pos_seq, self.clamp_len)
|
| 607 |
+
pos_emb = self.pos_emb(pos_seq)
|
| 608 |
+
|
| 609 |
+
core_out = self.drop(word_emb, training=training)
|
| 610 |
+
pos_emb = self.drop(pos_emb, training=training)
|
| 611 |
+
|
| 612 |
+
for i, layer in enumerate(self.layers):
|
| 613 |
+
hids.append(core_out)
|
| 614 |
+
mems_i = None if mems is None else mems[i]
|
| 615 |
+
layer_outputs = layer(
|
| 616 |
+
core_out,
|
| 617 |
+
pos_emb,
|
| 618 |
+
dec_attn_mask,
|
| 619 |
+
mems_i,
|
| 620 |
+
head_mask[i],
|
| 621 |
+
output_attentions,
|
| 622 |
+
training=training,
|
| 623 |
+
)
|
| 624 |
+
core_out = layer_outputs[0]
|
| 625 |
+
if output_attentions:
|
| 626 |
+
attentions.append(layer_outputs[1])
|
| 627 |
+
else: # learnable embeddings and absolute embeddings
|
| 628 |
+
raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
|
| 629 |
+
|
| 630 |
+
core_out = self.drop(core_out, training=training)
|
| 631 |
+
|
| 632 |
+
new_mems = self._update_mems(hids, mems, mlen, qlen)
|
| 633 |
+
|
| 634 |
+
# We transpose back here to shape [bsz, len, hidden_dim]
|
| 635 |
+
core_out = tf.transpose(core_out, perm=(1, 0, 2))
|
| 636 |
+
|
| 637 |
+
if output_hidden_states:
|
| 638 |
+
# Transpose to library standard shape [bsz, len, hidden_dim] and add last layer
|
| 639 |
+
hids = tuple(tf.transpose(t, perm=(1, 0, 2)) for t in hids)
|
| 640 |
+
hids = hids + (core_out,)
|
| 641 |
+
else:
|
| 642 |
+
hids = None
|
| 643 |
+
if output_attentions:
|
| 644 |
+
# Transpose to library standard shape [bsz, n_heads, query_seq_len, key_seq_len]
|
| 645 |
+
attentions = tuple(tf.transpose(t, perm=(2, 3, 0, 1)) for t in attentions)
|
| 646 |
+
|
| 647 |
+
if not return_dict:
|
| 648 |
+
return tuple(v for v in [core_out, new_mems, hids, attentions] if v is not None)
|
| 649 |
+
|
| 650 |
+
return TFTransfoXLModelOutput(
|
| 651 |
+
last_hidden_state=core_out,
|
| 652 |
+
mems=new_mems,
|
| 653 |
+
hidden_states=hids,
|
| 654 |
+
attentions=attentions,
|
| 655 |
+
)
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
class TFTransfoXLPreTrainedModel(TFPreTrainedModel):
|
| 659 |
+
"""
|
| 660 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 661 |
+
models.
|
| 662 |
+
"""
|
| 663 |
+
|
| 664 |
+
config_class = TransfoXLConfig
|
| 665 |
+
base_model_prefix = "transformer"
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
@dataclass
|
| 669 |
+
class TFTransfoXLModelOutput(ModelOutput):
|
| 670 |
+
"""
|
| 671 |
+
Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
|
| 672 |
+
|
| 673 |
+
Args:
|
| 674 |
+
last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 675 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 676 |
+
mems (`List[tf.Tensor]` of length `config.n_layers`):
|
| 677 |
+
Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
|
| 678 |
+
input) to speed up sequential decoding. The token ids which have their past given to this model should not
|
| 679 |
+
be passed as input ids as they have already been computed.
|
| 680 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 681 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 682 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 683 |
+
|
| 684 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 685 |
+
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 686 |
+
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 687 |
+
sequence_length)`.
|
| 688 |
+
|
| 689 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 690 |
+
heads.
|
| 691 |
+
"""
|
| 692 |
+
|
| 693 |
+
last_hidden_state: tf.Tensor = None
|
| 694 |
+
mems: List[tf.Tensor] = None
|
| 695 |
+
hidden_states: Tuple[tf.Tensor] | None = None
|
| 696 |
+
attentions: Tuple[tf.Tensor] | None = None
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
@dataclass
|
| 700 |
+
class TFTransfoXLLMHeadModelOutput(ModelOutput):
|
| 701 |
+
"""
|
| 702 |
+
Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
|
| 703 |
+
|
| 704 |
+
Args:
|
| 705 |
+
losses (`tf.Tensor` of shape *(batch_size, sequence_length-1)*, *optional*, returned when `labels` is provided):
|
| 706 |
+
Language modeling losses (not reduced).
|
| 707 |
+
prediction_scores (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 708 |
+
Prediction scores of the language modeling head (scores for each vocabulary token after SoftMax).
|
| 709 |
+
mems (`List[tf.Tensor]` of length `config.n_layers`):
|
| 710 |
+
Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
|
| 711 |
+
input) to speed up sequential decoding. The token ids which have their past given to this model should not
|
| 712 |
+
be passed as input ids as they have already been computed.
|
| 713 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 714 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 715 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 716 |
+
|
| 717 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 718 |
+
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 719 |
+
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 720 |
+
sequence_length)`.
|
| 721 |
+
|
| 722 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 723 |
+
heads.
|
| 724 |
+
"""
|
| 725 |
+
|
| 726 |
+
prediction_scores: tf.Tensor = None
|
| 727 |
+
mems: List[tf.Tensor] = None
|
| 728 |
+
hidden_states: Tuple[tf.Tensor] | None = None
|
| 729 |
+
attentions: Tuple[tf.Tensor] | None = None
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
@dataclass
|
| 733 |
+
class TFTransfoXLSequenceClassifierOutputWithPast(ModelOutput):
|
| 734 |
+
"""
|
| 735 |
+
Base class for outputs of sentence classification models.
|
| 736 |
+
|
| 737 |
+
Args:
|
| 738 |
+
loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 739 |
+
Classification (or regression if config.num_labels==1) loss.
|
| 740 |
+
logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`):
|
| 741 |
+
Classification (or regression if config.num_labels==1) scores (before SoftMax).
|
| 742 |
+
mems (`List[tf.Tensor]` of length `config.n_layers`):
|
| 743 |
+
Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
|
| 744 |
+
input) to speed up sequential decoding. The token ids which have their past given to this model should not
|
| 745 |
+
be passed as input ids as they have already been computed.
|
| 746 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 747 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 748 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 749 |
+
|
| 750 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 751 |
+
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 752 |
+
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 753 |
+
sequence_length)`.
|
| 754 |
+
|
| 755 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 756 |
+
heads.
|
| 757 |
+
"""
|
| 758 |
+
|
| 759 |
+
loss: tf.Tensor | None = None
|
| 760 |
+
logits: tf.Tensor = None
|
| 761 |
+
mems: List[tf.Tensor] = None
|
| 762 |
+
hidden_states: Tuple[tf.Tensor] | None = None
|
| 763 |
+
attentions: Tuple[tf.Tensor] | None = None
|
| 764 |
+
|
| 765 |
+
|
| 766 |
+
TRANSFO_XL_START_DOCSTRING = r"""
|
| 767 |
+
|
| 768 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 769 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 770 |
+
etc.)
|
| 771 |
+
|
| 772 |
+
This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 773 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 774 |
+
behavior.
|
| 775 |
+
|
| 776 |
+
<Tip>
|
| 777 |
+
|
| 778 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
| 779 |
+
|
| 780 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 781 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
| 782 |
+
|
| 783 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
| 784 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
| 785 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
| 786 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
| 787 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
| 788 |
+
positional argument:
|
| 789 |
+
|
| 790 |
+
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
|
| 791 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
| 792 |
+
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
|
| 793 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
| 794 |
+
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
|
| 795 |
+
|
| 796 |
+
Note that when creating models and layers with
|
| 797 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
| 798 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
| 799 |
+
|
| 800 |
+
</Tip>
|
| 801 |
+
|
| 802 |
+
Parameters:
|
| 803 |
+
config ([`TransfoXLConfig`]): Model configuration class with all the parameters of the model.
|
| 804 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 805 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 806 |
+
"""
|
| 807 |
+
|
| 808 |
+
TRANSFO_XL_INPUTS_DOCSTRING = r"""
|
| 809 |
+
Args:
|
| 810 |
+
input_ids (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`):
|
| 811 |
+
Indices of input sequence tokens in the vocabulary.
|
| 812 |
+
|
| 813 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
|
| 814 |
+
[`PreTrainedTokenizer.encode`] for details.
|
| 815 |
+
|
| 816 |
+
[What are input IDs?](../glossary#input-ids)
|
| 817 |
+
mems (`List[tf.Tensor]` of length `config.n_layers`):
|
| 818 |
+
Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see
|
| 819 |
+
`mems` output below). Can be used to speed up sequential decoding. The token ids which have their mems
|
| 820 |
+
given to this model should not be passed as `input_ids` as they have already been computed.
|
| 821 |
+
head_mask (`tf.Tensor` or `Numpy array` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 822 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 823 |
+
|
| 824 |
+
- 1 indicates the head is **not masked**,
|
| 825 |
+
- 0 indicates the head is **masked**.
|
| 826 |
+
inputs_embeds (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 827 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 828 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 829 |
+
model's internal embedding lookup matrix.
|
| 830 |
+
output_attentions (`bool`, *optional*):
|
| 831 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 832 |
+
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
|
| 833 |
+
config will be used instead.
|
| 834 |
+
output_hidden_states (`bool`, *optional*):
|
| 835 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 836 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 837 |
+
used instead.
|
| 838 |
+
return_dict (`bool`, *optional*):
|
| 839 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 840 |
+
eager mode, in graph mode the value will always be set to True.
|
| 841 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 842 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 843 |
+
behaviors between training and evaluation).
|
| 844 |
+
"""
|
| 845 |
+
|
| 846 |
+
|
| 847 |
+
@add_start_docstrings(
|
| 848 |
+
"The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
|
| 849 |
+
TRANSFO_XL_START_DOCSTRING,
|
| 850 |
+
)
|
| 851 |
+
class TFTransfoXLModel(TFTransfoXLPreTrainedModel):
|
| 852 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 853 |
+
super().__init__(config, *inputs, **kwargs)
|
| 854 |
+
self.transformer = TFTransfoXLMainLayer(config, name="transformer")
|
| 855 |
+
|
| 856 |
+
@unpack_inputs
|
| 857 |
+
@add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
|
| 858 |
+
@add_code_sample_docstrings(
|
| 859 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 860 |
+
output_type=TFTransfoXLModelOutput,
|
| 861 |
+
config_class=_CONFIG_FOR_DOC,
|
| 862 |
+
)
|
| 863 |
+
def call(
|
| 864 |
+
self,
|
| 865 |
+
input_ids: TFModelInputType | None = None,
|
| 866 |
+
mems: List[tf.Tensor] | None = None,
|
| 867 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 868 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 869 |
+
output_attentions: bool | None = None,
|
| 870 |
+
output_hidden_states: bool | None = None,
|
| 871 |
+
return_dict: bool | None = None,
|
| 872 |
+
training: bool = False,
|
| 873 |
+
) -> TFTransfoXLModelOutput | Tuple[tf.Tensor]:
|
| 874 |
+
outputs = self.transformer(
|
| 875 |
+
input_ids=input_ids,
|
| 876 |
+
mems=mems,
|
| 877 |
+
head_mask=head_mask,
|
| 878 |
+
inputs_embeds=inputs_embeds,
|
| 879 |
+
output_attentions=output_attentions,
|
| 880 |
+
output_hidden_states=output_hidden_states,
|
| 881 |
+
return_dict=return_dict,
|
| 882 |
+
training=training,
|
| 883 |
+
)
|
| 884 |
+
|
| 885 |
+
return outputs
|
| 886 |
+
|
| 887 |
+
|
| 888 |
+
@add_start_docstrings(
|
| 889 |
+
"""
|
| 890 |
+
The Transformer-XL Model with a language modeling head on top (adaptive softmax with weights tied to the adaptive
|
| 891 |
+
input embeddings)
|
| 892 |
+
""",
|
| 893 |
+
TRANSFO_XL_START_DOCSTRING,
|
| 894 |
+
)
|
| 895 |
+
class TFTransfoXLLMHeadModel(TFTransfoXLPreTrainedModel):
|
| 896 |
+
def __init__(self, config):
|
| 897 |
+
super().__init__(config)
|
| 898 |
+
self.transformer = TFTransfoXLMainLayer(config, name="transformer")
|
| 899 |
+
self.sample_softmax = config.sample_softmax
|
| 900 |
+
assert self.sample_softmax <= 0, (
|
| 901 |
+
"Sampling from the softmax is not implemented yet. Please look at issue: #3310:"
|
| 902 |
+
" https://github.com/huggingface/transformers/issues/3310"
|
| 903 |
+
)
|
| 904 |
+
|
| 905 |
+
self.crit = TFAdaptiveSoftmaxMask(
|
| 906 |
+
config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val, name="crit"
|
| 907 |
+
)
|
| 908 |
+
|
| 909 |
+
def _resize_token_embeddings(self, new_num_tokens):
|
| 910 |
+
raise NotImplementedError()
|
| 911 |
+
|
| 912 |
+
def get_output_embeddings(self):
|
| 913 |
+
"""Double-check if you are using adaptive softmax."""
|
| 914 |
+
if len(self.crit.out_layers) > 0:
|
| 915 |
+
return self.crit.out_layers[-1]
|
| 916 |
+
return None
|
| 917 |
+
|
| 918 |
+
def reset_memory_length(self, mem_len):
|
| 919 |
+
self.transformer.reset_memory_length(mem_len)
|
| 920 |
+
|
| 921 |
+
def init_mems(self, bsz):
|
| 922 |
+
return self.transformer.init_mems(bsz)
|
| 923 |
+
|
| 924 |
+
@unpack_inputs
|
| 925 |
+
@add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
|
| 926 |
+
@add_code_sample_docstrings(
|
| 927 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 928 |
+
output_type=TFTransfoXLLMHeadModelOutput,
|
| 929 |
+
config_class=_CONFIG_FOR_DOC,
|
| 930 |
+
)
|
| 931 |
+
def call(
|
| 932 |
+
self,
|
| 933 |
+
input_ids: TFModelInputType | None = None,
|
| 934 |
+
mems: List[tf.Tensor] | None = None,
|
| 935 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 936 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 937 |
+
output_attentions: bool | None = None,
|
| 938 |
+
output_hidden_states: bool | None = None,
|
| 939 |
+
return_dict: bool | None = None,
|
| 940 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 941 |
+
training: bool = False,
|
| 942 |
+
) -> TFTransfoXLLMHeadModelOutput | Tuple[tf.Tensor]:
|
| 943 |
+
if input_ids is not None:
|
| 944 |
+
bsz, tgt_len = shape_list(input_ids)[:2]
|
| 945 |
+
else:
|
| 946 |
+
bsz, tgt_len = shape_list(inputs_embeds)[:2]
|
| 947 |
+
|
| 948 |
+
transformer_outputs = self.transformer(
|
| 949 |
+
input_ids,
|
| 950 |
+
mems,
|
| 951 |
+
head_mask,
|
| 952 |
+
inputs_embeds,
|
| 953 |
+
output_attentions,
|
| 954 |
+
output_hidden_states,
|
| 955 |
+
return_dict,
|
| 956 |
+
training=training,
|
| 957 |
+
)
|
| 958 |
+
|
| 959 |
+
last_hidden = transformer_outputs[0]
|
| 960 |
+
pred_hid = last_hidden[:, -tgt_len:]
|
| 961 |
+
|
| 962 |
+
softmax_output = self.crit(pred_hid, labels, training=training)
|
| 963 |
+
prediction_scores = softmax_output if labels is None else ()
|
| 964 |
+
|
| 965 |
+
if not return_dict:
|
| 966 |
+
return (prediction_scores,) + transformer_outputs[1:]
|
| 967 |
+
|
| 968 |
+
return TFTransfoXLLMHeadModelOutput(
|
| 969 |
+
prediction_scores=prediction_scores,
|
| 970 |
+
mems=transformer_outputs.mems,
|
| 971 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 972 |
+
attentions=transformer_outputs.attentions,
|
| 973 |
+
)
|
| 974 |
+
|
| 975 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **model_kwargs):
|
| 976 |
+
inputs = {}
|
| 977 |
+
|
| 978 |
+
# if past is defined in model kwargs then use it for faster decoding
|
| 979 |
+
if past_key_values:
|
| 980 |
+
input_ids = tf.expand_dims(input_ids[:, -1], axis=-1)
|
| 981 |
+
else:
|
| 982 |
+
input_ids = input_ids
|
| 983 |
+
|
| 984 |
+
return inputs
|
| 985 |
+
|
| 986 |
+
# Adapted from the torch tie_weights function
|
| 987 |
+
def tf_to_pt_weight_rename(self, tf_weight):
|
| 988 |
+
if self.config.tie_word_embeddings and "crit.out_layers" in tf_weight:
|
| 989 |
+
return tf_weight, tf_weight.replace("crit.out_layers", "transformer.word_emb.emb_layers")
|
| 990 |
+
elif self.config.tie_projs and "crit.out_projs" in tf_weight:
|
| 991 |
+
for i, tie_proj in enumerate(self.config.tie_projs):
|
| 992 |
+
if tie_proj and self.config.div_val == 1 and self.config.d_model != self.config.d_embed:
|
| 993 |
+
# self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[0]
|
| 994 |
+
return tf_weight, tf_weight.replace(f"crit.out_projs.{i}", "transformer.word_emb.emb_projs.0")
|
| 995 |
+
elif tie_proj and self.config.div_val != 1:
|
| 996 |
+
# self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[i]
|
| 997 |
+
return tf_weight, tf_weight.replace("crit.out_projs", "transformer.word_emb.emb_projs")
|
| 998 |
+
else:
|
| 999 |
+
return (tf_weight,)
|
| 1000 |
+
|
| 1001 |
+
|
| 1002 |
+
@add_start_docstrings(
|
| 1003 |
+
"""
|
| 1004 |
+
The Transfo XL Model transformer with a sequence classification head on top (linear layer).
|
| 1005 |
+
|
| 1006 |
+
[`TFTransfoXLForSequenceClassification`] uses the last token in order to do the classification, as other causal
|
| 1007 |
+
models (e.g. GPT-1,GPT-2) do.
|
| 1008 |
+
|
| 1009 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
| 1010 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
| 1011 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
| 1012 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
| 1013 |
+
each row of the batch).
|
| 1014 |
+
""",
|
| 1015 |
+
TRANSFO_XL_START_DOCSTRING,
|
| 1016 |
+
)
|
| 1017 |
+
class TFTransfoXLForSequenceClassification(TFTransfoXLPreTrainedModel, TFSequenceClassificationLoss):
|
| 1018 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 1019 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1020 |
+
self.num_labels = config.num_labels
|
| 1021 |
+
self.score = keras.layers.Dense(
|
| 1022 |
+
config.num_labels,
|
| 1023 |
+
kernel_initializer=get_initializer(config.init_range),
|
| 1024 |
+
name="score",
|
| 1025 |
+
use_bias=False,
|
| 1026 |
+
)
|
| 1027 |
+
self.transformer = TFTransfoXLMainLayer(config, name="transformer")
|
| 1028 |
+
|
| 1029 |
+
def get_output_embeddings(self):
|
| 1030 |
+
# Remove after transformers v4.32. Fix this model's `test_model_common_attributes` test too.
|
| 1031 |
+
logger.warning(
|
| 1032 |
+
"Sequence classification models do not have output embeddings. `.get_output_embeddings` will be removed "
|
| 1033 |
+
"in transformers v4.32."
|
| 1034 |
+
)
|
| 1035 |
+
return self.transformer.word_emb
|
| 1036 |
+
|
| 1037 |
+
@unpack_inputs
|
| 1038 |
+
@add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
|
| 1039 |
+
@add_code_sample_docstrings(
|
| 1040 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1041 |
+
output_type=TFTransfoXLSequenceClassifierOutputWithPast,
|
| 1042 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1043 |
+
)
|
| 1044 |
+
def call(
|
| 1045 |
+
self,
|
| 1046 |
+
input_ids: TFModelInputType | None = None,
|
| 1047 |
+
mems: List[tf.Tensor] | None = None,
|
| 1048 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1049 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1050 |
+
output_attentions: Optional[bool] = None,
|
| 1051 |
+
output_hidden_states: Optional[bool] = None,
|
| 1052 |
+
return_dict: Optional[bool] = None,
|
| 1053 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1054 |
+
training: Optional[bool] = False,
|
| 1055 |
+
) -> Union[Tuple, TFTransfoXLSequenceClassifierOutputWithPast]:
|
| 1056 |
+
r"""
|
| 1057 |
+
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1058 |
+
Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
|
| 1059 |
+
config.vocab_size - 1]`.
|
| 1060 |
+
"""
|
| 1061 |
+
transformer_outputs = self.transformer(
|
| 1062 |
+
input_ids=input_ids,
|
| 1063 |
+
mems=mems,
|
| 1064 |
+
head_mask=head_mask,
|
| 1065 |
+
inputs_embeds=inputs_embeds,
|
| 1066 |
+
output_attentions=output_attentions,
|
| 1067 |
+
output_hidden_states=output_hidden_states,
|
| 1068 |
+
return_dict=return_dict,
|
| 1069 |
+
training=training,
|
| 1070 |
+
)
|
| 1071 |
+
|
| 1072 |
+
hidden_states = transformer_outputs[0]
|
| 1073 |
+
logits = self.score(hidden_states)
|
| 1074 |
+
in_logits = None
|
| 1075 |
+
if self.config.pad_token_id is None:
|
| 1076 |
+
sequence_lengths = -1
|
| 1077 |
+
else:
|
| 1078 |
+
if input_ids is not None:
|
| 1079 |
+
sequence_lengths = (
|
| 1080 |
+
tf.argmax(tf.cast(tf.math.equal(input_ids, self.config.pad_token_id), input_ids.dtype), axis=-1)
|
| 1081 |
+
- 1
|
| 1082 |
+
)
|
| 1083 |
+
sequence_lengths = tf.where(sequence_lengths >= 0, sequence_lengths, input_ids.shape[-1] - 1)
|
| 1084 |
+
in_logits = tf.gather(logits, sequence_lengths, batch_dims=1, axis=1)
|
| 1085 |
+
else:
|
| 1086 |
+
sequence_lengths = -1
|
| 1087 |
+
logger.warning_once(
|
| 1088 |
+
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
|
| 1089 |
+
"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
|
| 1090 |
+
)
|
| 1091 |
+
loss = None
|
| 1092 |
+
|
| 1093 |
+
if labels is not None:
|
| 1094 |
+
if input_ids is not None:
|
| 1095 |
+
batch_size, sequence_length = shape_list(input_ids)[:2]
|
| 1096 |
+
else:
|
| 1097 |
+
batch_size, sequence_length = shape_list(inputs_embeds)[:2]
|
| 1098 |
+
assert (
|
| 1099 |
+
self.config.pad_token_id is not None or batch_size == 1
|
| 1100 |
+
), "Cannot handle batch sizes > 1 if no padding token is defined."
|
| 1101 |
+
|
| 1102 |
+
if not tf.is_tensor(sequence_lengths):
|
| 1103 |
+
in_logits = logits[0:batch_size, sequence_lengths]
|
| 1104 |
+
|
| 1105 |
+
loss = self.hf_compute_loss(tf.reshape(labels, [-1, 1]), tf.reshape(in_logits, [-1, self.num_labels]))
|
| 1106 |
+
|
| 1107 |
+
pooled_logits = in_logits if in_logits is not None else logits
|
| 1108 |
+
|
| 1109 |
+
if not return_dict:
|
| 1110 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
| 1111 |
+
return ((loss,) + output) if loss is not None else output
|
| 1112 |
+
|
| 1113 |
+
return TFTransfoXLSequenceClassifierOutputWithPast(
|
| 1114 |
+
loss=loss,
|
| 1115 |
+
logits=pooled_logits,
|
| 1116 |
+
mems=transformer_outputs.mems,
|
| 1117 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1118 |
+
attentions=transformer_outputs.attentions,
|
| 1119 |
+
)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl_utilities.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""
|
| 17 |
+
A TF 2.0 Adaptive Softmax for Transformer XL model.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import tensorflow as tf
|
| 21 |
+
|
| 22 |
+
from ....modeling_tf_utils import keras
|
| 23 |
+
from ....tf_utils import shape_list
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class TFAdaptiveSoftmaxMask(keras.layers.Layer):
|
| 27 |
+
def __init__(self, vocab_size, d_embed, d_proj, cutoffs, div_val=1, keep_order=False, **kwargs):
|
| 28 |
+
super().__init__(**kwargs)
|
| 29 |
+
|
| 30 |
+
self.vocab_size = vocab_size
|
| 31 |
+
self.d_embed = d_embed
|
| 32 |
+
self.d_proj = d_proj
|
| 33 |
+
|
| 34 |
+
self.cutoffs = cutoffs + [vocab_size]
|
| 35 |
+
self.cutoff_ends = [0] + self.cutoffs
|
| 36 |
+
self.div_val = div_val
|
| 37 |
+
|
| 38 |
+
self.shortlist_size = self.cutoffs[0]
|
| 39 |
+
self.n_clusters = len(self.cutoffs) - 1
|
| 40 |
+
self.head_size = self.shortlist_size + self.n_clusters
|
| 41 |
+
self.keep_order = keep_order
|
| 42 |
+
|
| 43 |
+
self.out_layers = []
|
| 44 |
+
self.out_projs = []
|
| 45 |
+
|
| 46 |
+
def build(self, input_shape):
|
| 47 |
+
if self.n_clusters > 0:
|
| 48 |
+
self.cluster_weight = self.add_weight(
|
| 49 |
+
shape=(self.n_clusters, self.d_embed), initializer="zeros", trainable=True, name="cluster_weight"
|
| 50 |
+
)
|
| 51 |
+
self.cluster_bias = self.add_weight(
|
| 52 |
+
shape=(self.n_clusters,), initializer="zeros", trainable=True, name="cluster_bias"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
if self.div_val == 1:
|
| 56 |
+
for i in range(len(self.cutoffs)):
|
| 57 |
+
if self.d_proj != self.d_embed:
|
| 58 |
+
weight = self.add_weight(
|
| 59 |
+
shape=(self.d_embed, self.d_proj),
|
| 60 |
+
initializer="zeros",
|
| 61 |
+
trainable=True,
|
| 62 |
+
name=f"out_projs_._{i}",
|
| 63 |
+
)
|
| 64 |
+
self.out_projs.append(weight)
|
| 65 |
+
else:
|
| 66 |
+
self.out_projs.append(None)
|
| 67 |
+
weight = self.add_weight(
|
| 68 |
+
shape=(self.vocab_size, self.d_embed),
|
| 69 |
+
initializer="zeros",
|
| 70 |
+
trainable=True,
|
| 71 |
+
name=f"out_layers_._{i}_._weight",
|
| 72 |
+
)
|
| 73 |
+
bias = self.add_weight(
|
| 74 |
+
shape=(self.vocab_size,),
|
| 75 |
+
initializer="zeros",
|
| 76 |
+
trainable=True,
|
| 77 |
+
name=f"out_layers_._{i}_._bias",
|
| 78 |
+
)
|
| 79 |
+
self.out_layers.append((weight, bias))
|
| 80 |
+
else:
|
| 81 |
+
for i in range(len(self.cutoffs)):
|
| 82 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 83 |
+
d_emb_i = self.d_embed // (self.div_val**i)
|
| 84 |
+
|
| 85 |
+
weight = self.add_weight(
|
| 86 |
+
shape=(d_emb_i, self.d_proj), initializer="zeros", trainable=True, name=f"out_projs_._{i}"
|
| 87 |
+
)
|
| 88 |
+
self.out_projs.append(weight)
|
| 89 |
+
weight = self.add_weight(
|
| 90 |
+
shape=(r_idx - l_idx, d_emb_i),
|
| 91 |
+
initializer="zeros",
|
| 92 |
+
trainable=True,
|
| 93 |
+
name=f"out_layers_._{i}_._weight",
|
| 94 |
+
)
|
| 95 |
+
bias = self.add_weight(
|
| 96 |
+
shape=(r_idx - l_idx,),
|
| 97 |
+
initializer="zeros",
|
| 98 |
+
trainable=True,
|
| 99 |
+
name=f"out_layers_._{i}_._bias",
|
| 100 |
+
)
|
| 101 |
+
self.out_layers.append((weight, bias))
|
| 102 |
+
super().build(input_shape)
|
| 103 |
+
|
| 104 |
+
@staticmethod
|
| 105 |
+
def _logit(x, W, b, proj=None):
|
| 106 |
+
y = x
|
| 107 |
+
if proj is not None:
|
| 108 |
+
y = tf.einsum("ibd,ed->ibe", y, proj)
|
| 109 |
+
return tf.einsum("ibd,nd->ibn", y, W) + b
|
| 110 |
+
|
| 111 |
+
@staticmethod
|
| 112 |
+
def _gather_logprob(logprob, target):
|
| 113 |
+
lp_size = shape_list(logprob)
|
| 114 |
+
r = tf.range(lp_size[0], dtype=target.dtype)
|
| 115 |
+
idx = tf.stack([r, target], 1)
|
| 116 |
+
return tf.gather_nd(logprob, idx)
|
| 117 |
+
|
| 118 |
+
def call(self, hidden, target, return_mean=True, training=False):
|
| 119 |
+
head_logprob = 0
|
| 120 |
+
if self.n_clusters == 0:
|
| 121 |
+
output = self._logit(hidden, self.out_layers[0][0], self.out_layers[0][1], self.out_projs[0])
|
| 122 |
+
if target is not None:
|
| 123 |
+
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=target, logits=output)
|
| 124 |
+
out = tf.nn.log_softmax(output, axis=-1)
|
| 125 |
+
else:
|
| 126 |
+
hidden_sizes = shape_list(hidden)
|
| 127 |
+
out = []
|
| 128 |
+
loss = tf.zeros(hidden_sizes[:2])
|
| 129 |
+
for i in range(len(self.cutoffs)):
|
| 130 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 131 |
+
if target is not None:
|
| 132 |
+
mask = (target >= l_idx) & (target < r_idx)
|
| 133 |
+
mask_idx = tf.where(mask)
|
| 134 |
+
cur_target = tf.boolean_mask(target, mask) - l_idx
|
| 135 |
+
|
| 136 |
+
if self.div_val == 1:
|
| 137 |
+
cur_W = self.out_layers[0][0][l_idx:r_idx]
|
| 138 |
+
cur_b = self.out_layers[0][1][l_idx:r_idx]
|
| 139 |
+
else:
|
| 140 |
+
cur_W = self.out_layers[i][0]
|
| 141 |
+
cur_b = self.out_layers[i][1]
|
| 142 |
+
|
| 143 |
+
if i == 0:
|
| 144 |
+
cur_W = tf.concat([cur_W, self.cluster_weight], 0)
|
| 145 |
+
cur_b = tf.concat([cur_b, self.cluster_bias], 0)
|
| 146 |
+
|
| 147 |
+
head_logit = self._logit(hidden, cur_W, cur_b, self.out_projs[0])
|
| 148 |
+
head_logprob = tf.nn.log_softmax(head_logit)
|
| 149 |
+
out.append(head_logprob[..., : self.cutoffs[0]])
|
| 150 |
+
if target is not None:
|
| 151 |
+
cur_head_logprob = tf.boolean_mask(head_logprob, mask)
|
| 152 |
+
cur_logprob = self._gather_logprob(cur_head_logprob, cur_target)
|
| 153 |
+
else:
|
| 154 |
+
tail_logit = self._logit(hidden, cur_W, cur_b, self.out_projs[i])
|
| 155 |
+
tail_logprob = tf.nn.log_softmax(tail_logit)
|
| 156 |
+
cluster_prob_idx = self.cutoffs[0] + i - 1 # No probability for the head cluster
|
| 157 |
+
logprob_i = head_logprob[..., cluster_prob_idx, None] + tail_logprob
|
| 158 |
+
out.append(logprob_i)
|
| 159 |
+
if target is not None:
|
| 160 |
+
cur_head_logprob = tf.boolean_mask(head_logprob, mask)
|
| 161 |
+
cur_tail_logprob = tf.boolean_mask(tail_logprob, mask)
|
| 162 |
+
cur_logprob = self._gather_logprob(cur_tail_logprob, cur_target)
|
| 163 |
+
cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1]
|
| 164 |
+
if target is not None:
|
| 165 |
+
loss += tf.scatter_nd(mask_idx, -cur_logprob, shape_list(loss))
|
| 166 |
+
out = tf.concat(out, axis=-1)
|
| 167 |
+
|
| 168 |
+
if target is not None:
|
| 169 |
+
if return_mean:
|
| 170 |
+
loss = tf.reduce_mean(loss)
|
| 171 |
+
# Add the training-time loss value to the layer using `self.add_loss()`.
|
| 172 |
+
self.add_loss(loss)
|
| 173 |
+
|
| 174 |
+
# Log the loss as a metric (we could log arbitrary metrics,
|
| 175 |
+
# including different metrics for training and inference.
|
| 176 |
+
self.add_metric(loss, name=self.name, aggregation="mean" if return_mean else "")
|
| 177 |
+
|
| 178 |
+
return out
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/transfo_xl/modeling_transfo_xl.py
ADDED
|
@@ -0,0 +1,1293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""
|
| 17 |
+
PyTorch Transformer XL model. Adapted from https://github.com/kimiyoung/transformer-xl. In particular
|
| 18 |
+
https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/mem_transformer.py
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import warnings
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from typing import List, Optional, Tuple, Union
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
from torch import nn
|
| 27 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 28 |
+
|
| 29 |
+
from ....modeling_utils import PreTrainedModel
|
| 30 |
+
from ....utils import (
|
| 31 |
+
ModelOutput,
|
| 32 |
+
add_code_sample_docstrings,
|
| 33 |
+
add_start_docstrings,
|
| 34 |
+
add_start_docstrings_to_model_forward,
|
| 35 |
+
logging,
|
| 36 |
+
)
|
| 37 |
+
from .configuration_transfo_xl import TransfoXLConfig
|
| 38 |
+
from .modeling_transfo_xl_utilities import ProjectedAdaptiveLogSoftmax
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
logger = logging.get_logger(__name__)
|
| 42 |
+
|
| 43 |
+
_CHECKPOINT_FOR_DOC = "transfo-xl/transfo-xl-wt103"
|
| 44 |
+
_CONFIG_FOR_DOC = "TransfoXLConfig"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def build_tf_to_pytorch_map(model, config):
|
| 48 |
+
"""
|
| 49 |
+
A map of modules from TF to PyTorch. This time I use a map to keep the PyTorch model as identical to the original
|
| 50 |
+
PyTorch model as possible.
|
| 51 |
+
"""
|
| 52 |
+
tf_to_pt_map = {}
|
| 53 |
+
|
| 54 |
+
if hasattr(model, "transformer"):
|
| 55 |
+
# We are loading in a TransfoXLLMHeadModel => we will load also the Adaptive Softmax
|
| 56 |
+
tf_to_pt_map.update(
|
| 57 |
+
{
|
| 58 |
+
"transformer/adaptive_softmax/cutoff_0/cluster_W": model.crit.cluster_weight,
|
| 59 |
+
"transformer/adaptive_softmax/cutoff_0/cluster_b": model.crit.cluster_bias,
|
| 60 |
+
}
|
| 61 |
+
)
|
| 62 |
+
for i, (out_l, proj_l, tie_proj) in enumerate(
|
| 63 |
+
zip(model.crit.out_layers, model.crit.out_projs, config.tie_projs)
|
| 64 |
+
):
|
| 65 |
+
layer_str = f"transformer/adaptive_softmax/cutoff_{i}/"
|
| 66 |
+
if config.tie_word_embeddings:
|
| 67 |
+
tf_to_pt_map.update({layer_str + "b": out_l.bias})
|
| 68 |
+
else:
|
| 69 |
+
raise NotImplementedError
|
| 70 |
+
# I don't think this is implemented in the TF code
|
| 71 |
+
tf_to_pt_map.update({layer_str + "lookup_table": out_l.weight, layer_str + "b": out_l.bias})
|
| 72 |
+
if not tie_proj:
|
| 73 |
+
tf_to_pt_map.update({layer_str + "proj": proj_l})
|
| 74 |
+
# Now load the rest of the transformer
|
| 75 |
+
model = model.transformer
|
| 76 |
+
|
| 77 |
+
# Embeddings
|
| 78 |
+
for i, (embed_l, proj_l) in enumerate(zip(model.word_emb.emb_layers, model.word_emb.emb_projs)):
|
| 79 |
+
layer_str = f"transformer/adaptive_embed/cutoff_{i}/"
|
| 80 |
+
tf_to_pt_map.update({layer_str + "lookup_table": embed_l.weight, layer_str + "proj_W": proj_l})
|
| 81 |
+
|
| 82 |
+
# Transformer blocks
|
| 83 |
+
for i, b in enumerate(model.layers):
|
| 84 |
+
layer_str = f"transformer/layer_{i}/"
|
| 85 |
+
tf_to_pt_map.update(
|
| 86 |
+
{
|
| 87 |
+
layer_str + "rel_attn/LayerNorm/gamma": b.dec_attn.layer_norm.weight,
|
| 88 |
+
layer_str + "rel_attn/LayerNorm/beta": b.dec_attn.layer_norm.bias,
|
| 89 |
+
layer_str + "rel_attn/o/kernel": b.dec_attn.o_net.weight,
|
| 90 |
+
layer_str + "rel_attn/qkv/kernel": b.dec_attn.qkv_net.weight,
|
| 91 |
+
layer_str + "rel_attn/r/kernel": b.dec_attn.r_net.weight,
|
| 92 |
+
layer_str + "ff/LayerNorm/gamma": b.pos_ff.layer_norm.weight,
|
| 93 |
+
layer_str + "ff/LayerNorm/beta": b.pos_ff.layer_norm.bias,
|
| 94 |
+
layer_str + "ff/layer_1/kernel": b.pos_ff.CoreNet[0].weight,
|
| 95 |
+
layer_str + "ff/layer_1/bias": b.pos_ff.CoreNet[0].bias,
|
| 96 |
+
layer_str + "ff/layer_2/kernel": b.pos_ff.CoreNet[3].weight,
|
| 97 |
+
layer_str + "ff/layer_2/bias": b.pos_ff.CoreNet[3].bias,
|
| 98 |
+
}
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
# Relative positioning biases
|
| 102 |
+
if config.untie_r:
|
| 103 |
+
r_r_list = []
|
| 104 |
+
r_w_list = []
|
| 105 |
+
for b in model.layers:
|
| 106 |
+
r_r_list.append(b.dec_attn.r_r_bias)
|
| 107 |
+
r_w_list.append(b.dec_attn.r_w_bias)
|
| 108 |
+
else:
|
| 109 |
+
r_r_list = [model.r_r_bias]
|
| 110 |
+
r_w_list = [model.r_w_bias]
|
| 111 |
+
tf_to_pt_map.update({"transformer/r_r_bias": r_r_list, "transformer/r_w_bias": r_w_list})
|
| 112 |
+
return tf_to_pt_map
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def load_tf_weights_in_transfo_xl(model, config, tf_path):
|
| 116 |
+
"""Load tf checkpoints in a pytorch model"""
|
| 117 |
+
try:
|
| 118 |
+
import numpy as np
|
| 119 |
+
import tensorflow as tf
|
| 120 |
+
except ImportError:
|
| 121 |
+
logger.error(
|
| 122 |
+
"Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see "
|
| 123 |
+
"https://www.tensorflow.org/install/ for installation instructions."
|
| 124 |
+
)
|
| 125 |
+
raise
|
| 126 |
+
# Build TF to PyTorch weights loading map
|
| 127 |
+
tf_to_pt_map = build_tf_to_pytorch_map(model, config)
|
| 128 |
+
|
| 129 |
+
# Load weights from TF model
|
| 130 |
+
init_vars = tf.train.list_variables(tf_path)
|
| 131 |
+
tf_weights = {}
|
| 132 |
+
for name, shape in init_vars:
|
| 133 |
+
logger.info(f"Loading TF weight {name} with shape {shape}")
|
| 134 |
+
array = tf.train.load_variable(tf_path, name)
|
| 135 |
+
tf_weights[name] = array
|
| 136 |
+
|
| 137 |
+
for name, pointer in tf_to_pt_map.items():
|
| 138 |
+
assert name in tf_weights
|
| 139 |
+
array = tf_weights[name]
|
| 140 |
+
# adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
|
| 141 |
+
# which are not required for using pretrained model
|
| 142 |
+
if "kernel" in name or "proj" in name:
|
| 143 |
+
array = np.transpose(array)
|
| 144 |
+
if ("r_r_bias" in name or "r_w_bias" in name) and len(pointer) > 1:
|
| 145 |
+
# Here we will split the TF weights
|
| 146 |
+
assert len(pointer) == array.shape[0]
|
| 147 |
+
for i, p_i in enumerate(pointer):
|
| 148 |
+
arr_i = array[i, ...]
|
| 149 |
+
try:
|
| 150 |
+
assert p_i.shape == arr_i.shape
|
| 151 |
+
except AssertionError as e:
|
| 152 |
+
e.args += (p_i.shape, arr_i.shape)
|
| 153 |
+
raise
|
| 154 |
+
logger.info(f"Initialize PyTorch weight {name} for layer {i}")
|
| 155 |
+
p_i.data = torch.from_numpy(arr_i)
|
| 156 |
+
else:
|
| 157 |
+
try:
|
| 158 |
+
assert (
|
| 159 |
+
pointer.shape == array.shape
|
| 160 |
+
), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
|
| 161 |
+
except AssertionError as e:
|
| 162 |
+
e.args += (pointer.shape, array.shape)
|
| 163 |
+
raise
|
| 164 |
+
logger.info(f"Initialize PyTorch weight {name}")
|
| 165 |
+
pointer.data = torch.from_numpy(array)
|
| 166 |
+
tf_weights.pop(name, None)
|
| 167 |
+
tf_weights.pop(name + "/Adam", None)
|
| 168 |
+
tf_weights.pop(name + "/Adam_1", None)
|
| 169 |
+
|
| 170 |
+
logger.info(f"Weights not copied to PyTorch model: {', '.join(tf_weights.keys())}")
|
| 171 |
+
return model
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class PositionalEmbedding(nn.Module):
|
| 175 |
+
def __init__(self, demb):
|
| 176 |
+
super().__init__()
|
| 177 |
+
|
| 178 |
+
self.demb = demb
|
| 179 |
+
|
| 180 |
+
inv_freq = 1 / (10000 ** (torch.arange(0.0, demb, 2.0) / demb))
|
| 181 |
+
self.register_buffer("inv_freq", inv_freq)
|
| 182 |
+
|
| 183 |
+
def forward(self, pos_seq, bsz=None):
|
| 184 |
+
sinusoid_inp = torch.outer(pos_seq, self.inv_freq)
|
| 185 |
+
pos_emb = torch.cat([sinusoid_inp.sin(), sinusoid_inp.cos()], dim=-1)
|
| 186 |
+
|
| 187 |
+
if bsz is not None:
|
| 188 |
+
return pos_emb[:, None, :].expand(-1, bsz, -1)
|
| 189 |
+
else:
|
| 190 |
+
return pos_emb[:, None, :]
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class PositionwiseFF(nn.Module):
|
| 194 |
+
def __init__(self, d_model, d_inner, dropout, pre_lnorm=False, layer_norm_epsilon=1e-5):
|
| 195 |
+
super().__init__()
|
| 196 |
+
|
| 197 |
+
self.d_model = d_model
|
| 198 |
+
self.d_inner = d_inner
|
| 199 |
+
self.dropout = dropout
|
| 200 |
+
|
| 201 |
+
self.CoreNet = nn.Sequential(
|
| 202 |
+
nn.Linear(d_model, d_inner),
|
| 203 |
+
nn.ReLU(inplace=True),
|
| 204 |
+
nn.Dropout(dropout),
|
| 205 |
+
nn.Linear(d_inner, d_model),
|
| 206 |
+
nn.Dropout(dropout),
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
self.layer_norm = nn.LayerNorm(d_model, eps=layer_norm_epsilon)
|
| 210 |
+
|
| 211 |
+
self.pre_lnorm = pre_lnorm
|
| 212 |
+
|
| 213 |
+
def forward(self, inp):
|
| 214 |
+
if self.pre_lnorm:
|
| 215 |
+
# layer normalization + positionwise feed-forward
|
| 216 |
+
core_out = self.CoreNet(self.layer_norm(inp))
|
| 217 |
+
|
| 218 |
+
# residual connection
|
| 219 |
+
output = core_out + inp
|
| 220 |
+
else:
|
| 221 |
+
# positionwise feed-forward
|
| 222 |
+
core_out = self.CoreNet(inp)
|
| 223 |
+
|
| 224 |
+
# residual connection + layer normalization
|
| 225 |
+
output = self.layer_norm(inp + core_out)
|
| 226 |
+
|
| 227 |
+
return output
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class RelPartialLearnableMultiHeadAttn(nn.Module):
|
| 231 |
+
def __init__(
|
| 232 |
+
self,
|
| 233 |
+
n_head,
|
| 234 |
+
d_model,
|
| 235 |
+
d_head,
|
| 236 |
+
dropout,
|
| 237 |
+
dropatt=0,
|
| 238 |
+
pre_lnorm=False,
|
| 239 |
+
r_r_bias=None,
|
| 240 |
+
r_w_bias=None,
|
| 241 |
+
layer_norm_epsilon=1e-5,
|
| 242 |
+
):
|
| 243 |
+
super().__init__()
|
| 244 |
+
|
| 245 |
+
self.n_head = n_head
|
| 246 |
+
self.d_model = d_model
|
| 247 |
+
self.d_head = d_head
|
| 248 |
+
self.dropout = dropout
|
| 249 |
+
|
| 250 |
+
self.qkv_net = nn.Linear(d_model, 3 * n_head * d_head, bias=False)
|
| 251 |
+
|
| 252 |
+
self.drop = nn.Dropout(dropout)
|
| 253 |
+
self.dropatt = nn.Dropout(dropatt)
|
| 254 |
+
self.o_net = nn.Linear(n_head * d_head, d_model, bias=False)
|
| 255 |
+
|
| 256 |
+
self.layer_norm = nn.LayerNorm(d_model, eps=layer_norm_epsilon)
|
| 257 |
+
|
| 258 |
+
self.scale = 1 / (d_head**0.5)
|
| 259 |
+
|
| 260 |
+
self.pre_lnorm = pre_lnorm
|
| 261 |
+
|
| 262 |
+
if r_r_bias is None or r_w_bias is None: # Biases are not shared
|
| 263 |
+
self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
|
| 264 |
+
self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
|
| 265 |
+
else:
|
| 266 |
+
self.r_r_bias = r_r_bias
|
| 267 |
+
self.r_w_bias = r_w_bias
|
| 268 |
+
|
| 269 |
+
self.r_net = nn.Linear(self.d_model, self.n_head * self.d_head, bias=False)
|
| 270 |
+
|
| 271 |
+
def _rel_shift(self, x):
|
| 272 |
+
zero_pad_shape = (x.size(0), 1) + x.size()[2:]
|
| 273 |
+
zero_pad = torch.zeros(zero_pad_shape, device=x.device, dtype=x.dtype)
|
| 274 |
+
x_padded = torch.cat([zero_pad, x], dim=1)
|
| 275 |
+
|
| 276 |
+
x_padded_shape = (x.size(1) + 1, x.size(0)) + x.size()[2:]
|
| 277 |
+
x_padded = x_padded.view(*x_padded_shape)
|
| 278 |
+
|
| 279 |
+
x = x_padded[1:].view_as(x)
|
| 280 |
+
|
| 281 |
+
return x
|
| 282 |
+
|
| 283 |
+
def forward(self, w, r, attn_mask=None, mems=None, head_mask=None, output_attentions=False):
|
| 284 |
+
qlen, rlen, bsz = w.size(0), r.size(0), w.size(1)
|
| 285 |
+
|
| 286 |
+
if mems is not None:
|
| 287 |
+
cat = torch.cat([mems, w], 0)
|
| 288 |
+
if self.pre_lnorm:
|
| 289 |
+
w_heads = self.qkv_net(self.layer_norm(cat))
|
| 290 |
+
else:
|
| 291 |
+
w_heads = self.qkv_net(cat)
|
| 292 |
+
r_head_k = self.r_net(r)
|
| 293 |
+
|
| 294 |
+
w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)
|
| 295 |
+
w_head_q = w_head_q[-qlen:]
|
| 296 |
+
else:
|
| 297 |
+
if self.pre_lnorm:
|
| 298 |
+
w_heads = self.qkv_net(self.layer_norm(w))
|
| 299 |
+
else:
|
| 300 |
+
w_heads = self.qkv_net(w)
|
| 301 |
+
r_head_k = self.r_net(r)
|
| 302 |
+
|
| 303 |
+
w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)
|
| 304 |
+
|
| 305 |
+
klen = w_head_k.size(0)
|
| 306 |
+
|
| 307 |
+
w_head_q = w_head_q.view(qlen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head
|
| 308 |
+
w_head_k = w_head_k.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head
|
| 309 |
+
w_head_v = w_head_v.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head
|
| 310 |
+
|
| 311 |
+
r_head_k = r_head_k.view(rlen, self.n_head, self.d_head) # qlen x n_head x d_head
|
| 312 |
+
|
| 313 |
+
# compute attention score
|
| 314 |
+
rw_head_q = w_head_q + self.r_w_bias # qlen x bsz x n_head x d_head
|
| 315 |
+
AC = torch.einsum("ibnd,jbnd->ijbn", (rw_head_q, w_head_k)) # qlen x klen x bsz x n_head
|
| 316 |
+
|
| 317 |
+
rr_head_q = w_head_q + self.r_r_bias
|
| 318 |
+
BD = torch.einsum("ibnd,jnd->ijbn", (rr_head_q, r_head_k)) # qlen x klen x bsz x n_head
|
| 319 |
+
BD = self._rel_shift(BD)
|
| 320 |
+
|
| 321 |
+
# [qlen x klen x bsz x n_head]
|
| 322 |
+
attn_score = AC + BD
|
| 323 |
+
attn_score.mul_(self.scale)
|
| 324 |
+
|
| 325 |
+
mask_value = torch.finfo(attn_score.dtype).min
|
| 326 |
+
|
| 327 |
+
# compute attention probability
|
| 328 |
+
if attn_mask is not None and torch.sum(attn_mask).item():
|
| 329 |
+
attn_mask = attn_mask == 1 # Switch to bool
|
| 330 |
+
if attn_mask.dim() == 2:
|
| 331 |
+
attn_score = (
|
| 332 |
+
attn_score.float().masked_fill(attn_mask[None, :, :, None], mask_value).type_as(attn_score)
|
| 333 |
+
)
|
| 334 |
+
elif attn_mask.dim() == 3:
|
| 335 |
+
attn_score = attn_score.float().masked_fill(attn_mask[:, :, :, None], mask_value).type_as(attn_score)
|
| 336 |
+
|
| 337 |
+
# [qlen x klen x bsz x n_head]
|
| 338 |
+
attn_prob = nn.functional.softmax(attn_score, dim=1)
|
| 339 |
+
attn_prob = self.dropatt(attn_prob)
|
| 340 |
+
|
| 341 |
+
# Mask heads if we want to
|
| 342 |
+
if head_mask is not None:
|
| 343 |
+
attn_prob = attn_prob * head_mask
|
| 344 |
+
|
| 345 |
+
# compute attention vector
|
| 346 |
+
attn_vec = torch.einsum("ijbn,jbnd->ibnd", (attn_prob, w_head_v))
|
| 347 |
+
|
| 348 |
+
# [qlen x bsz x n_head x d_head]
|
| 349 |
+
attn_vec = attn_vec.contiguous().view(attn_vec.size(0), attn_vec.size(1), self.n_head * self.d_head)
|
| 350 |
+
|
| 351 |
+
# linear projection
|
| 352 |
+
attn_out = self.o_net(attn_vec)
|
| 353 |
+
attn_out = self.drop(attn_out)
|
| 354 |
+
|
| 355 |
+
if self.pre_lnorm:
|
| 356 |
+
# residual connection
|
| 357 |
+
outputs = [w + attn_out]
|
| 358 |
+
else:
|
| 359 |
+
# residual connection + layer normalization
|
| 360 |
+
outputs = [self.layer_norm(w + attn_out)]
|
| 361 |
+
|
| 362 |
+
if output_attentions:
|
| 363 |
+
outputs.append(attn_prob)
|
| 364 |
+
|
| 365 |
+
return outputs
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
class RelPartialLearnableDecoderLayer(nn.Module):
|
| 369 |
+
def __init__(self, n_head, d_model, d_head, d_inner, dropout, layer_norm_epsilon=1e-5, **kwargs):
|
| 370 |
+
super().__init__()
|
| 371 |
+
|
| 372 |
+
self.dec_attn = RelPartialLearnableMultiHeadAttn(
|
| 373 |
+
n_head, d_model, d_head, dropout, layer_norm_epsilon=layer_norm_epsilon, **kwargs
|
| 374 |
+
)
|
| 375 |
+
self.pos_ff = PositionwiseFF(
|
| 376 |
+
d_model, d_inner, dropout, pre_lnorm=kwargs.get("pre_lnorm"), layer_norm_epsilon=layer_norm_epsilon
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
def forward(self, dec_inp, r, dec_attn_mask=None, mems=None, head_mask=None, output_attentions=False):
|
| 380 |
+
attn_outputs = self.dec_attn(
|
| 381 |
+
dec_inp,
|
| 382 |
+
r,
|
| 383 |
+
attn_mask=dec_attn_mask,
|
| 384 |
+
mems=mems,
|
| 385 |
+
head_mask=head_mask,
|
| 386 |
+
output_attentions=output_attentions,
|
| 387 |
+
)
|
| 388 |
+
ff_output = self.pos_ff(attn_outputs[0])
|
| 389 |
+
|
| 390 |
+
outputs = [ff_output] + attn_outputs[1:]
|
| 391 |
+
|
| 392 |
+
return outputs
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
class AdaptiveEmbedding(nn.Module):
|
| 396 |
+
def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, sample_softmax=False):
|
| 397 |
+
super().__init__()
|
| 398 |
+
|
| 399 |
+
self.n_token = n_token
|
| 400 |
+
self.d_embed = d_embed
|
| 401 |
+
|
| 402 |
+
self.cutoffs = cutoffs + [n_token]
|
| 403 |
+
self.div_val = div_val
|
| 404 |
+
self.d_proj = d_proj
|
| 405 |
+
|
| 406 |
+
self.emb_scale = d_proj**0.5
|
| 407 |
+
|
| 408 |
+
self.cutoff_ends = [0] + self.cutoffs
|
| 409 |
+
|
| 410 |
+
self.emb_layers = nn.ModuleList()
|
| 411 |
+
self.emb_projs = nn.ParameterList()
|
| 412 |
+
if div_val == 1:
|
| 413 |
+
self.emb_layers.append(nn.Embedding(n_token, d_embed, sparse=sample_softmax > 0))
|
| 414 |
+
if d_proj != d_embed:
|
| 415 |
+
self.emb_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_embed)))
|
| 416 |
+
else:
|
| 417 |
+
for i in range(len(self.cutoffs)):
|
| 418 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 419 |
+
d_emb_i = d_embed // (div_val**i)
|
| 420 |
+
self.emb_layers.append(nn.Embedding(r_idx - l_idx, d_emb_i))
|
| 421 |
+
self.emb_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_emb_i)))
|
| 422 |
+
|
| 423 |
+
def forward(self, inp):
|
| 424 |
+
if self.div_val == 1:
|
| 425 |
+
embed = self.emb_layers[0](inp)
|
| 426 |
+
if self.d_proj != self.d_embed:
|
| 427 |
+
embed = nn.functional.linear(embed, self.emb_projs[0])
|
| 428 |
+
else:
|
| 429 |
+
param = next(self.parameters())
|
| 430 |
+
inp_flat = inp.view(-1)
|
| 431 |
+
emb_flat = torch.zeros([inp_flat.size(0), self.d_proj], dtype=param.dtype, device=param.device)
|
| 432 |
+
for i in range(len(self.cutoffs)):
|
| 433 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 434 |
+
|
| 435 |
+
mask_i = (inp_flat >= l_idx) & (inp_flat < r_idx)
|
| 436 |
+
indices_i = mask_i.nonzero().squeeze()
|
| 437 |
+
|
| 438 |
+
if indices_i.numel() == 0:
|
| 439 |
+
continue
|
| 440 |
+
|
| 441 |
+
inp_i = inp_flat.index_select(0, indices_i) - l_idx
|
| 442 |
+
emb_i = self.emb_layers[i](inp_i)
|
| 443 |
+
emb_i = nn.functional.linear(emb_i, self.emb_projs[i])
|
| 444 |
+
|
| 445 |
+
emb_flat.index_copy_(0, indices_i, emb_i)
|
| 446 |
+
|
| 447 |
+
embed_shape = inp.size() + (self.d_proj,)
|
| 448 |
+
embed = emb_flat.view(embed_shape)
|
| 449 |
+
|
| 450 |
+
embed.mul_(self.emb_scale)
|
| 451 |
+
|
| 452 |
+
return embed
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
class TransfoXLPreTrainedModel(PreTrainedModel):
|
| 456 |
+
"""
|
| 457 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 458 |
+
models.
|
| 459 |
+
"""
|
| 460 |
+
|
| 461 |
+
config_class = TransfoXLConfig
|
| 462 |
+
load_tf_weights = load_tf_weights_in_transfo_xl
|
| 463 |
+
base_model_prefix = "transformer"
|
| 464 |
+
|
| 465 |
+
def _init_weight(self, weight):
|
| 466 |
+
if self.config.init == "uniform":
|
| 467 |
+
nn.init.uniform_(weight, -self.config.init_range, self.config.init_range)
|
| 468 |
+
elif self.config.init == "normal":
|
| 469 |
+
nn.init.normal_(weight, 0.0, self.config.init_std)
|
| 470 |
+
|
| 471 |
+
def _init_bias(self, bias):
|
| 472 |
+
nn.init.constant_(bias, 0.0)
|
| 473 |
+
|
| 474 |
+
def _init_weights(self, m):
|
| 475 |
+
"""Initialize the weights."""
|
| 476 |
+
classname = m.__class__.__name__
|
| 477 |
+
if classname.find("Linear") != -1:
|
| 478 |
+
if hasattr(m, "weight") and m.weight is not None:
|
| 479 |
+
self._init_weight(m.weight)
|
| 480 |
+
if hasattr(m, "bias") and m.bias is not None:
|
| 481 |
+
self._init_bias(m.bias)
|
| 482 |
+
elif classname.find("AdaptiveEmbedding") != -1:
|
| 483 |
+
if hasattr(m, "emb_projs"):
|
| 484 |
+
for i in range(len(m.emb_projs)):
|
| 485 |
+
if m.emb_projs[i] is not None:
|
| 486 |
+
nn.init.normal_(m.emb_projs[i], 0.0, self.config.proj_init_std)
|
| 487 |
+
elif classname.find("Embedding") != -1:
|
| 488 |
+
if hasattr(m, "weight"):
|
| 489 |
+
self._init_weight(m.weight)
|
| 490 |
+
elif classname.find("ProjectedAdaptiveLogSoftmax") != -1:
|
| 491 |
+
if hasattr(m, "cluster_weight") and m.cluster_weight is not None:
|
| 492 |
+
self._init_weight(m.cluster_weight)
|
| 493 |
+
if hasattr(m, "cluster_bias") and m.cluster_bias is not None:
|
| 494 |
+
self._init_bias(m.cluster_bias)
|
| 495 |
+
if hasattr(m, "out_projs"):
|
| 496 |
+
for i in range(len(m.out_projs)):
|
| 497 |
+
if m.out_projs[i] is not None:
|
| 498 |
+
nn.init.normal_(m.out_projs[i], 0.0, self.config.proj_init_std)
|
| 499 |
+
elif classname.find("LayerNorm") != -1:
|
| 500 |
+
if hasattr(m, "weight"):
|
| 501 |
+
nn.init.normal_(m.weight, 1.0, self.config.init_std)
|
| 502 |
+
if hasattr(m, "bias") and m.bias is not None:
|
| 503 |
+
self._init_bias(m.bias)
|
| 504 |
+
else:
|
| 505 |
+
if hasattr(m, "r_emb"):
|
| 506 |
+
self._init_weight(m.r_emb)
|
| 507 |
+
if hasattr(m, "r_w_bias"):
|
| 508 |
+
self._init_weight(m.r_w_bias)
|
| 509 |
+
if hasattr(m, "r_r_bias"):
|
| 510 |
+
self._init_weight(m.r_r_bias)
|
| 511 |
+
if hasattr(m, "r_bias"):
|
| 512 |
+
self._init_bias(m.r_bias)
|
| 513 |
+
|
| 514 |
+
def resize_token_embeddings(self, new_num_tokens: Optional[int] = None, layer: Optional[int] = -1):
|
| 515 |
+
"""
|
| 516 |
+
Resize input token embeddings matrix of the model if new_num_tokens != config.vocab_size. Take care of tying
|
| 517 |
+
weights embeddings afterwards if the model class has a *tie_weights()* method.
|
| 518 |
+
|
| 519 |
+
Arguments:
|
| 520 |
+
new_num_tokens: (*optional*) int:
|
| 521 |
+
New number of tokens in the embedding matrix. Increasing the size will add newly initialized vectors at
|
| 522 |
+
the end. Reducing the size will remove vectors from the end. If not provided or None: does nothing and
|
| 523 |
+
just returns a pointer to the input tokens `torch.nn.Embeddings` Module of the model.
|
| 524 |
+
layer: (*optional*) int:
|
| 525 |
+
Layer of the *AdaptiveEmbedding* where the resizing should be done. Per default the last layer will be
|
| 526 |
+
resized. Be aware that when resizing other than the last layer, you have to ensure that the new
|
| 527 |
+
token(s) in the tokenizer are at the corresponding position.
|
| 528 |
+
|
| 529 |
+
Return: `torch.nn.Embeddings` Pointer to the input tokens Embeddings Module of the model
|
| 530 |
+
"""
|
| 531 |
+
base_model = getattr(self, self.base_model_prefix, self) # get the base model if needed
|
| 532 |
+
|
| 533 |
+
if new_num_tokens is None:
|
| 534 |
+
return self.get_input_embeddings()
|
| 535 |
+
|
| 536 |
+
new_num_tokens_layer, layer = self._get_new_num_tokens_layer(new_num_tokens, layer)
|
| 537 |
+
assert new_num_tokens_layer > 0, "The size of the new embedding layer cannot be 0 or less"
|
| 538 |
+
model_embeds = base_model._resize_token_embeddings(new_num_tokens_layer, layer)
|
| 539 |
+
|
| 540 |
+
# Update base model and current model config
|
| 541 |
+
self.config.vocab_size = new_num_tokens
|
| 542 |
+
base_model.vocab_size = new_num_tokens
|
| 543 |
+
base_model.n_token = new_num_tokens
|
| 544 |
+
|
| 545 |
+
new_embedding_shapes = self._get_embedding_shapes()
|
| 546 |
+
self._resize_cutoffs(new_num_tokens, new_num_tokens_layer, new_embedding_shapes, layer)
|
| 547 |
+
|
| 548 |
+
# Tie weights again if needed
|
| 549 |
+
self.tie_weights()
|
| 550 |
+
|
| 551 |
+
return model_embeds
|
| 552 |
+
|
| 553 |
+
def _get_new_num_tokens_layer(self, new_num_tokens, layer):
|
| 554 |
+
embeddings = self.get_input_embeddings()
|
| 555 |
+
if layer == -1:
|
| 556 |
+
layer = len(embeddings.emb_layers) - 1
|
| 557 |
+
assert 0 <= layer <= len(embeddings.emb_layers) - 1
|
| 558 |
+
|
| 559 |
+
new_num_tokens_layer = (
|
| 560 |
+
new_num_tokens
|
| 561 |
+
- sum([emb.weight.shape[0] for emb in embeddings.emb_layers[:layer]])
|
| 562 |
+
- sum([emb.weight.shape[0] for emb in embeddings.emb_layers[layer + 1 :]])
|
| 563 |
+
)
|
| 564 |
+
return new_num_tokens_layer, layer
|
| 565 |
+
|
| 566 |
+
def _get_embedding_shapes(self):
|
| 567 |
+
embeddings = self.get_input_embeddings()
|
| 568 |
+
return [emb.weight.shape[0] for emb in embeddings.emb_layers]
|
| 569 |
+
|
| 570 |
+
def _resize_token_embeddings(self, new_num_tokens, layer=-1):
|
| 571 |
+
embeddings = self.get_input_embeddings()
|
| 572 |
+
if new_num_tokens is None:
|
| 573 |
+
return embeddings
|
| 574 |
+
new_embeddings_layer = self._get_resized_embeddings(embeddings.emb_layers[layer], new_num_tokens)
|
| 575 |
+
embeddings.emb_layers[layer] = new_embeddings_layer
|
| 576 |
+
|
| 577 |
+
self.set_input_embeddings(embeddings)
|
| 578 |
+
|
| 579 |
+
return self.get_input_embeddings()
|
| 580 |
+
|
| 581 |
+
def _resize_cutoffs(self, new_num_tokens, new_emb_size, new_embedding_shapes, layer):
|
| 582 |
+
embeddings = self.get_input_embeddings()
|
| 583 |
+
|
| 584 |
+
for i in range(layer, len(embeddings.cutoffs)):
|
| 585 |
+
embeddings.cutoffs[i] = sum(new_embedding_shapes[: i + 1])
|
| 586 |
+
|
| 587 |
+
embeddings.cutoff_ends = [0] + embeddings.cutoffs
|
| 588 |
+
embeddings.n_token = new_num_tokens
|
| 589 |
+
|
| 590 |
+
self.config.cutoffs = embeddings.cutoffs[:-1]
|
| 591 |
+
|
| 592 |
+
return embeddings.cutoffs
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
@dataclass
|
| 596 |
+
class TransfoXLModelOutput(ModelOutput):
|
| 597 |
+
"""
|
| 598 |
+
Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
|
| 599 |
+
|
| 600 |
+
Args:
|
| 601 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 602 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 603 |
+
mems (`List[torch.FloatTensor]` of length `config.n_layers`):
|
| 604 |
+
Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
|
| 605 |
+
input) to speed up sequential decoding. The token ids which have their past given to this model should not
|
| 606 |
+
be passed as input ids as they have already been computed.
|
| 607 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 608 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 609 |
+
shape `(batch_size, sequence_length, hidden_size)`.
|
| 610 |
+
|
| 611 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 612 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 613 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 614 |
+
sequence_length)`.
|
| 615 |
+
|
| 616 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 617 |
+
heads.
|
| 618 |
+
"""
|
| 619 |
+
|
| 620 |
+
last_hidden_state: torch.FloatTensor
|
| 621 |
+
mems: List[torch.FloatTensor] = None
|
| 622 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 623 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
@dataclass
|
| 627 |
+
class TransfoXLSequenceClassifierOutputWithPast(ModelOutput):
|
| 628 |
+
"""
|
| 629 |
+
Base class for outputs of sentence classification models.
|
| 630 |
+
|
| 631 |
+
Args:
|
| 632 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 633 |
+
Classification (or regression if config.num_labels==1) loss.
|
| 634 |
+
logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
|
| 635 |
+
Classification (or regression if config.num_labels==1) scores (before SoftMax).
|
| 636 |
+
mems (`List[torch.FloatTensor]` of length `config.n_layers`):
|
| 637 |
+
Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
|
| 638 |
+
input) to speed up sequential decoding. The token ids which have their past given to this model should not
|
| 639 |
+
be passed as input ids as they have already been computed.
|
| 640 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 641 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 642 |
+
shape `(batch_size, sequence_length, hidden_size)`.
|
| 643 |
+
|
| 644 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 645 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 646 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 647 |
+
sequence_length)`.
|
| 648 |
+
|
| 649 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 650 |
+
heads.
|
| 651 |
+
"""
|
| 652 |
+
|
| 653 |
+
loss: Optional[torch.FloatTensor] = None
|
| 654 |
+
logits: torch.FloatTensor = None
|
| 655 |
+
mems: List[torch.FloatTensor] = None
|
| 656 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 657 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
@dataclass
|
| 661 |
+
class TransfoXLLMHeadModelOutput(ModelOutput):
|
| 662 |
+
"""
|
| 663 |
+
Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
|
| 664 |
+
|
| 665 |
+
Args:
|
| 666 |
+
losses (`torch.FloatTensor` of shape *(batch_size, sequence_length-1)*, *optional*, returned when `labels` is provided):
|
| 667 |
+
Language modeling losses (not reduced).
|
| 668 |
+
prediction_scores (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 669 |
+
Prediction scores of the language modeling head (scores for each vocabulary token after SoftMax).
|
| 670 |
+
mems (`List[torch.FloatTensor]` of length `config.n_layers`):
|
| 671 |
+
Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
|
| 672 |
+
input) to speed up sequential decoding. The token ids which have their past given to this model should not
|
| 673 |
+
be passed as input ids as they have already been computed.
|
| 674 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 675 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 676 |
+
shape `(batch_size, sequence_length, hidden_size)`.
|
| 677 |
+
|
| 678 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 679 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 680 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 681 |
+
sequence_length)`.
|
| 682 |
+
|
| 683 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 684 |
+
heads.
|
| 685 |
+
loss (`torch.FloatTensor` of shape `()`, *optional*, returned when `labels` is provided)
|
| 686 |
+
Reduced language modeling loss.
|
| 687 |
+
"""
|
| 688 |
+
|
| 689 |
+
losses: Optional[torch.FloatTensor] = None
|
| 690 |
+
prediction_scores: torch.FloatTensor = None
|
| 691 |
+
mems: List[torch.FloatTensor] = None
|
| 692 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 693 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 694 |
+
loss: Optional[torch.FloatTensor] = None
|
| 695 |
+
|
| 696 |
+
@property
|
| 697 |
+
def logits(self):
|
| 698 |
+
# prediction scores are the output of the adaptive softmax, see
|
| 699 |
+
# the file `modeling_transfo_xl_utilities`. Since the adaptive
|
| 700 |
+
# softmax returns the log softmax value, `self.prediction_scores`
|
| 701 |
+
# are strictly speaking not exactly `logits`, but behave the same
|
| 702 |
+
# way logits do.
|
| 703 |
+
return self.prediction_scores
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
TRANSFO_XL_START_DOCSTRING = r"""
|
| 707 |
+
|
| 708 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 709 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 710 |
+
etc.)
|
| 711 |
+
|
| 712 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 713 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 714 |
+
and behavior.
|
| 715 |
+
|
| 716 |
+
Parameters:
|
| 717 |
+
config ([`TransfoXLConfig`]): Model configuration class with all the parameters of the model.
|
| 718 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 719 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 720 |
+
"""
|
| 721 |
+
|
| 722 |
+
TRANSFO_XL_INPUTS_DOCSTRING = r"""
|
| 723 |
+
Args:
|
| 724 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 725 |
+
Indices of input sequence tokens in the vocabulary.
|
| 726 |
+
|
| 727 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 728 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 729 |
+
|
| 730 |
+
[What are input IDs?](../glossary#input-ids)
|
| 731 |
+
mems (`List[torch.FloatTensor]` of length `config.n_layers`):
|
| 732 |
+
Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see
|
| 733 |
+
`mems` output below). Can be used to speed up sequential decoding. The token ids which have their mems
|
| 734 |
+
given to this model should not be passed as `input_ids` as they have already been computed.
|
| 735 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 736 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 737 |
+
|
| 738 |
+
- 1 indicates the head is **not masked**,
|
| 739 |
+
- 0 indicates the head is **masked**.
|
| 740 |
+
|
| 741 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 742 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 743 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 744 |
+
model's internal embedding lookup matrix.
|
| 745 |
+
output_attentions (`bool`, *optional*):
|
| 746 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 747 |
+
tensors for more detail.
|
| 748 |
+
output_hidden_states (`bool`, *optional*):
|
| 749 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 750 |
+
more detail.
|
| 751 |
+
return_dict (`bool`, *optional*):
|
| 752 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 753 |
+
"""
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
@add_start_docstrings(
|
| 757 |
+
"The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
|
| 758 |
+
TRANSFO_XL_START_DOCSTRING,
|
| 759 |
+
)
|
| 760 |
+
class TransfoXLModel(TransfoXLPreTrainedModel):
|
| 761 |
+
def __init__(self, config):
|
| 762 |
+
super().__init__(config)
|
| 763 |
+
|
| 764 |
+
self.n_token = config.vocab_size
|
| 765 |
+
|
| 766 |
+
self.d_embed = config.d_embed
|
| 767 |
+
self.d_model = config.d_model
|
| 768 |
+
self.n_head = config.n_head
|
| 769 |
+
self.d_head = config.d_head
|
| 770 |
+
|
| 771 |
+
self.word_emb = AdaptiveEmbedding(
|
| 772 |
+
config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val
|
| 773 |
+
)
|
| 774 |
+
|
| 775 |
+
self.drop = nn.Dropout(config.dropout)
|
| 776 |
+
|
| 777 |
+
self.n_layer = config.n_layer
|
| 778 |
+
self.mem_len = config.mem_len
|
| 779 |
+
self.attn_type = config.attn_type
|
| 780 |
+
|
| 781 |
+
if not config.untie_r:
|
| 782 |
+
self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
|
| 783 |
+
self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
|
| 784 |
+
|
| 785 |
+
self.layers = nn.ModuleList()
|
| 786 |
+
if config.attn_type == 0: # the default attention
|
| 787 |
+
for i in range(config.n_layer):
|
| 788 |
+
self.layers.append(
|
| 789 |
+
RelPartialLearnableDecoderLayer(
|
| 790 |
+
config.n_head,
|
| 791 |
+
config.d_model,
|
| 792 |
+
config.d_head,
|
| 793 |
+
config.d_inner,
|
| 794 |
+
config.dropout,
|
| 795 |
+
dropatt=config.dropatt,
|
| 796 |
+
pre_lnorm=config.pre_lnorm,
|
| 797 |
+
r_w_bias=None if config.untie_r else self.r_w_bias,
|
| 798 |
+
r_r_bias=None if config.untie_r else self.r_r_bias,
|
| 799 |
+
layer_norm_epsilon=config.layer_norm_epsilon,
|
| 800 |
+
)
|
| 801 |
+
)
|
| 802 |
+
else: # learnable embeddings and absolute embeddings are not used in our pretrained checkpoints
|
| 803 |
+
raise NotImplementedError # Removed them to avoid maintaining dead code
|
| 804 |
+
|
| 805 |
+
self.same_length = config.same_length
|
| 806 |
+
self.clamp_len = config.clamp_len
|
| 807 |
+
|
| 808 |
+
if self.attn_type == 0: # default attention
|
| 809 |
+
self.pos_emb = PositionalEmbedding(self.d_model)
|
| 810 |
+
else: # learnable embeddings and absolute embeddings
|
| 811 |
+
raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
|
| 812 |
+
|
| 813 |
+
# Initialize weights and apply final processing
|
| 814 |
+
self.post_init()
|
| 815 |
+
|
| 816 |
+
def get_input_embeddings(self):
|
| 817 |
+
return self.word_emb
|
| 818 |
+
|
| 819 |
+
def set_input_embeddings(self, new_embeddings):
|
| 820 |
+
self.word_emb = new_embeddings
|
| 821 |
+
|
| 822 |
+
def backward_compatible(self):
|
| 823 |
+
self.sample_softmax = -1
|
| 824 |
+
|
| 825 |
+
def reset_memory_length(self, mem_len):
|
| 826 |
+
self.mem_len = mem_len
|
| 827 |
+
|
| 828 |
+
def _prune_heads(self, heads):
|
| 829 |
+
logger.info("Head pruning is not implemented for Transformer-XL model")
|
| 830 |
+
pass
|
| 831 |
+
|
| 832 |
+
def init_mems(self, bsz):
|
| 833 |
+
if self.mem_len > 0:
|
| 834 |
+
mems = []
|
| 835 |
+
param = next(self.parameters())
|
| 836 |
+
for i in range(self.n_layer):
|
| 837 |
+
empty = torch.zeros(self.mem_len, bsz, self.config.d_model, dtype=param.dtype, device=param.device)
|
| 838 |
+
mems.append(empty)
|
| 839 |
+
|
| 840 |
+
return mems
|
| 841 |
+
else:
|
| 842 |
+
return None
|
| 843 |
+
|
| 844 |
+
def _update_mems(self, hids, mems, mlen, qlen):
|
| 845 |
+
# does not deal with None
|
| 846 |
+
if mems is None:
|
| 847 |
+
return None
|
| 848 |
+
|
| 849 |
+
# mems is not None
|
| 850 |
+
assert len(hids) == len(mems), "len(hids) != len(mems)"
|
| 851 |
+
|
| 852 |
+
# There are `mlen + qlen` steps that can be cached into mems
|
| 853 |
+
with torch.no_grad():
|
| 854 |
+
new_mems = []
|
| 855 |
+
end_idx = mlen + max(0, qlen)
|
| 856 |
+
beg_idx = max(0, end_idx - self.mem_len)
|
| 857 |
+
for i in range(len(hids)):
|
| 858 |
+
cat = torch.cat([mems[i], hids[i]], dim=0)
|
| 859 |
+
new_mems.append(cat[beg_idx:end_idx].detach())
|
| 860 |
+
|
| 861 |
+
return new_mems
|
| 862 |
+
|
| 863 |
+
@add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
|
| 864 |
+
@add_code_sample_docstrings(
|
| 865 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 866 |
+
output_type=TransfoXLModelOutput,
|
| 867 |
+
config_class=_CONFIG_FOR_DOC,
|
| 868 |
+
)
|
| 869 |
+
def forward(
|
| 870 |
+
self,
|
| 871 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 872 |
+
mems: Optional[List[torch.FloatTensor]] = None,
|
| 873 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 874 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 875 |
+
output_attentions: Optional[bool] = None,
|
| 876 |
+
output_hidden_states: Optional[bool] = None,
|
| 877 |
+
return_dict: Optional[bool] = None,
|
| 878 |
+
) -> Union[Tuple, TransfoXLModelOutput]:
|
| 879 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 880 |
+
output_hidden_states = (
|
| 881 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 882 |
+
)
|
| 883 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 884 |
+
|
| 885 |
+
# the original code for Transformer-XL used shapes [len, bsz] but we want a unified interface in the library
|
| 886 |
+
# so we transpose here from shape [bsz, len] to shape [len, bsz]
|
| 887 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 888 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 889 |
+
elif input_ids is not None:
|
| 890 |
+
input_ids = input_ids.transpose(0, 1).contiguous()
|
| 891 |
+
qlen, bsz = input_ids.size()
|
| 892 |
+
elif inputs_embeds is not None:
|
| 893 |
+
inputs_embeds = inputs_embeds.transpose(0, 1).contiguous()
|
| 894 |
+
qlen, bsz = inputs_embeds.shape[0], inputs_embeds.shape[1]
|
| 895 |
+
else:
|
| 896 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 897 |
+
|
| 898 |
+
if mems is None:
|
| 899 |
+
mems = self.init_mems(bsz)
|
| 900 |
+
|
| 901 |
+
# Prepare head mask if needed
|
| 902 |
+
# 1.0 in head_mask indicate we keep the head
|
| 903 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 904 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] (a head_mask for each layer)
|
| 905 |
+
# and head_mask is converted to shape [num_hidden_layers x qlen x klen x bsz x n_head]
|
| 906 |
+
if head_mask is not None:
|
| 907 |
+
if head_mask.dim() == 1:
|
| 908 |
+
head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(0).unsqueeze(0)
|
| 909 |
+
head_mask = head_mask.expand(self.n_layer, -1, -1, -1, -1)
|
| 910 |
+
elif head_mask.dim() == 2:
|
| 911 |
+
head_mask = head_mask.unsqueeze(1).unsqueeze(1).unsqueeze(1)
|
| 912 |
+
head_mask = head_mask.to(
|
| 913 |
+
dtype=next(self.parameters()).dtype
|
| 914 |
+
) # switch to float if need + fp16 compatibility
|
| 915 |
+
else:
|
| 916 |
+
head_mask = [None] * self.n_layer
|
| 917 |
+
|
| 918 |
+
if inputs_embeds is not None:
|
| 919 |
+
word_emb = inputs_embeds
|
| 920 |
+
else:
|
| 921 |
+
word_emb = self.word_emb(input_ids)
|
| 922 |
+
|
| 923 |
+
mlen = mems[0].size(0) if mems is not None else 0
|
| 924 |
+
klen = mlen + qlen
|
| 925 |
+
if self.same_length:
|
| 926 |
+
all_ones = word_emb.new_ones((qlen, klen), dtype=torch.bool)
|
| 927 |
+
mask_len = klen - self.mem_len
|
| 928 |
+
if mask_len > 0:
|
| 929 |
+
mask_shift_len = qlen - mask_len
|
| 930 |
+
else:
|
| 931 |
+
mask_shift_len = qlen
|
| 932 |
+
dec_attn_mask = (torch.triu(all_ones, 1 + mlen) + torch.tril(all_ones, -mask_shift_len))[:, :, None] # -1
|
| 933 |
+
else:
|
| 934 |
+
dec_attn_mask = torch.triu(word_emb.new_ones((qlen, klen), dtype=torch.bool), diagonal=1 + mlen)[
|
| 935 |
+
:, :, None
|
| 936 |
+
]
|
| 937 |
+
|
| 938 |
+
hids = []
|
| 939 |
+
attentions = [] if output_attentions else None
|
| 940 |
+
if self.attn_type == 0: # default
|
| 941 |
+
pos_seq = torch.arange(klen - 1, -1, -1.0, device=word_emb.device, dtype=torch.int64).type_as(
|
| 942 |
+
dtype=word_emb.dtype
|
| 943 |
+
)
|
| 944 |
+
if self.clamp_len > 0:
|
| 945 |
+
pos_seq.clamp_(max=self.clamp_len)
|
| 946 |
+
pos_emb = self.pos_emb(pos_seq)
|
| 947 |
+
|
| 948 |
+
core_out = self.drop(word_emb)
|
| 949 |
+
pos_emb = self.drop(pos_emb)
|
| 950 |
+
|
| 951 |
+
for i, layer in enumerate(self.layers):
|
| 952 |
+
hids.append(core_out)
|
| 953 |
+
mems_i = None if mems is None else mems[i]
|
| 954 |
+
layer_outputs = layer(
|
| 955 |
+
core_out,
|
| 956 |
+
pos_emb,
|
| 957 |
+
dec_attn_mask=dec_attn_mask,
|
| 958 |
+
mems=mems_i,
|
| 959 |
+
head_mask=head_mask[i],
|
| 960 |
+
output_attentions=output_attentions,
|
| 961 |
+
)
|
| 962 |
+
core_out = layer_outputs[0]
|
| 963 |
+
if output_attentions:
|
| 964 |
+
attentions.append(layer_outputs[1])
|
| 965 |
+
else: # learnable embeddings and absolute embeddings
|
| 966 |
+
raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
|
| 967 |
+
|
| 968 |
+
core_out = self.drop(core_out)
|
| 969 |
+
|
| 970 |
+
new_mems = self._update_mems(hids, mems, mlen, qlen)
|
| 971 |
+
|
| 972 |
+
if output_hidden_states:
|
| 973 |
+
# Add last layer and transpose to library standard shape [bsz, len, hidden_dim]
|
| 974 |
+
hids.append(core_out)
|
| 975 |
+
hids = tuple(t.transpose(0, 1).contiguous() for t in hids)
|
| 976 |
+
else:
|
| 977 |
+
hids = None
|
| 978 |
+
if output_attentions:
|
| 979 |
+
# Transpose to library standard shape [bsz, n_heads, query_seq_len, key_seq_len]
|
| 980 |
+
attentions = tuple(t.permute(2, 3, 0, 1).contiguous() for t in attentions)
|
| 981 |
+
# We transpose back here to shape [bsz, len, hidden_dim]
|
| 982 |
+
core_out = core_out.transpose(0, 1).contiguous()
|
| 983 |
+
|
| 984 |
+
if not return_dict:
|
| 985 |
+
return tuple(v for v in [core_out, new_mems, hids, attentions] if v is not None)
|
| 986 |
+
|
| 987 |
+
return TransfoXLModelOutput(
|
| 988 |
+
last_hidden_state=core_out,
|
| 989 |
+
mems=new_mems,
|
| 990 |
+
hidden_states=hids,
|
| 991 |
+
attentions=attentions,
|
| 992 |
+
)
|
| 993 |
+
|
| 994 |
+
|
| 995 |
+
@add_start_docstrings(
|
| 996 |
+
"""
|
| 997 |
+
The Transformer-XL Model with a language modeling head on top (adaptive softmax with weights tied to the adaptive
|
| 998 |
+
input embeddings)
|
| 999 |
+
""",
|
| 1000 |
+
TRANSFO_XL_START_DOCSTRING,
|
| 1001 |
+
)
|
| 1002 |
+
class TransfoXLLMHeadModel(TransfoXLPreTrainedModel):
|
| 1003 |
+
_tied_weights_keys = [r"crit\.out_projs\.\d+", r"crit\.out_layers\.\d+\.weight"]
|
| 1004 |
+
|
| 1005 |
+
def __init__(self, config):
|
| 1006 |
+
super().__init__(config)
|
| 1007 |
+
self.transformer = TransfoXLModel(config)
|
| 1008 |
+
self.sample_softmax = config.sample_softmax
|
| 1009 |
+
self.trainer_compatible = getattr(config, "trainer_compatible", False)
|
| 1010 |
+
|
| 1011 |
+
if not self.trainer_compatible:
|
| 1012 |
+
warnings.warn(
|
| 1013 |
+
"The output of TransfoXL will be updated in v5 to support a single loss as first argument. In order "
|
| 1014 |
+
"to use that updated output, please specify `trainer_compatible=True` as your configuration"
|
| 1015 |
+
" attribute.",
|
| 1016 |
+
DeprecationWarning,
|
| 1017 |
+
)
|
| 1018 |
+
|
| 1019 |
+
assert self.sample_softmax <= 0, (
|
| 1020 |
+
"Sampling from the softmax is not implemented yet. Please look at issue: #3310:"
|
| 1021 |
+
" https://github.com/huggingface/transformers/issues/3310"
|
| 1022 |
+
)
|
| 1023 |
+
|
| 1024 |
+
self.crit = ProjectedAdaptiveLogSoftmax(
|
| 1025 |
+
config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val
|
| 1026 |
+
)
|
| 1027 |
+
|
| 1028 |
+
# Initialize weights and apply final processing
|
| 1029 |
+
self.post_init()
|
| 1030 |
+
|
| 1031 |
+
def tie_weights(self):
|
| 1032 |
+
"""
|
| 1033 |
+
Run this to be sure output and input (adaptive) softmax weights are tied
|
| 1034 |
+
"""
|
| 1035 |
+
|
| 1036 |
+
if self.config.tie_word_embeddings:
|
| 1037 |
+
for i in range(len(self.crit.out_layers)):
|
| 1038 |
+
self._tie_or_clone_weights(self.crit.out_layers[i], self.transformer.word_emb.emb_layers[i])
|
| 1039 |
+
if self.config.tie_projs:
|
| 1040 |
+
for i, tie_proj in enumerate(self.config.tie_projs):
|
| 1041 |
+
if tie_proj and self.config.div_val == 1 and self.config.d_model != self.config.d_embed:
|
| 1042 |
+
if self.config.torchscript:
|
| 1043 |
+
self.crit.out_projs[i] = nn.Parameter(self.transformer.word_emb.emb_projs[0].clone())
|
| 1044 |
+
else:
|
| 1045 |
+
self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[0]
|
| 1046 |
+
elif tie_proj and self.config.div_val != 1:
|
| 1047 |
+
if self.config.torchscript:
|
| 1048 |
+
self.crit.out_projs[i] = nn.Parameter(self.transformer.word_emb.emb_projs[i].clone())
|
| 1049 |
+
else:
|
| 1050 |
+
self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[i]
|
| 1051 |
+
|
| 1052 |
+
def reset_memory_length(self, mem_len):
|
| 1053 |
+
self.transformer.reset_memory_length(mem_len)
|
| 1054 |
+
|
| 1055 |
+
def init_mems(self, bsz):
|
| 1056 |
+
return self.transformer.init_mems(bsz)
|
| 1057 |
+
|
| 1058 |
+
@add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
|
| 1059 |
+
@add_code_sample_docstrings(
|
| 1060 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1061 |
+
output_type=TransfoXLLMHeadModelOutput,
|
| 1062 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1063 |
+
)
|
| 1064 |
+
def forward(
|
| 1065 |
+
self,
|
| 1066 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1067 |
+
mems: Optional[List[torch.FloatTensor]] = None,
|
| 1068 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1069 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1070 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1071 |
+
output_attentions: Optional[bool] = None,
|
| 1072 |
+
output_hidden_states: Optional[bool] = None,
|
| 1073 |
+
return_dict: Optional[bool] = None,
|
| 1074 |
+
) -> Union[Tuple, TransfoXLLMHeadModelOutput]:
|
| 1075 |
+
r"""
|
| 1076 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1077 |
+
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
| 1078 |
+
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
| 1079 |
+
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
| 1080 |
+
"""
|
| 1081 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1082 |
+
if input_ids is not None:
|
| 1083 |
+
bsz, tgt_len = input_ids.size(0), input_ids.size(1)
|
| 1084 |
+
elif inputs_embeds is not None:
|
| 1085 |
+
bsz, tgt_len = inputs_embeds.size(0), inputs_embeds.size(1)
|
| 1086 |
+
else:
|
| 1087 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 1088 |
+
|
| 1089 |
+
transformer_outputs = self.transformer(
|
| 1090 |
+
input_ids,
|
| 1091 |
+
mems=mems,
|
| 1092 |
+
head_mask=head_mask,
|
| 1093 |
+
inputs_embeds=inputs_embeds,
|
| 1094 |
+
output_attentions=output_attentions,
|
| 1095 |
+
output_hidden_states=output_hidden_states,
|
| 1096 |
+
return_dict=return_dict,
|
| 1097 |
+
)
|
| 1098 |
+
|
| 1099 |
+
last_hidden = transformer_outputs[0]
|
| 1100 |
+
pred_hid = last_hidden[:, -tgt_len:]
|
| 1101 |
+
|
| 1102 |
+
if labels is not None:
|
| 1103 |
+
# Prevents all labels being -100 and throwing an error
|
| 1104 |
+
# when backwarding the loss
|
| 1105 |
+
miss_valid_label = labels[0, 1:].sum() == (labels.size(1) - 1) * -100
|
| 1106 |
+
if miss_valid_label:
|
| 1107 |
+
# Sets an <EOS> token, just to prevent loss from being NaN
|
| 1108 |
+
labels[0, 1] = self.config.eos_token_id
|
| 1109 |
+
|
| 1110 |
+
softmax_output = self.crit(pred_hid, labels)
|
| 1111 |
+
prediction_scores = softmax_output.view(bsz, tgt_len, -1) if labels is None else ()
|
| 1112 |
+
|
| 1113 |
+
if labels is not None:
|
| 1114 |
+
losses = softmax_output.view(bsz, tgt_len - 1)
|
| 1115 |
+
# Avoids from incorporating padding (-100) tokens into loss value
|
| 1116 |
+
loss = losses[losses != 0].mean()
|
| 1117 |
+
else:
|
| 1118 |
+
losses, loss = None, None
|
| 1119 |
+
|
| 1120 |
+
if not return_dict:
|
| 1121 |
+
if self.trainer_compatible:
|
| 1122 |
+
output = (prediction_scores, losses) if losses is not None else (prediction_scores,)
|
| 1123 |
+
output += transformer_outputs[1:]
|
| 1124 |
+
return ((loss,) + output) if loss is not None else output
|
| 1125 |
+
else:
|
| 1126 |
+
output = (prediction_scores, *transformer_outputs[1:])
|
| 1127 |
+
output = ((losses,) + output) if losses is not None else output
|
| 1128 |
+
return (output + (loss,)) if loss is not None else output
|
| 1129 |
+
|
| 1130 |
+
return TransfoXLLMHeadModelOutput(
|
| 1131 |
+
loss=loss,
|
| 1132 |
+
prediction_scores=prediction_scores,
|
| 1133 |
+
losses=losses,
|
| 1134 |
+
mems=transformer_outputs.mems,
|
| 1135 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1136 |
+
attentions=transformer_outputs.attentions,
|
| 1137 |
+
)
|
| 1138 |
+
|
| 1139 |
+
def get_output_embeddings(self):
|
| 1140 |
+
"""Double-check if you are using adaptive softmax."""
|
| 1141 |
+
if self.sample_softmax > 0:
|
| 1142 |
+
return self.out_layer
|
| 1143 |
+
else:
|
| 1144 |
+
return self.crit.out_layers[-1]
|
| 1145 |
+
|
| 1146 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **model_kwargs):
|
| 1147 |
+
inputs = {}
|
| 1148 |
+
|
| 1149 |
+
# if past is defined in model kwargs then use it for faster decoding
|
| 1150 |
+
if past_key_values:
|
| 1151 |
+
inputs["mems"] = past_key_values
|
| 1152 |
+
inputs["input_ids"] = input_ids[:, -1].unsqueeze(-1)
|
| 1153 |
+
else:
|
| 1154 |
+
inputs["input_ids"] = input_ids
|
| 1155 |
+
|
| 1156 |
+
return inputs
|
| 1157 |
+
|
| 1158 |
+
def _resize_cutoffs(self, new_num_tokens, new_emb_size, new_embedding_shapes, layer):
|
| 1159 |
+
new_cutoffs = super()._resize_cutoffs(new_num_tokens, new_emb_size, new_embedding_shapes, layer)
|
| 1160 |
+
|
| 1161 |
+
self.crit.cutoffs = new_cutoffs
|
| 1162 |
+
self.crit.cutoff_ends = [0] + new_cutoffs
|
| 1163 |
+
self.crit.n_token = new_num_tokens
|
| 1164 |
+
|
| 1165 |
+
@staticmethod
|
| 1166 |
+
def _reorder_cache(mems: List[torch.Tensor], beam_idx: torch.Tensor) -> List[torch.Tensor]:
|
| 1167 |
+
"""
|
| 1168 |
+
This function is used to re-order the `mems` cache if [`~PreTrainedModel.beam_search`] or
|
| 1169 |
+
[`~PreTrainedModel.beam_sample`] is called. This is required to match `mems` with the correct beam_idx at every
|
| 1170 |
+
generation step.
|
| 1171 |
+
"""
|
| 1172 |
+
return [layer_past.index_select(1, beam_idx.to(layer_past.device)) for layer_past in mems]
|
| 1173 |
+
|
| 1174 |
+
|
| 1175 |
+
@add_start_docstrings(
|
| 1176 |
+
"""
|
| 1177 |
+
The Transformer-XL Model transformer with a sequence classification head on top (linear layer).
|
| 1178 |
+
|
| 1179 |
+
[`TransfoXLForSequenceClassification`] uses the last token in order to do the classification, as other causal
|
| 1180 |
+
models (e.g. GPT-1) do.
|
| 1181 |
+
|
| 1182 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
| 1183 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
| 1184 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
| 1185 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
| 1186 |
+
each row of the batch).
|
| 1187 |
+
""",
|
| 1188 |
+
TRANSFO_XL_START_DOCSTRING,
|
| 1189 |
+
)
|
| 1190 |
+
class TransfoXLForSequenceClassification(TransfoXLPreTrainedModel):
|
| 1191 |
+
def __init__(self, config):
|
| 1192 |
+
super().__init__(config)
|
| 1193 |
+
self.num_labels = config.num_labels
|
| 1194 |
+
self.transformer = TransfoXLModel(config)
|
| 1195 |
+
self.score = nn.Linear(config.d_embed, self.num_labels, bias=False)
|
| 1196 |
+
# Initialize weights and apply final processing
|
| 1197 |
+
self.post_init()
|
| 1198 |
+
|
| 1199 |
+
@add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
|
| 1200 |
+
@add_code_sample_docstrings(
|
| 1201 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1202 |
+
output_type=TransfoXLSequenceClassifierOutputWithPast,
|
| 1203 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1204 |
+
)
|
| 1205 |
+
def forward(
|
| 1206 |
+
self,
|
| 1207 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1208 |
+
mems: Optional[List[torch.FloatTensor]] = None,
|
| 1209 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1210 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1211 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1212 |
+
output_attentions: Optional[bool] = None,
|
| 1213 |
+
output_hidden_states: Optional[bool] = None,
|
| 1214 |
+
return_dict: Optional[bool] = None,
|
| 1215 |
+
) -> Union[Tuple, TransfoXLSequenceClassifierOutputWithPast]:
|
| 1216 |
+
r"""
|
| 1217 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1218 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1219 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1220 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1221 |
+
"""
|
| 1222 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1223 |
+
|
| 1224 |
+
transformer_outputs = self.transformer(
|
| 1225 |
+
input_ids,
|
| 1226 |
+
mems=mems,
|
| 1227 |
+
head_mask=head_mask,
|
| 1228 |
+
inputs_embeds=inputs_embeds,
|
| 1229 |
+
output_attentions=output_attentions,
|
| 1230 |
+
output_hidden_states=output_hidden_states,
|
| 1231 |
+
return_dict=return_dict,
|
| 1232 |
+
)
|
| 1233 |
+
hidden_states = transformer_outputs[0]
|
| 1234 |
+
logits = self.score(hidden_states)
|
| 1235 |
+
|
| 1236 |
+
if input_ids is not None:
|
| 1237 |
+
batch_size, sequence_length = input_ids.shape[:2]
|
| 1238 |
+
else:
|
| 1239 |
+
batch_size, sequence_length = inputs_embeds.shape[:2]
|
| 1240 |
+
|
| 1241 |
+
assert (
|
| 1242 |
+
self.config.pad_token_id is not None or batch_size == 1
|
| 1243 |
+
), "Cannot handle batch sizes > 1 if no padding token is defined."
|
| 1244 |
+
if self.config.pad_token_id is None:
|
| 1245 |
+
sequence_lengths = -1
|
| 1246 |
+
else:
|
| 1247 |
+
if input_ids is not None:
|
| 1248 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
| 1249 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
| 1250 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
| 1251 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
| 1252 |
+
else:
|
| 1253 |
+
sequence_lengths = -1
|
| 1254 |
+
logger.warning_once(
|
| 1255 |
+
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
|
| 1256 |
+
"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
|
| 1257 |
+
)
|
| 1258 |
+
|
| 1259 |
+
pooled_logits = logits[range(batch_size), sequence_lengths]
|
| 1260 |
+
|
| 1261 |
+
loss = None
|
| 1262 |
+
if labels is not None:
|
| 1263 |
+
if self.config.problem_type is None:
|
| 1264 |
+
if self.num_labels == 1:
|
| 1265 |
+
self.config.problem_type = "regression"
|
| 1266 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1267 |
+
self.config.problem_type = "single_label_classification"
|
| 1268 |
+
else:
|
| 1269 |
+
self.config.problem_type = "multi_label_classification"
|
| 1270 |
+
|
| 1271 |
+
if self.config.problem_type == "regression":
|
| 1272 |
+
loss_fct = MSELoss()
|
| 1273 |
+
if self.num_labels == 1:
|
| 1274 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
| 1275 |
+
else:
|
| 1276 |
+
loss = loss_fct(pooled_logits, labels)
|
| 1277 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1278 |
+
loss_fct = CrossEntropyLoss()
|
| 1279 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
| 1280 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1281 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1282 |
+
loss = loss_fct(pooled_logits, labels)
|
| 1283 |
+
if not return_dict:
|
| 1284 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
| 1285 |
+
return ((loss,) + output) if loss is not None else output
|
| 1286 |
+
|
| 1287 |
+
return TransfoXLSequenceClassifierOutputWithPast(
|
| 1288 |
+
loss=loss,
|
| 1289 |
+
logits=pooled_logits,
|
| 1290 |
+
mems=transformer_outputs.mems,
|
| 1291 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1292 |
+
attentions=transformer_outputs.attentions,
|
| 1293 |
+
)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/transfo_xl/modeling_transfo_xl_utilities.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""
|
| 17 |
+
Utilities for PyTorch Transformer XL model. Directly adapted from https://github.com/kimiyoung/transformer-xl.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import nn
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# CUDA_MAJOR = int(torch.version.cuda.split('.')[0])
|
| 25 |
+
# CUDA_MINOR = int(torch.version.cuda.split('.')[1])
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class ProjectedAdaptiveLogSoftmax(nn.Module):
|
| 29 |
+
def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, keep_order=False):
|
| 30 |
+
super().__init__()
|
| 31 |
+
|
| 32 |
+
self.n_token = n_token
|
| 33 |
+
self.d_embed = d_embed
|
| 34 |
+
self.d_proj = d_proj
|
| 35 |
+
|
| 36 |
+
self.cutoffs = cutoffs + [n_token]
|
| 37 |
+
self.cutoff_ends = [0] + self.cutoffs
|
| 38 |
+
self.div_val = div_val
|
| 39 |
+
|
| 40 |
+
self.shortlist_size = self.cutoffs[0]
|
| 41 |
+
self.n_clusters = len(self.cutoffs) - 1
|
| 42 |
+
self.head_size = self.shortlist_size + self.n_clusters
|
| 43 |
+
|
| 44 |
+
if self.n_clusters > 0:
|
| 45 |
+
self.cluster_weight = nn.Parameter(torch.zeros(self.n_clusters, self.d_embed))
|
| 46 |
+
self.cluster_bias = nn.Parameter(torch.zeros(self.n_clusters))
|
| 47 |
+
|
| 48 |
+
self.out_layers = nn.ModuleList()
|
| 49 |
+
self.out_projs = nn.ParameterList()
|
| 50 |
+
|
| 51 |
+
if div_val == 1:
|
| 52 |
+
for i in range(len(self.cutoffs)):
|
| 53 |
+
if d_proj != d_embed:
|
| 54 |
+
self.out_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_embed)))
|
| 55 |
+
else:
|
| 56 |
+
self.out_projs.append(None)
|
| 57 |
+
|
| 58 |
+
self.out_layers.append(nn.Linear(d_embed, n_token))
|
| 59 |
+
else:
|
| 60 |
+
for i in range(len(self.cutoffs)):
|
| 61 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 62 |
+
d_emb_i = d_embed // (div_val**i)
|
| 63 |
+
|
| 64 |
+
self.out_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_emb_i)))
|
| 65 |
+
|
| 66 |
+
self.out_layers.append(nn.Linear(d_emb_i, r_idx - l_idx))
|
| 67 |
+
|
| 68 |
+
self.keep_order = keep_order
|
| 69 |
+
|
| 70 |
+
def _compute_logit(self, hidden, weight, bias, proj):
|
| 71 |
+
if proj is None:
|
| 72 |
+
logit = nn.functional.linear(hidden, weight, bias=bias)
|
| 73 |
+
else:
|
| 74 |
+
# if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1:
|
| 75 |
+
proj_hid = nn.functional.linear(hidden, proj.t().contiguous())
|
| 76 |
+
logit = nn.functional.linear(proj_hid, weight, bias=bias)
|
| 77 |
+
# else:
|
| 78 |
+
# logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t()))
|
| 79 |
+
# if bias is not None:
|
| 80 |
+
# logit = logit + bias
|
| 81 |
+
|
| 82 |
+
return logit
|
| 83 |
+
|
| 84 |
+
def forward(self, hidden, labels=None, keep_order=False):
|
| 85 |
+
"""
|
| 86 |
+
Params:
|
| 87 |
+
hidden :: [len*bsz x d_proj]
|
| 88 |
+
labels :: [len*bsz]
|
| 89 |
+
|
| 90 |
+
Return:
|
| 91 |
+
if labels is None: out :: [len*bsz x n_tokens] log probabilities of tokens over the vocabulary else: out ::
|
| 92 |
+
[(len-1)*bsz] Negative log likelihood. We could replace this implementation by the native PyTorch one if
|
| 93 |
+
theirs had an option to set bias on all clusters in the native one. here:
|
| 94 |
+
https://github.com/pytorch/pytorch/blob/dbe6a7a9ff1a364a8706bf5df58a1ca96d2fd9da/torch/nn/modules/adaptive.py#L138
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
if labels is not None:
|
| 98 |
+
# Shift so that tokens < n predict n
|
| 99 |
+
hidden = hidden[..., :-1, :].contiguous()
|
| 100 |
+
labels = labels[..., 1:].contiguous()
|
| 101 |
+
hidden = hidden.view(-1, hidden.size(-1))
|
| 102 |
+
labels = labels.view(-1)
|
| 103 |
+
if hidden.size(0) != labels.size(0):
|
| 104 |
+
raise RuntimeError("Input and labels should have the same size in the batch dimension.")
|
| 105 |
+
else:
|
| 106 |
+
hidden = hidden.view(-1, hidden.size(-1))
|
| 107 |
+
|
| 108 |
+
if self.n_clusters == 0:
|
| 109 |
+
logit = self._compute_logit(hidden, self.out_layers[0].weight, self.out_layers[0].bias, self.out_projs[0])
|
| 110 |
+
if labels is not None:
|
| 111 |
+
mask = labels != -100
|
| 112 |
+
out = torch.zeros_like(labels, dtype=hidden.dtype, device=hidden.device)
|
| 113 |
+
out[mask] = (
|
| 114 |
+
-nn.functional.log_softmax(logit, dim=-1)[mask].gather(1, labels[mask].unsqueeze(1)).squeeze(1)
|
| 115 |
+
)
|
| 116 |
+
else:
|
| 117 |
+
out = nn.functional.log_softmax(logit, dim=-1)
|
| 118 |
+
else:
|
| 119 |
+
# construct weights and biases
|
| 120 |
+
weights, biases = [], []
|
| 121 |
+
for i in range(len(self.cutoffs)):
|
| 122 |
+
if self.div_val == 1:
|
| 123 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 124 |
+
weight_i = self.out_layers[0].weight[l_idx:r_idx]
|
| 125 |
+
bias_i = self.out_layers[0].bias[l_idx:r_idx]
|
| 126 |
+
else:
|
| 127 |
+
weight_i = self.out_layers[i].weight
|
| 128 |
+
bias_i = self.out_layers[i].bias
|
| 129 |
+
|
| 130 |
+
if i == 0:
|
| 131 |
+
weight_i = torch.cat([weight_i, self.cluster_weight], dim=0)
|
| 132 |
+
bias_i = torch.cat([bias_i, self.cluster_bias], dim=0)
|
| 133 |
+
|
| 134 |
+
weights.append(weight_i)
|
| 135 |
+
biases.append(bias_i)
|
| 136 |
+
|
| 137 |
+
head_weight, head_bias, head_proj = weights[0], biases[0], self.out_projs[0]
|
| 138 |
+
|
| 139 |
+
head_logit = self._compute_logit(hidden, head_weight, head_bias, head_proj)
|
| 140 |
+
head_logprob = nn.functional.log_softmax(head_logit, dim=1)
|
| 141 |
+
|
| 142 |
+
if labels is None:
|
| 143 |
+
out = hidden.new_empty((head_logit.size(0), self.n_token))
|
| 144 |
+
else:
|
| 145 |
+
out = torch.zeros_like(labels, dtype=hidden.dtype, device=hidden.device)
|
| 146 |
+
|
| 147 |
+
offset = 0
|
| 148 |
+
cutoff_values = [0] + self.cutoffs
|
| 149 |
+
for i in range(len(cutoff_values) - 1):
|
| 150 |
+
l_idx, r_idx = cutoff_values[i], cutoff_values[i + 1]
|
| 151 |
+
|
| 152 |
+
if labels is not None:
|
| 153 |
+
mask_i = (labels >= l_idx) & (labels < r_idx)
|
| 154 |
+
indices_i = mask_i.nonzero().squeeze()
|
| 155 |
+
|
| 156 |
+
if indices_i.numel() == 0:
|
| 157 |
+
continue
|
| 158 |
+
|
| 159 |
+
target_i = labels.index_select(0, indices_i) - l_idx
|
| 160 |
+
head_logprob_i = head_logprob.index_select(0, indices_i)
|
| 161 |
+
hidden_i = hidden.index_select(0, indices_i)
|
| 162 |
+
else:
|
| 163 |
+
hidden_i = hidden
|
| 164 |
+
|
| 165 |
+
if i == 0:
|
| 166 |
+
if labels is not None:
|
| 167 |
+
logprob_i = head_logprob_i.gather(1, target_i[:, None]).squeeze(1)
|
| 168 |
+
else:
|
| 169 |
+
out[:, : self.cutoffs[0]] = head_logprob[:, : self.cutoffs[0]]
|
| 170 |
+
else:
|
| 171 |
+
weight_i, bias_i, proj_i = weights[i], biases[i], self.out_projs[i]
|
| 172 |
+
|
| 173 |
+
tail_logit_i = self._compute_logit(hidden_i, weight_i, bias_i, proj_i)
|
| 174 |
+
tail_logprob_i = nn.functional.log_softmax(tail_logit_i, dim=1)
|
| 175 |
+
cluster_prob_idx = self.cutoffs[0] + i - 1 # No probability for the head cluster
|
| 176 |
+
if labels is not None:
|
| 177 |
+
logprob_i = head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather(
|
| 178 |
+
1, target_i[:, None]
|
| 179 |
+
).squeeze(1)
|
| 180 |
+
else:
|
| 181 |
+
logprob_i = head_logprob[:, cluster_prob_idx, None] + tail_logprob_i
|
| 182 |
+
out[:, l_idx:r_idx] = logprob_i
|
| 183 |
+
|
| 184 |
+
if labels is not None:
|
| 185 |
+
if (hasattr(self, "keep_order") and self.keep_order) or keep_order:
|
| 186 |
+
out.index_copy_(0, indices_i, -logprob_i)
|
| 187 |
+
else:
|
| 188 |
+
out[offset : offset + logprob_i.size(0)].copy_(-logprob_i)
|
| 189 |
+
offset += logprob_i.size(0)
|
| 190 |
+
|
| 191 |
+
return out
|
| 192 |
+
|
| 193 |
+
def log_prob(self, hidden):
|
| 194 |
+
r"""
|
| 195 |
+
Computes log probabilities for all \\(n\_classes\\) From:
|
| 196 |
+
https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/adaptive.p
|
| 197 |
+
|
| 198 |
+
Args:
|
| 199 |
+
hidden (Tensor): a minibatch of example
|
| 200 |
+
|
| 201 |
+
Returns:
|
| 202 |
+
log-probabilities of for each class \\(c\\) in range \\(0 <= c <= n\_classes\\), where \\(n\_classes\\) is
|
| 203 |
+
a parameter passed to `AdaptiveLogSoftmaxWithLoss` constructor. Shape:
|
| 204 |
+
|
| 205 |
+
- Input: \\((N, in\_features)\\)
|
| 206 |
+
- Output: \\((N, n\_classes)\\)
|
| 207 |
+
"""
|
| 208 |
+
if self.n_clusters == 0:
|
| 209 |
+
logit = self._compute_logit(hidden, self.out_layers[0].weight, self.out_layers[0].bias, self.out_projs[0])
|
| 210 |
+
return nn.functional.log_softmax(logit, dim=-1)
|
| 211 |
+
else:
|
| 212 |
+
# construct weights and biases
|
| 213 |
+
weights, biases = [], []
|
| 214 |
+
for i in range(len(self.cutoffs)):
|
| 215 |
+
if self.div_val == 1:
|
| 216 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 217 |
+
weight_i = self.out_layers[0].weight[l_idx:r_idx]
|
| 218 |
+
bias_i = self.out_layers[0].bias[l_idx:r_idx]
|
| 219 |
+
else:
|
| 220 |
+
weight_i = self.out_layers[i].weight
|
| 221 |
+
bias_i = self.out_layers[i].bias
|
| 222 |
+
|
| 223 |
+
if i == 0:
|
| 224 |
+
weight_i = torch.cat([weight_i, self.cluster_weight], dim=0)
|
| 225 |
+
bias_i = torch.cat([bias_i, self.cluster_bias], dim=0)
|
| 226 |
+
|
| 227 |
+
weights.append(weight_i)
|
| 228 |
+
biases.append(bias_i)
|
| 229 |
+
|
| 230 |
+
head_weight, head_bias, head_proj = weights[0], biases[0], self.out_projs[0]
|
| 231 |
+
head_logit = self._compute_logit(hidden, head_weight, head_bias, head_proj)
|
| 232 |
+
|
| 233 |
+
out = hidden.new_empty((head_logit.size(0), self.n_token))
|
| 234 |
+
head_logprob = nn.functional.log_softmax(head_logit, dim=1)
|
| 235 |
+
|
| 236 |
+
cutoff_values = [0] + self.cutoffs
|
| 237 |
+
for i in range(len(cutoff_values) - 1):
|
| 238 |
+
start_idx, stop_idx = cutoff_values[i], cutoff_values[i + 1]
|
| 239 |
+
|
| 240 |
+
if i == 0:
|
| 241 |
+
out[:, : self.cutoffs[0]] = head_logprob[:, : self.cutoffs[0]]
|
| 242 |
+
else:
|
| 243 |
+
weight_i, bias_i, proj_i = weights[i], biases[i], self.out_projs[i]
|
| 244 |
+
|
| 245 |
+
tail_logit_i = self._compute_logit(hidden, weight_i, bias_i, proj_i)
|
| 246 |
+
tail_logprob_i = nn.functional.log_softmax(tail_logit_i, dim=1)
|
| 247 |
+
|
| 248 |
+
logprob_i = head_logprob[:, -i] + tail_logprob_i
|
| 249 |
+
out[:, start_idx, stop_idx] = logprob_i
|
| 250 |
+
|
| 251 |
+
return out
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/transfo_xl/tokenization_transfo_xl.py
ADDED
|
@@ -0,0 +1,818 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""
|
| 17 |
+
Tokenization classes for Transformer XL model. Adapted from https://github.com/kimiyoung/transformer-xl.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import glob
|
| 21 |
+
import os
|
| 22 |
+
import pickle
|
| 23 |
+
import re
|
| 24 |
+
from collections import Counter, OrderedDict
|
| 25 |
+
from typing import List, Optional, Tuple
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
from ....tokenization_utils import PreTrainedTokenizer
|
| 30 |
+
from ....utils import (
|
| 31 |
+
cached_file,
|
| 32 |
+
is_sacremoses_available,
|
| 33 |
+
is_torch_available,
|
| 34 |
+
logging,
|
| 35 |
+
requires_backends,
|
| 36 |
+
strtobool,
|
| 37 |
+
torch_only_method,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
if is_sacremoses_available():
|
| 42 |
+
import sacremoses as sm
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
if is_torch_available():
|
| 46 |
+
import torch
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
logger = logging.get_logger(__name__)
|
| 50 |
+
|
| 51 |
+
VOCAB_FILES_NAMES = {
|
| 52 |
+
"pretrained_vocab_file": "vocab.pkl",
|
| 53 |
+
"pretrained_vocab_file_torch": "vocab.bin",
|
| 54 |
+
"vocab_file": "vocab.txt",
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
PRETRAINED_CORPUS_ARCHIVE_MAP = {
|
| 59 |
+
"transfo-xl/transfo-xl-wt103": "https://huggingface.co/transfo-xl/transfo-xl-wt103/resolve/main/corpus.bin",
|
| 60 |
+
}
|
| 61 |
+
CORPUS_NAME = "corpus.bin"
|
| 62 |
+
|
| 63 |
+
MATCH_NUMBERS = r"(?<=\d)[,.](?=\d)", r" @\g<0>@ "
|
| 64 |
+
DETOKENIZE_NUMBERS = [(r" @\,@ ", r","), (r" @\.@ ", r".")]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def tokenize_numbers(text_array: List[str]) -> List[str]:
|
| 68 |
+
"""
|
| 69 |
+
Splits large comma-separated numbers and floating point values. This is done by replacing commas with ' @,@ ' and
|
| 70 |
+
dots with ' @.@ '.
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
text_array: An already tokenized text as list.
|
| 74 |
+
|
| 75 |
+
Returns:
|
| 76 |
+
A list of strings with tokenized numbers.
|
| 77 |
+
|
| 78 |
+
Example:
|
| 79 |
+
|
| 80 |
+
```python
|
| 81 |
+
>>> tokenize_numbers(["$", "5,000", "1.73", "m"])
|
| 82 |
+
['$', '5', '@,@', '000', '1', '@.@', '73', 'm']
|
| 83 |
+
```"""
|
| 84 |
+
tokenized = []
|
| 85 |
+
for i in range(len(text_array)):
|
| 86 |
+
reg, sub = MATCH_NUMBERS
|
| 87 |
+
replaced = re.sub(reg, sub, text_array[i]).split()
|
| 88 |
+
tokenized.extend(replaced)
|
| 89 |
+
|
| 90 |
+
return tokenized
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def detokenize_numbers(text: str) -> str:
|
| 94 |
+
"""
|
| 95 |
+
Inverts the operation of *tokenize_numbers*. This is replacing ' @,@ ' and ' @.@' by ',' and '.'.
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
text: A string where the number should be detokenized.
|
| 99 |
+
|
| 100 |
+
Returns:
|
| 101 |
+
A detokenized string.
|
| 102 |
+
|
| 103 |
+
Example:
|
| 104 |
+
|
| 105 |
+
```python
|
| 106 |
+
>>> detokenize_numbers("$ 5 @,@ 000 1 @.@ 73 m")
|
| 107 |
+
'$ 5,000 1.73 m'
|
| 108 |
+
```"""
|
| 109 |
+
for reg, sub in DETOKENIZE_NUMBERS:
|
| 110 |
+
text = re.sub(reg, sub, text)
|
| 111 |
+
return text
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class TransfoXLTokenizer(PreTrainedTokenizer):
|
| 115 |
+
"""
|
| 116 |
+
Construct a Transformer-XL tokenizer adapted from Vocab class in [the original
|
| 117 |
+
code](https://github.com/kimiyoung/transformer-xl). The Transformer-XL tokenizer is a word-level tokenizer (no
|
| 118 |
+
sub-word tokenization).
|
| 119 |
+
|
| 120 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 121 |
+
this superclass for more information regarding those methods.
|
| 122 |
+
|
| 123 |
+
Args:
|
| 124 |
+
special (`List[str]`, *optional*):
|
| 125 |
+
A list of special tokens (to be treated by the original implementation of this tokenizer).
|
| 126 |
+
min_freq (`int`, *optional*, defaults to 0):
|
| 127 |
+
The minimum number of times a token has to be present in order to be kept in the vocabulary (otherwise it
|
| 128 |
+
will be mapped to `unk_token`).
|
| 129 |
+
max_size (`int`, *optional*):
|
| 130 |
+
The maximum size of the vocabulary. If left unset, it will default to the size of the vocabulary found
|
| 131 |
+
after excluding the tokens according to the `min_freq` rule.
|
| 132 |
+
lower_case (`bool`, *optional*, defaults to `False`):
|
| 133 |
+
Whether or not to lowercase the input when tokenizing.
|
| 134 |
+
delimiter (`str`, *optional*):
|
| 135 |
+
The delimiter used between tokens.
|
| 136 |
+
vocab_file (`str`, *optional*):
|
| 137 |
+
File containing the vocabulary (from the original implementation).
|
| 138 |
+
pretrained_vocab_file (`str`, *optional*):
|
| 139 |
+
File containing the vocabulary as saved with the `save_pretrained()` method.
|
| 140 |
+
never_split (`List[str]`, *optional*):
|
| 141 |
+
List of tokens that should never be split. If no list is specified, will simply use the existing special
|
| 142 |
+
tokens.
|
| 143 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 144 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 145 |
+
token instead.
|
| 146 |
+
eos_token (`str`, *optional*, defaults to `"<eos>"`):
|
| 147 |
+
The end of sequence token.
|
| 148 |
+
additional_special_tokens (`List[str]`, *optional*, defaults to `['<formula>']`):
|
| 149 |
+
A list of additional special tokens (for the HuggingFace functionality).
|
| 150 |
+
language (`str`, *optional*, defaults to `"en"`):
|
| 151 |
+
The language of this tokenizer (used for mose preprocessing).
|
| 152 |
+
"""
|
| 153 |
+
|
| 154 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 155 |
+
model_input_names = ["input_ids"]
|
| 156 |
+
|
| 157 |
+
def __init__(
|
| 158 |
+
self,
|
| 159 |
+
special=None,
|
| 160 |
+
min_freq=0,
|
| 161 |
+
max_size=None,
|
| 162 |
+
lower_case=False,
|
| 163 |
+
delimiter=None,
|
| 164 |
+
vocab_file=None,
|
| 165 |
+
pretrained_vocab_file: str = None,
|
| 166 |
+
never_split=None,
|
| 167 |
+
unk_token="<unk>",
|
| 168 |
+
eos_token="<eos>",
|
| 169 |
+
additional_special_tokens=["<formula>"],
|
| 170 |
+
language="en",
|
| 171 |
+
**kwargs,
|
| 172 |
+
):
|
| 173 |
+
logger.error(
|
| 174 |
+
"`TransfoXL` was deprecated due to security issues linked to `pickle.load` in `TransfoXLTokenizer`. "
|
| 175 |
+
"See more details on this model's documentation page: "
|
| 176 |
+
"`https://github.com/huggingface/transformers/blob/main/docs/source/en/model_doc/transfo-xl.md`."
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
requires_backends(self, "sacremoses")
|
| 180 |
+
if special is None:
|
| 181 |
+
special = []
|
| 182 |
+
self.counter = Counter()
|
| 183 |
+
self.special = special
|
| 184 |
+
self.min_freq = min_freq
|
| 185 |
+
self.max_size = max_size
|
| 186 |
+
self.lower_case = lower_case
|
| 187 |
+
self.delimiter = delimiter
|
| 188 |
+
self.vocab_file = vocab_file
|
| 189 |
+
self.punctuation_symbols = '!"#$%&()*+,-./\\:;<=>?@[\\]^_`{|}~'
|
| 190 |
+
self.punction_without_space_before_pattern = re.compile(rf"[^\s][{self.punctuation_symbols}]")
|
| 191 |
+
self.punctuation_with_space_around_pattern = self._compile_space_around_punctuation_pattern()
|
| 192 |
+
self.language = language
|
| 193 |
+
self.moses_punct_normalizer = sm.MosesPunctNormalizer(language)
|
| 194 |
+
self.moses_tokenizer = sm.MosesTokenizer(language)
|
| 195 |
+
self.moses_detokenizer = sm.MosesDetokenizer(language)
|
| 196 |
+
self.idx2sym = []
|
| 197 |
+
self.sym2idx = OrderedDict()
|
| 198 |
+
# This try... catch... is not beautiful but honestly this tokenizer was not made to be used
|
| 199 |
+
# in a library like ours, at all.
|
| 200 |
+
try:
|
| 201 |
+
vocab_dict = None
|
| 202 |
+
if pretrained_vocab_file is not None:
|
| 203 |
+
# Priority on pickle files (support PyTorch and TF)
|
| 204 |
+
if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
|
| 205 |
+
raise ValueError(
|
| 206 |
+
"This part uses `pickle.load` which is insecure and will execute arbitrary code that is "
|
| 207 |
+
"potentially malicious. It's recommended to never unpickle data that could have come from an "
|
| 208 |
+
"untrusted source, or that could have been tampered with. If you already verified the pickle "
|
| 209 |
+
"data and decided to use it, you can set the environment variable "
|
| 210 |
+
"`TRUST_REMOTE_CODE` to `True` to allow it."
|
| 211 |
+
)
|
| 212 |
+
with open(pretrained_vocab_file, "rb") as f:
|
| 213 |
+
vocab_dict = pickle.load(f)
|
| 214 |
+
|
| 215 |
+
# Loading a torch-saved transfo-xl vocab dict with pickle results in an integer
|
| 216 |
+
# Entering this if statement means that we tried to load a torch-saved file with pickle, and we failed.
|
| 217 |
+
# We therefore load it with torch, if it's available.
|
| 218 |
+
if isinstance(vocab_dict, int):
|
| 219 |
+
if not is_torch_available():
|
| 220 |
+
raise ImportError(
|
| 221 |
+
"Not trying to load dict with PyTorch as you need to install pytorch to load "
|
| 222 |
+
"from a PyTorch pretrained vocabulary, "
|
| 223 |
+
"or activate it with environment variables USE_TORCH=1 and USE_TF=0."
|
| 224 |
+
)
|
| 225 |
+
vocab_dict = torch.load(pretrained_vocab_file, weights_only=True)
|
| 226 |
+
|
| 227 |
+
if vocab_dict is not None:
|
| 228 |
+
for key, value in vocab_dict.items():
|
| 229 |
+
if key not in self.__dict__ or key in ["sym2idx", "idx2sym"]:
|
| 230 |
+
self.__dict__[key] = value
|
| 231 |
+
elif vocab_file is not None:
|
| 232 |
+
self.build_vocab()
|
| 233 |
+
|
| 234 |
+
except Exception as e:
|
| 235 |
+
raise ValueError(
|
| 236 |
+
f"Unable to parse file {pretrained_vocab_file}. Unknown format. "
|
| 237 |
+
"If you tried to load a model saved through TransfoXLTokenizerFast, "
|
| 238 |
+
"please note they are not compatible."
|
| 239 |
+
) from e
|
| 240 |
+
|
| 241 |
+
if vocab_file is not None:
|
| 242 |
+
self.build_vocab()
|
| 243 |
+
|
| 244 |
+
super().__init__(
|
| 245 |
+
special=special,
|
| 246 |
+
min_freq=min_freq,
|
| 247 |
+
max_size=max_size,
|
| 248 |
+
lower_case=lower_case,
|
| 249 |
+
delimiter=delimiter,
|
| 250 |
+
vocab_file=vocab_file,
|
| 251 |
+
pretrained_vocab_file=pretrained_vocab_file,
|
| 252 |
+
never_split=never_split,
|
| 253 |
+
unk_token=unk_token,
|
| 254 |
+
eos_token=eos_token,
|
| 255 |
+
additional_special_tokens=additional_special_tokens,
|
| 256 |
+
language=language,
|
| 257 |
+
**kwargs,
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
# these are not required to initialize the parent class as only used when tokenizing.
|
| 261 |
+
if never_split is None:
|
| 262 |
+
never_split = self.all_special_tokens
|
| 263 |
+
self.never_split = never_split
|
| 264 |
+
|
| 265 |
+
@property
|
| 266 |
+
def do_lower_case(self):
|
| 267 |
+
return self.lower_case
|
| 268 |
+
|
| 269 |
+
def _compile_space_around_punctuation_pattern(self):
|
| 270 |
+
look_ahead_for_special_token = f"(?=[{self.punctuation_symbols}])"
|
| 271 |
+
look_ahead_to_match_all_except_space = r"(?=[^\s])"
|
| 272 |
+
return re.compile(r"" + look_ahead_for_special_token + look_ahead_to_match_all_except_space)
|
| 273 |
+
|
| 274 |
+
def count_file(self, path, verbose=False, add_eos=False):
|
| 275 |
+
if verbose:
|
| 276 |
+
logger.info(f"counting file {path} ...")
|
| 277 |
+
assert os.path.exists(path), f"Input file {path} not found"
|
| 278 |
+
|
| 279 |
+
sents = []
|
| 280 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 281 |
+
for idx, line in enumerate(f):
|
| 282 |
+
if verbose and idx > 0 and idx % 500000 == 0:
|
| 283 |
+
logger.info(f" line {idx}")
|
| 284 |
+
symbols = self.tokenize(line, add_eos=add_eos)
|
| 285 |
+
self.counter.update(symbols)
|
| 286 |
+
sents.append(symbols)
|
| 287 |
+
|
| 288 |
+
return sents
|
| 289 |
+
|
| 290 |
+
def count_sents(self, sents, verbose=False):
|
| 291 |
+
"""
|
| 292 |
+
sents : a list of sentences, each a list of tokenized symbols
|
| 293 |
+
"""
|
| 294 |
+
if verbose:
|
| 295 |
+
logger.info(f"counting {len(sents)} sents ...")
|
| 296 |
+
for idx, symbols in enumerate(sents):
|
| 297 |
+
if verbose and idx > 0 and idx % 500000 == 0:
|
| 298 |
+
logger.info(f" line {idx}")
|
| 299 |
+
self.counter.update(symbols)
|
| 300 |
+
|
| 301 |
+
def _build_from_file(self, vocab_file):
|
| 302 |
+
self.idx2sym = []
|
| 303 |
+
self.sym2idx = OrderedDict()
|
| 304 |
+
|
| 305 |
+
with open(vocab_file, "r", encoding="utf-8") as f:
|
| 306 |
+
for line in f:
|
| 307 |
+
symb = line.strip().split()[0]
|
| 308 |
+
self.add_symbol(symb)
|
| 309 |
+
if "<UNK>" in self.sym2idx:
|
| 310 |
+
self.unk_idx = self.sym2idx["<UNK>"]
|
| 311 |
+
elif "<unk>" in self.sym2idx:
|
| 312 |
+
self.unk_idx = self.sym2idx["<unk>"]
|
| 313 |
+
else:
|
| 314 |
+
raise ValueError("Token not in vocabulary and no <unk> token in vocabulary for replacement.")
|
| 315 |
+
|
| 316 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 317 |
+
if os.path.isdir(save_directory):
|
| 318 |
+
vocab_file = os.path.join(
|
| 319 |
+
save_directory,
|
| 320 |
+
(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["pretrained_vocab_file"],
|
| 321 |
+
)
|
| 322 |
+
else:
|
| 323 |
+
vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
|
| 324 |
+
with open(vocab_file, "wb") as f:
|
| 325 |
+
pickle.dump(self.__dict__, f)
|
| 326 |
+
return (vocab_file,)
|
| 327 |
+
|
| 328 |
+
def build_vocab(self):
|
| 329 |
+
if self.vocab_file:
|
| 330 |
+
logger.info(f"building vocab from {self.vocab_file}")
|
| 331 |
+
self._build_from_file(self.vocab_file)
|
| 332 |
+
logger.info(f"Final vocab size {len(self.sym2idx)}")
|
| 333 |
+
else:
|
| 334 |
+
logger.info(f"building vocab with min_freq={self.min_freq}, max_size={self.max_size}")
|
| 335 |
+
self.idx2sym = []
|
| 336 |
+
self.sym2idx = OrderedDict()
|
| 337 |
+
|
| 338 |
+
for sym in self.special:
|
| 339 |
+
self.add_special(sym)
|
| 340 |
+
|
| 341 |
+
for sym, cnt in self.counter.most_common(self.max_size):
|
| 342 |
+
if cnt < self.min_freq:
|
| 343 |
+
break
|
| 344 |
+
self.add_symbol(sym)
|
| 345 |
+
|
| 346 |
+
logger.info(f"Final vocab size {len(self.sym2idx)} from {len(self.counter)} unique tokens")
|
| 347 |
+
|
| 348 |
+
@torch_only_method
|
| 349 |
+
def encode_file(self, path, ordered=False, verbose=False, add_eos=True, add_double_eos=False):
|
| 350 |
+
if verbose:
|
| 351 |
+
logger.info(f"encoding file {path} ...")
|
| 352 |
+
assert os.path.exists(path), f"Output file {path} not found"
|
| 353 |
+
encoded = []
|
| 354 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 355 |
+
for idx, line in enumerate(f):
|
| 356 |
+
if verbose and idx > 0 and idx % 500000 == 0:
|
| 357 |
+
logger.info(f" line {idx}")
|
| 358 |
+
symbols = self.tokenize(line, add_eos=add_eos, add_double_eos=add_double_eos)
|
| 359 |
+
encoded.append(self.convert_to_tensor(symbols))
|
| 360 |
+
|
| 361 |
+
if ordered:
|
| 362 |
+
encoded = torch.cat(encoded)
|
| 363 |
+
|
| 364 |
+
return encoded
|
| 365 |
+
|
| 366 |
+
@torch_only_method
|
| 367 |
+
def encode_sents(self, sents, ordered=False, verbose=False):
|
| 368 |
+
if verbose:
|
| 369 |
+
logger.info(f"encoding {len(sents)} sents ...")
|
| 370 |
+
encoded = []
|
| 371 |
+
for idx, symbols in enumerate(sents):
|
| 372 |
+
if verbose and idx > 0 and idx % 500000 == 0:
|
| 373 |
+
logger.info(f" line {idx}")
|
| 374 |
+
encoded.append(self.convert_to_tensor(symbols))
|
| 375 |
+
|
| 376 |
+
if ordered:
|
| 377 |
+
encoded = torch.cat(encoded)
|
| 378 |
+
|
| 379 |
+
return encoded
|
| 380 |
+
|
| 381 |
+
def add_special(self, sym):
|
| 382 |
+
if sym not in self.sym2idx:
|
| 383 |
+
self.idx2sym.append(sym)
|
| 384 |
+
self.sym2idx[sym] = len(self.idx2sym) - 1
|
| 385 |
+
setattr(self, f"{sym.strip('<>')}_idx", self.sym2idx[sym])
|
| 386 |
+
|
| 387 |
+
def add_symbol(self, sym):
|
| 388 |
+
if sym not in self.sym2idx:
|
| 389 |
+
self.idx2sym.append(sym)
|
| 390 |
+
self.sym2idx[sym] = len(self.idx2sym) - 1
|
| 391 |
+
|
| 392 |
+
def move_added_token(self, token: str, target_idx: int):
|
| 393 |
+
"""
|
| 394 |
+
Moves an added token to a specific position in the vocab. This method should be used when resizing an embedding
|
| 395 |
+
layer other than the last one in the `AdaptiveEmbedding` in order to move the token in the tokenizer from the
|
| 396 |
+
default position (at the very end) to the desired one.
|
| 397 |
+
|
| 398 |
+
Args:
|
| 399 |
+
token: The token to move to a specific position in the vocab.
|
| 400 |
+
target_idx: The position where the token should be moved to.
|
| 401 |
+
"""
|
| 402 |
+
assert token in self.added_tokens_encoder, "Token which should be moved has to be an added token"
|
| 403 |
+
assert token not in self.idx2sym, "Token which should be moved is already in vocab"
|
| 404 |
+
|
| 405 |
+
# Insert sym into vocab
|
| 406 |
+
self.idx2sym.insert(target_idx, token)
|
| 407 |
+
self.sym2idx[token] = target_idx
|
| 408 |
+
|
| 409 |
+
# Shift following indices in sym2idx
|
| 410 |
+
for idx in range(target_idx + 1, len(self.idx2sym)):
|
| 411 |
+
current_sym = self.idx2sym[idx]
|
| 412 |
+
self.sym2idx[current_sym] = idx
|
| 413 |
+
|
| 414 |
+
# Delete token from added_tokens
|
| 415 |
+
old_index = self._added_tokens_encoder.pop(token)
|
| 416 |
+
self._added_tokens_decoder.pop(old_index)
|
| 417 |
+
|
| 418 |
+
def moses_punct_norm(self, text):
|
| 419 |
+
return self.moses_punct_normalizer.normalize(text)
|
| 420 |
+
|
| 421 |
+
def moses_tokenize(self, text):
|
| 422 |
+
return self.moses_tokenizer.tokenize(
|
| 423 |
+
text, aggressive_dash_splits=True, return_str=False, escape=False, protected_patterns=self.never_split
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
def moses_pipeline(self, text: str) -> List[str]:
|
| 427 |
+
"""
|
| 428 |
+
Does basic tokenization using [`sacremoses.MosesPunctNormalizer`] and [`sacremoses.MosesTokenizer`] with
|
| 429 |
+
*aggressive_dash_splits=True* (see [`sacremoses.tokenize.MosesTokenizer.tokenize`]). Additionally, large
|
| 430 |
+
comma-separated numbers and floating point values are split. E.g. "23,000 people are 1.80m tall" -> "23 @,@ 000
|
| 431 |
+
people are 1 @.@ 80m tall"
|
| 432 |
+
|
| 433 |
+
Args:
|
| 434 |
+
text: Text to be tokenize
|
| 435 |
+
|
| 436 |
+
Returns:
|
| 437 |
+
A list of tokenized string
|
| 438 |
+
|
| 439 |
+
Example:
|
| 440 |
+
|
| 441 |
+
```python
|
| 442 |
+
>>> tokenizer = TransfoXLTokenizer.from_pretrained("transfo-xl/transfo-xl-wt103")
|
| 443 |
+
>>> tokenizer.moses_pipeline("23,000 people are 1.80 m tall")
|
| 444 |
+
['23', '@,@', '000', 'people', 'are', '1', '@.@', '80', 'm', 'tall']
|
| 445 |
+
```"""
|
| 446 |
+
text = self.moses_punct_norm(text)
|
| 447 |
+
text = self.moses_tokenize(text)
|
| 448 |
+
text = tokenize_numbers(text)
|
| 449 |
+
return text
|
| 450 |
+
|
| 451 |
+
def _convert_id_to_token(self, idx):
|
| 452 |
+
"""Converts an id in a token (BPE) using the vocab."""
|
| 453 |
+
assert 0 <= idx < len(self), f"Index {idx} out of vocabulary range"
|
| 454 |
+
return self.idx2sym[idx]
|
| 455 |
+
|
| 456 |
+
def _convert_token_to_id(self, sym):
|
| 457 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 458 |
+
if sym in self.sym2idx:
|
| 459 |
+
return self.sym2idx[sym]
|
| 460 |
+
else:
|
| 461 |
+
# logger.info(f'encounter unk {sym}')
|
| 462 |
+
# assert '<eos>' not in sym
|
| 463 |
+
if hasattr(self, "unk_idx"):
|
| 464 |
+
return self.sym2idx.get(sym, self.unk_idx)
|
| 465 |
+
# Backward compatibility with pre-trained models
|
| 466 |
+
elif "<unk>" in self.sym2idx:
|
| 467 |
+
return self.sym2idx["<unk>"]
|
| 468 |
+
elif "<UNK>" in self.sym2idx:
|
| 469 |
+
return self.sym2idx["<UNK>"]
|
| 470 |
+
else:
|
| 471 |
+
raise ValueError("Token not in vocabulary and no <unk> token in vocabulary for replacement.")
|
| 472 |
+
|
| 473 |
+
def convert_tokens_to_string(self, tokens):
|
| 474 |
+
"""
|
| 475 |
+
Converts a sequence of tokens (string) in a single string. Additionally, the split numbers are converted back
|
| 476 |
+
into it's original form.
|
| 477 |
+
"""
|
| 478 |
+
out_string = self.moses_detokenizer.detokenize(tokens)
|
| 479 |
+
return detokenize_numbers(out_string).strip()
|
| 480 |
+
|
| 481 |
+
@torch_only_method
|
| 482 |
+
def convert_to_tensor(self, symbols):
|
| 483 |
+
return torch.LongTensor(self.convert_tokens_to_ids(symbols))
|
| 484 |
+
|
| 485 |
+
@property
|
| 486 |
+
def vocab_size(self):
|
| 487 |
+
return len(self.idx2sym)
|
| 488 |
+
|
| 489 |
+
def get_vocab(self):
|
| 490 |
+
vocab = self.sym2idx.copy()
|
| 491 |
+
vocab.update(self.added_tokens_encoder)
|
| 492 |
+
return vocab
|
| 493 |
+
|
| 494 |
+
def _tokenize(self, line, add_eos=False, add_double_eos=False):
|
| 495 |
+
line = line.strip()
|
| 496 |
+
# convert to lower case
|
| 497 |
+
if self.lower_case:
|
| 498 |
+
line = line.lower()
|
| 499 |
+
|
| 500 |
+
# empty delimiter '' will evaluate False
|
| 501 |
+
if self.delimiter == "":
|
| 502 |
+
symbols = line
|
| 503 |
+
else:
|
| 504 |
+
symbols = self.moses_pipeline(line)
|
| 505 |
+
|
| 506 |
+
if add_double_eos: # lm1b
|
| 507 |
+
return ["<S>"] + symbols + ["<S>"]
|
| 508 |
+
elif add_eos:
|
| 509 |
+
return symbols + ["<eos>"]
|
| 510 |
+
else:
|
| 511 |
+
return symbols
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
class LMOrderedIterator:
|
| 515 |
+
def __init__(self, data, bsz, bptt, device="cpu", ext_len=None):
|
| 516 |
+
"""
|
| 517 |
+
data -- LongTensor -- the LongTensor is strictly ordered
|
| 518 |
+
"""
|
| 519 |
+
self.bsz = bsz
|
| 520 |
+
self.bptt = bptt
|
| 521 |
+
self.ext_len = ext_len if ext_len is not None else 0
|
| 522 |
+
|
| 523 |
+
self.device = device
|
| 524 |
+
|
| 525 |
+
# Work out how cleanly we can divide the dataset into bsz parts.
|
| 526 |
+
self.n_step = data.size(0) // bsz
|
| 527 |
+
|
| 528 |
+
# Trim off any extra elements that wouldn't cleanly fit (remainders).
|
| 529 |
+
data = data.narrow(0, 0, self.n_step * bsz)
|
| 530 |
+
|
| 531 |
+
# Evenly divide the data across the bsz batches.
|
| 532 |
+
self.data = data.view(bsz, -1).t().contiguous().to(device)
|
| 533 |
+
|
| 534 |
+
# Number of mini-batches
|
| 535 |
+
self.n_batch = (self.n_step + self.bptt - 1) // self.bptt
|
| 536 |
+
|
| 537 |
+
def get_batch(self, i, bptt=None):
|
| 538 |
+
if bptt is None:
|
| 539 |
+
bptt = self.bptt
|
| 540 |
+
seq_len = min(bptt, self.data.size(0) - 1 - i)
|
| 541 |
+
|
| 542 |
+
end_idx = i + seq_len
|
| 543 |
+
beg_idx = max(0, i - self.ext_len)
|
| 544 |
+
|
| 545 |
+
data = self.data[beg_idx:end_idx]
|
| 546 |
+
target = self.data[i + 1 : i + 1 + seq_len]
|
| 547 |
+
|
| 548 |
+
data_out = data.transpose(0, 1).contiguous().to(self.device)
|
| 549 |
+
target_out = target.transpose(0, 1).contiguous().to(self.device)
|
| 550 |
+
|
| 551 |
+
return data_out, target_out, seq_len
|
| 552 |
+
|
| 553 |
+
def get_fixlen_iter(self, start=0):
|
| 554 |
+
for i in range(start, self.data.size(0) - 1, self.bptt):
|
| 555 |
+
yield self.get_batch(i)
|
| 556 |
+
|
| 557 |
+
def get_varlen_iter(self, start=0, std=5, min_len=5, max_deviation=3):
|
| 558 |
+
max_len = self.bptt + max_deviation * std
|
| 559 |
+
i = start
|
| 560 |
+
while True:
|
| 561 |
+
bptt = self.bptt if np.random.random() < 0.95 else self.bptt / 2.0
|
| 562 |
+
bptt = min(max_len, max(min_len, int(np.random.normal(bptt, std))))
|
| 563 |
+
data, target, seq_len = self.get_batch(i, bptt)
|
| 564 |
+
i += seq_len
|
| 565 |
+
yield data, target, seq_len
|
| 566 |
+
if i >= self.data.size(0) - 2:
|
| 567 |
+
break
|
| 568 |
+
|
| 569 |
+
def __iter__(self):
|
| 570 |
+
return self.get_fixlen_iter()
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
class LMShuffledIterator:
|
| 574 |
+
def __init__(self, data, bsz, bptt, device="cpu", ext_len=None, shuffle=False):
|
| 575 |
+
"""
|
| 576 |
+
data -- list[LongTensor] -- there is no order among the LongTensors
|
| 577 |
+
"""
|
| 578 |
+
self.data = data
|
| 579 |
+
|
| 580 |
+
self.bsz = bsz
|
| 581 |
+
self.bptt = bptt
|
| 582 |
+
self.ext_len = ext_len if ext_len is not None else 0
|
| 583 |
+
|
| 584 |
+
self.device = device
|
| 585 |
+
self.shuffle = shuffle
|
| 586 |
+
|
| 587 |
+
def get_sent_stream(self):
|
| 588 |
+
# index iterator
|
| 589 |
+
epoch_indices = np.random.permutation(len(self.data)) if self.shuffle else np.array(range(len(self.data)))
|
| 590 |
+
|
| 591 |
+
# sentence iterator
|
| 592 |
+
for idx in epoch_indices:
|
| 593 |
+
yield self.data[idx]
|
| 594 |
+
|
| 595 |
+
@torch_only_method
|
| 596 |
+
def stream_iterator(self, sent_stream):
|
| 597 |
+
# streams for each data in the batch
|
| 598 |
+
streams = [None] * self.bsz
|
| 599 |
+
|
| 600 |
+
data = torch.LongTensor(self.bptt, self.bsz)
|
| 601 |
+
target = torch.LongTensor(self.bptt, self.bsz)
|
| 602 |
+
|
| 603 |
+
n_retain = 0
|
| 604 |
+
|
| 605 |
+
while True:
|
| 606 |
+
# data : [n_retain+bptt x bsz]
|
| 607 |
+
# target : [bptt x bsz]
|
| 608 |
+
data[n_retain:].fill_(-1)
|
| 609 |
+
target.fill_(-1)
|
| 610 |
+
|
| 611 |
+
valid_batch = True
|
| 612 |
+
|
| 613 |
+
for i in range(self.bsz):
|
| 614 |
+
n_filled = 0
|
| 615 |
+
try:
|
| 616 |
+
while n_filled < self.bptt:
|
| 617 |
+
if streams[i] is None or len(streams[i]) <= 1:
|
| 618 |
+
streams[i] = next(sent_stream)
|
| 619 |
+
# number of new tokens to fill in
|
| 620 |
+
n_new = min(len(streams[i]) - 1, self.bptt - n_filled)
|
| 621 |
+
# first n_retain tokens are retained from last batch
|
| 622 |
+
data[n_retain + n_filled : n_retain + n_filled + n_new, i] = streams[i][:n_new]
|
| 623 |
+
target[n_filled : n_filled + n_new, i] = streams[i][1 : n_new + 1]
|
| 624 |
+
streams[i] = streams[i][n_new:]
|
| 625 |
+
n_filled += n_new
|
| 626 |
+
except StopIteration:
|
| 627 |
+
valid_batch = False
|
| 628 |
+
break
|
| 629 |
+
|
| 630 |
+
if not valid_batch:
|
| 631 |
+
return
|
| 632 |
+
|
| 633 |
+
data_out = data.transpose(0, 1).contiguous().to(self.device)
|
| 634 |
+
target_out = target.transpose(0, 1).contiguous().to(self.device)
|
| 635 |
+
|
| 636 |
+
yield data_out, target_out, self.bptt
|
| 637 |
+
|
| 638 |
+
n_retain = min(data.size(0), self.ext_len)
|
| 639 |
+
if n_retain > 0:
|
| 640 |
+
data[:n_retain] = data[-n_retain:]
|
| 641 |
+
data.resize_(n_retain + self.bptt, data.size(1))
|
| 642 |
+
|
| 643 |
+
def __iter__(self):
|
| 644 |
+
# sent_stream is an iterator
|
| 645 |
+
sent_stream = self.get_sent_stream()
|
| 646 |
+
|
| 647 |
+
for batch in self.stream_iterator(sent_stream):
|
| 648 |
+
yield batch
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
class LMMultiFileIterator(LMShuffledIterator):
|
| 652 |
+
def __init__(self, paths, vocab, bsz, bptt, device="cpu", ext_len=None, shuffle=False):
|
| 653 |
+
self.paths = paths
|
| 654 |
+
self.vocab = vocab
|
| 655 |
+
|
| 656 |
+
self.bsz = bsz
|
| 657 |
+
self.bptt = bptt
|
| 658 |
+
self.ext_len = ext_len if ext_len is not None else 0
|
| 659 |
+
|
| 660 |
+
self.device = device
|
| 661 |
+
self.shuffle = shuffle
|
| 662 |
+
|
| 663 |
+
def get_sent_stream(self, path):
|
| 664 |
+
sents = self.vocab.encode_file(path, add_double_eos=True)
|
| 665 |
+
if self.shuffle:
|
| 666 |
+
np.random.shuffle(sents)
|
| 667 |
+
sent_stream = iter(sents)
|
| 668 |
+
|
| 669 |
+
return sent_stream
|
| 670 |
+
|
| 671 |
+
def __iter__(self):
|
| 672 |
+
if self.shuffle:
|
| 673 |
+
np.random.shuffle(self.paths)
|
| 674 |
+
|
| 675 |
+
for path in self.paths:
|
| 676 |
+
# sent_stream is an iterator
|
| 677 |
+
sent_stream = self.get_sent_stream(path)
|
| 678 |
+
for batch in self.stream_iterator(sent_stream):
|
| 679 |
+
yield batch
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
class TransfoXLCorpus:
|
| 683 |
+
@classmethod
|
| 684 |
+
@torch_only_method
|
| 685 |
+
def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs):
|
| 686 |
+
"""
|
| 687 |
+
Instantiate a pre-processed corpus.
|
| 688 |
+
"""
|
| 689 |
+
vocab = TransfoXLTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
|
| 690 |
+
is_local = os.path.isdir(pretrained_model_name_or_path)
|
| 691 |
+
# redirect to the cache, if necessary
|
| 692 |
+
try:
|
| 693 |
+
resolved_corpus_file = cached_file(pretrained_model_name_or_path, CORPUS_NAME, cache_dir=cache_dir)
|
| 694 |
+
except EnvironmentError:
|
| 695 |
+
logger.error(
|
| 696 |
+
f"Corpus '{pretrained_model_name_or_path}' was not found in corpus list"
|
| 697 |
+
f" ({', '.join(PRETRAINED_CORPUS_ARCHIVE_MAP.keys())}. We assumed '{pretrained_model_name_or_path}'"
|
| 698 |
+
f" was a path or url but couldn't find files {CORPUS_NAME} at this path or url."
|
| 699 |
+
)
|
| 700 |
+
return None
|
| 701 |
+
if is_local:
|
| 702 |
+
logger.info(f"loading corpus file {resolved_corpus_file}")
|
| 703 |
+
else:
|
| 704 |
+
logger.info(f"loading corpus file {CORPUS_NAME} from cache at {resolved_corpus_file}")
|
| 705 |
+
|
| 706 |
+
# Instantiate tokenizer.
|
| 707 |
+
corpus = cls(*inputs, **kwargs)
|
| 708 |
+
corpus_dict = torch.load(resolved_corpus_file, weights_only=True)
|
| 709 |
+
for key, value in corpus_dict.items():
|
| 710 |
+
corpus.__dict__[key] = value
|
| 711 |
+
corpus.vocab = vocab
|
| 712 |
+
if corpus.train is not None:
|
| 713 |
+
corpus.train = torch.tensor(corpus.train, dtype=torch.long)
|
| 714 |
+
if corpus.valid is not None:
|
| 715 |
+
corpus.valid = torch.tensor(corpus.valid, dtype=torch.long)
|
| 716 |
+
if corpus.test is not None:
|
| 717 |
+
corpus.test = torch.tensor(corpus.test, dtype=torch.long)
|
| 718 |
+
return corpus
|
| 719 |
+
|
| 720 |
+
def __init__(self, *args, **kwargs):
|
| 721 |
+
self.vocab = TransfoXLTokenizer(*args, **kwargs)
|
| 722 |
+
self.dataset = None
|
| 723 |
+
self.train = None
|
| 724 |
+
self.valid = None
|
| 725 |
+
self.test = None
|
| 726 |
+
|
| 727 |
+
def build_corpus(self, path, dataset):
|
| 728 |
+
self.dataset = dataset
|
| 729 |
+
|
| 730 |
+
if self.dataset in ["ptb", "wt2", "enwik8", "text8"]:
|
| 731 |
+
self.vocab.count_file(os.path.join(path, "train.txt"))
|
| 732 |
+
self.vocab.count_file(os.path.join(path, "valid.txt"))
|
| 733 |
+
self.vocab.count_file(os.path.join(path, "test.txt"))
|
| 734 |
+
elif self.dataset == "wt103":
|
| 735 |
+
self.vocab.count_file(os.path.join(path, "train.txt"))
|
| 736 |
+
elif self.dataset == "lm1b":
|
| 737 |
+
train_path_pattern = os.path.join(
|
| 738 |
+
path,
|
| 739 |
+
"1-billion-word-language-modeling-benchmark-r13output",
|
| 740 |
+
"training-monolingual.tokenized.shuffled",
|
| 741 |
+
"news.en-*",
|
| 742 |
+
)
|
| 743 |
+
train_paths = glob.glob(train_path_pattern)
|
| 744 |
+
# the vocab will load from file when build_vocab() is called
|
| 745 |
+
|
| 746 |
+
self.vocab.build_vocab()
|
| 747 |
+
|
| 748 |
+
if self.dataset in ["ptb", "wt2", "wt103"]:
|
| 749 |
+
self.train = self.vocab.encode_file(os.path.join(path, "train.txt"), ordered=True)
|
| 750 |
+
self.valid = self.vocab.encode_file(os.path.join(path, "valid.txt"), ordered=True)
|
| 751 |
+
self.test = self.vocab.encode_file(os.path.join(path, "test.txt"), ordered=True)
|
| 752 |
+
elif self.dataset in ["enwik8", "text8"]:
|
| 753 |
+
self.train = self.vocab.encode_file(os.path.join(path, "train.txt"), ordered=True, add_eos=False)
|
| 754 |
+
self.valid = self.vocab.encode_file(os.path.join(path, "valid.txt"), ordered=True, add_eos=False)
|
| 755 |
+
self.test = self.vocab.encode_file(os.path.join(path, "test.txt"), ordered=True, add_eos=False)
|
| 756 |
+
elif self.dataset == "lm1b":
|
| 757 |
+
self.train = train_paths
|
| 758 |
+
self.valid = self.vocab.encode_file(os.path.join(path, "valid.txt"), ordered=False, add_double_eos=True)
|
| 759 |
+
self.test = self.vocab.encode_file(os.path.join(path, "test.txt"), ordered=False, add_double_eos=True)
|
| 760 |
+
|
| 761 |
+
def get_iterator(self, split, *args, **kwargs):
|
| 762 |
+
if split == "train":
|
| 763 |
+
if self.dataset in ["ptb", "wt2", "wt103", "enwik8", "text8"]:
|
| 764 |
+
data_iter = LMOrderedIterator(self.train, *args, **kwargs)
|
| 765 |
+
elif self.dataset == "lm1b":
|
| 766 |
+
kwargs["shuffle"] = True
|
| 767 |
+
data_iter = LMMultiFileIterator(self.train, self.vocab, *args, **kwargs)
|
| 768 |
+
elif split in ["valid", "test"]:
|
| 769 |
+
data = self.valid if split == "valid" else self.test
|
| 770 |
+
if self.dataset in ["ptb", "wt2", "wt103", "enwik8", "text8"]:
|
| 771 |
+
data_iter = LMOrderedIterator(data, *args, **kwargs)
|
| 772 |
+
elif self.dataset == "lm1b":
|
| 773 |
+
data_iter = LMShuffledIterator(data, *args, **kwargs)
|
| 774 |
+
else:
|
| 775 |
+
data_iter = None
|
| 776 |
+
raise ValueError(f"Split not recognized: {split}")
|
| 777 |
+
|
| 778 |
+
return data_iter
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
@torch_only_method
|
| 782 |
+
def get_lm_corpus(datadir, dataset):
|
| 783 |
+
fn = os.path.join(datadir, "cache.pt")
|
| 784 |
+
fn_pickle = os.path.join(datadir, "cache.pkl")
|
| 785 |
+
if os.path.exists(fn):
|
| 786 |
+
logger.info("Loading cached dataset...")
|
| 787 |
+
corpus = torch.load(fn_pickle, weights_only=True)
|
| 788 |
+
elif os.path.exists(fn):
|
| 789 |
+
logger.info("Loading cached dataset from pickle...")
|
| 790 |
+
if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
|
| 791 |
+
raise ValueError(
|
| 792 |
+
"This part uses `pickle.load` which is insecure and will execute arbitrary code that is potentially "
|
| 793 |
+
"malicious. It's recommended to never unpickle data that could have come from an untrusted source, or "
|
| 794 |
+
"that could have been tampered with. If you already verified the pickle data and decided to use it, "
|
| 795 |
+
"you can set the environment variable `TRUST_REMOTE_CODE` to `True` to allow it."
|
| 796 |
+
)
|
| 797 |
+
with open(fn, "rb") as fp:
|
| 798 |
+
corpus = pickle.load(fp)
|
| 799 |
+
else:
|
| 800 |
+
logger.info(f"Producing dataset {dataset}...")
|
| 801 |
+
kwargs = {}
|
| 802 |
+
if dataset in ["wt103", "wt2"]:
|
| 803 |
+
kwargs["special"] = ["<eos>"]
|
| 804 |
+
kwargs["lower_case"] = False
|
| 805 |
+
elif dataset == "ptb":
|
| 806 |
+
kwargs["special"] = ["<eos>"]
|
| 807 |
+
kwargs["lower_case"] = True
|
| 808 |
+
elif dataset == "lm1b":
|
| 809 |
+
kwargs["special"] = []
|
| 810 |
+
kwargs["lower_case"] = False
|
| 811 |
+
kwargs["vocab_file"] = os.path.join(datadir, "1b_word_vocab.txt")
|
| 812 |
+
elif dataset in ["enwik8", "text8"]:
|
| 813 |
+
pass
|
| 814 |
+
|
| 815 |
+
corpus = TransfoXLCorpus(datadir, dataset, **kwargs)
|
| 816 |
+
torch.save(corpus, fn)
|
| 817 |
+
|
| 818 |
+
return corpus
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/tvlt/__init__.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 2023 The HuggingFace 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 |
+
from ....utils import (
|
| 21 |
+
OptionalDependencyNotAvailable,
|
| 22 |
+
_LazyModule,
|
| 23 |
+
is_torch_available,
|
| 24 |
+
is_vision_available,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
_import_structure = {
|
| 29 |
+
"configuration_tvlt": ["TvltConfig"],
|
| 30 |
+
"feature_extraction_tvlt": ["TvltFeatureExtractor"],
|
| 31 |
+
"processing_tvlt": ["TvltProcessor"],
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
try:
|
| 35 |
+
if not is_torch_available():
|
| 36 |
+
raise OptionalDependencyNotAvailable()
|
| 37 |
+
except OptionalDependencyNotAvailable:
|
| 38 |
+
pass
|
| 39 |
+
else:
|
| 40 |
+
_import_structure["modeling_tvlt"] = [
|
| 41 |
+
"TvltModel",
|
| 42 |
+
"TvltForPreTraining",
|
| 43 |
+
"TvltForAudioVisualClassification",
|
| 44 |
+
"TvltPreTrainedModel",
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
if not is_vision_available():
|
| 49 |
+
raise OptionalDependencyNotAvailable()
|
| 50 |
+
except OptionalDependencyNotAvailable:
|
| 51 |
+
pass
|
| 52 |
+
else:
|
| 53 |
+
_import_structure["image_processing_tvlt"] = ["TvltImageProcessor"]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
if TYPE_CHECKING:
|
| 57 |
+
from .configuration_tvlt import TvltConfig
|
| 58 |
+
from .processing_tvlt import TvltProcessor
|
| 59 |
+
from .feature_extraction_tvlt import TvltFeatureExtractor
|
| 60 |
+
|
| 61 |
+
try:
|
| 62 |
+
if not is_torch_available():
|
| 63 |
+
raise OptionalDependencyNotAvailable()
|
| 64 |
+
except OptionalDependencyNotAvailable:
|
| 65 |
+
pass
|
| 66 |
+
else:
|
| 67 |
+
from .modeling_tvlt import (
|
| 68 |
+
TvltForAudioVisualClassification,
|
| 69 |
+
TvltForPreTraining,
|
| 70 |
+
TvltModel,
|
| 71 |
+
TvltPreTrainedModel,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
if not is_vision_available():
|
| 76 |
+
raise OptionalDependencyNotAvailable()
|
| 77 |
+
except OptionalDependencyNotAvailable:
|
| 78 |
+
pass
|
| 79 |
+
else:
|
| 80 |
+
from .image_processing_tvlt import TvltImageProcessor
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
else:
|
| 84 |
+
import sys
|
| 85 |
+
|
| 86 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/tv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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 MURGe-Lab 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 |
+
"""TVLT model configuration"""
|
| 16 |
+
|
| 17 |
+
from ....configuration_utils import PretrainedConfig
|
| 18 |
+
from ....utils import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class TvltConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`TvltModel`]. It is used to instantiate a TVLT
|
| 27 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 28 |
+
defaults will yield a similar configuration to that of the TVLT
|
| 29 |
+
[ZinengTang/tvlt-base](https://huggingface.co/ZinengTang/tvlt-base) architecture.
|
| 30 |
+
|
| 31 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 32 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 36 |
+
The size (resolution) of each image.
|
| 37 |
+
spectrogram_length (`int`, *optional*, defaults to 2048):
|
| 38 |
+
The time length of each audio spectrogram.
|
| 39 |
+
frequency_length (`int`, *optional*, defaults to 128):
|
| 40 |
+
The frequency length of audio spectrogram.
|
| 41 |
+
image_patch_size (`List[int]`, *optional*, defaults to `[16, 16]`):
|
| 42 |
+
The size (resolution) of each image patch.
|
| 43 |
+
audio_patch_size (`List[int]`, *optional*, defaults to `[16, 16]`):
|
| 44 |
+
The size (resolution) of each audio patch.
|
| 45 |
+
num_image_channels (`int`, *optional*, defaults to 3):
|
| 46 |
+
The number of input image channels.
|
| 47 |
+
num_audio_channels (`int`, *optional*, defaults to 1):
|
| 48 |
+
The number of input audio channels.
|
| 49 |
+
num_frames (`int`, *optional*, defaults to 8):
|
| 50 |
+
The maximum number of frames for an input video.
|
| 51 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 52 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 53 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 54 |
+
Number of hidden layers in the Transformer encoder.
|
| 55 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 56 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 57 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 58 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 59 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 60 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 61 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 62 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 63 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 64 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 65 |
+
The dropout ratio for the attention probabilities.
|
| 66 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 67 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 68 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 69 |
+
The epsilon used by the layer normalization layers.
|
| 70 |
+
qkv_bias (`bool`, *optional*, defaults to `True`):
|
| 71 |
+
Whether to add a bias to the queries, keys and values.
|
| 72 |
+
use_mean_pooling (`bool`, *optional*, defaults to `False`):
|
| 73 |
+
Whether to mean pool the final hidden states instead of using the final hidden state of the [CLS] token.
|
| 74 |
+
decoder_num_attention_heads (`int`, *optional*, defaults to 16):
|
| 75 |
+
Number of attention heads for each attention layer in the decoder.
|
| 76 |
+
decoder_hidden_size (`int`, *optional*, defaults to 512):
|
| 77 |
+
Dimensionality of the decoder.
|
| 78 |
+
decoder_num_hidden_layers (`int`, *optional*, defaults to 8):
|
| 79 |
+
Number of hidden layers in the decoder.
|
| 80 |
+
decoder_intermediate_size (`int`, *optional*, defaults to 2048):
|
| 81 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the decoder.
|
| 82 |
+
pixel_mask_ratio (`float`, *optional*, defaults to 0.75):
|
| 83 |
+
Image patch masking ratio.
|
| 84 |
+
audio_mask_ratio (`float`, *optional*, defaults to 0.15):
|
| 85 |
+
Audio patch masking ratio.
|
| 86 |
+
audio_mask_type (`str`, *optional*, defaults to `"frame-level"`):
|
| 87 |
+
Audio patch masking type, choose between "frame-level" and "patch-level".
|
| 88 |
+
task_matching (`bool`, *optional*, defaults to `True`):
|
| 89 |
+
Whether to use vision audio matching task in pretraining.
|
| 90 |
+
task_mae (`bool`, *optional*, defaults to `True`):
|
| 91 |
+
Whether to use the masked auto-encoder (MAE) in pretraining.
|
| 92 |
+
loss_type (`str`, *optional*, defaults to `"classification"`):
|
| 93 |
+
Loss types including regression and classification.
|
| 94 |
+
|
| 95 |
+
Example:
|
| 96 |
+
|
| 97 |
+
```python
|
| 98 |
+
>>> from transformers import TvltConfig, TvltModel
|
| 99 |
+
|
| 100 |
+
>>> # # Initializing a TVLT ZinengTang/tvlt-base style configuration
|
| 101 |
+
>>> configuration = TvltConfig()
|
| 102 |
+
|
| 103 |
+
>>> # # Initializing a model (with random weights) from the ZinengTang/tvlt-base style configuration
|
| 104 |
+
>>> model = TvltModel(configuration)
|
| 105 |
+
|
| 106 |
+
>>> # Accessing the model configuration
|
| 107 |
+
>>> configuration = model.config
|
| 108 |
+
```"""
|
| 109 |
+
|
| 110 |
+
model_type = "tvlt"
|
| 111 |
+
|
| 112 |
+
def __init__(
|
| 113 |
+
self,
|
| 114 |
+
image_size=224,
|
| 115 |
+
spectrogram_length=2048,
|
| 116 |
+
frequency_length=128,
|
| 117 |
+
image_patch_size=[16, 16],
|
| 118 |
+
audio_patch_size=[16, 16],
|
| 119 |
+
num_image_channels=3,
|
| 120 |
+
num_audio_channels=1,
|
| 121 |
+
num_frames=8,
|
| 122 |
+
hidden_size=768,
|
| 123 |
+
num_hidden_layers=12,
|
| 124 |
+
num_attention_heads=12,
|
| 125 |
+
intermediate_size=3072,
|
| 126 |
+
hidden_act="gelu",
|
| 127 |
+
hidden_dropout_prob=0.0,
|
| 128 |
+
attention_probs_dropout_prob=0.0,
|
| 129 |
+
initializer_range=0.02,
|
| 130 |
+
layer_norm_eps=1e-6,
|
| 131 |
+
qkv_bias=True,
|
| 132 |
+
use_mean_pooling=False,
|
| 133 |
+
decoder_num_attention_heads=16,
|
| 134 |
+
decoder_hidden_size=512,
|
| 135 |
+
decoder_num_hidden_layers=8,
|
| 136 |
+
decoder_intermediate_size=2048,
|
| 137 |
+
pixel_mask_ratio=0.75,
|
| 138 |
+
audio_mask_ratio=0.15,
|
| 139 |
+
audio_mask_type="frame-level",
|
| 140 |
+
task_matching=True,
|
| 141 |
+
task_mae=True,
|
| 142 |
+
loss_type="classification",
|
| 143 |
+
**kwargs,
|
| 144 |
+
):
|
| 145 |
+
super().__init__(**kwargs)
|
| 146 |
+
|
| 147 |
+
if audio_mask_type not in ("frame-level", "patch_level"):
|
| 148 |
+
raise ValueError(
|
| 149 |
+
"audio_mask_type must be one of two acceptable strategies - {'frame_level', 'patch-level') "
|
| 150 |
+
f"got {audio_mask_type}"
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
self.image_size = image_size
|
| 154 |
+
self.spectrogram_length = spectrogram_length
|
| 155 |
+
self.frequency_length = frequency_length
|
| 156 |
+
self.image_patch_size = image_patch_size
|
| 157 |
+
self.audio_patch_size = audio_patch_size
|
| 158 |
+
self.num_image_channels = num_image_channels
|
| 159 |
+
self.num_audio_channels = num_audio_channels
|
| 160 |
+
self.num_frames = num_frames
|
| 161 |
+
|
| 162 |
+
self.hidden_size = hidden_size
|
| 163 |
+
self.num_hidden_layers = num_hidden_layers
|
| 164 |
+
self.num_attention_heads = num_attention_heads
|
| 165 |
+
self.intermediate_size = intermediate_size
|
| 166 |
+
self.hidden_act = hidden_act
|
| 167 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 168 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 169 |
+
self.initializer_range = initializer_range
|
| 170 |
+
self.layer_norm_eps = layer_norm_eps
|
| 171 |
+
self.qkv_bias = qkv_bias
|
| 172 |
+
self.use_mean_pooling = use_mean_pooling
|
| 173 |
+
|
| 174 |
+
self.decoder_num_attention_heads = decoder_num_attention_heads
|
| 175 |
+
self.decoder_hidden_size = decoder_hidden_size
|
| 176 |
+
self.decoder_num_hidden_layers = decoder_num_hidden_layers
|
| 177 |
+
self.decoder_intermediate_size = decoder_intermediate_size
|
| 178 |
+
self.pixel_mask_ratio = pixel_mask_ratio
|
| 179 |
+
self.audio_mask_ratio = audio_mask_ratio
|
| 180 |
+
self.audio_mask_type = audio_mask_type
|
| 181 |
+
|
| 182 |
+
self.task_matching = task_matching
|
| 183 |
+
self.task_mae = task_mae
|
| 184 |
+
self.loss_type = loss_type
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/tvlt/feature_extraction_tvlt.py
ADDED
|
@@ -0,0 +1,230 @@
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Feature extractor class for TVLT."""
|
| 16 |
+
|
| 17 |
+
from math import ceil
|
| 18 |
+
from typing import List, Optional, Union
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
from ....audio_utils import mel_filter_bank, spectrogram, window_function
|
| 23 |
+
from ....feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor
|
| 24 |
+
from ....utils import TensorType, logging
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TvltFeatureExtractor(SequenceFeatureExtractor):
|
| 31 |
+
r"""
|
| 32 |
+
Constructs a TVLT audio feature extractor. This feature extractor can be used to prepare audios for the model.
|
| 33 |
+
|
| 34 |
+
This feature extractor inherits from [`FeatureExtractionMixin`] which contains most of the main methods. Users
|
| 35 |
+
should refer to this superclass for more information regarding those methods.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
spectrogram_length (`Dict[str, int]` *optional*, defaults to 2048):
|
| 39 |
+
The time length of each audio spectrogram.
|
| 40 |
+
num_channels (`int` *optional*, defaults to 1):
|
| 41 |
+
Number of audio channels.
|
| 42 |
+
patch_size (`List[int]` *optional*, defaults to `[16, 16]`):
|
| 43 |
+
The patch size of audio patch embedding.
|
| 44 |
+
feature_size (`int`, *optional*, defaults to 128):
|
| 45 |
+
The frequency length of audio spectrogram.
|
| 46 |
+
sampling_rate (`int`, *optional*, defaults to 44100):
|
| 47 |
+
The sampling rate at which the audio files should be digitalized expressed in Hertz (Hz).
|
| 48 |
+
hop_length_to_sampling_rate (`int`, *optional*, defaults to 86):
|
| 49 |
+
Hop length is length of the overlaping windows for the STFT used to obtain the Mel Frequency coefficients.
|
| 50 |
+
For example, with sampling rate 44100, the hop length is 512, with 44100 / 512 = 86
|
| 51 |
+
n_fft (`int`, *optional*, defaults to 2048):
|
| 52 |
+
Size of the Fourier transform.
|
| 53 |
+
padding_value (`float`, *optional*, defaults to 0.0):
|
| 54 |
+
Padding value used to pad the audio. Should correspond to silences.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
model_input_names = ["audio_values", "audio_mask"]
|
| 58 |
+
|
| 59 |
+
def __init__(
|
| 60 |
+
self,
|
| 61 |
+
spectrogram_length=2048,
|
| 62 |
+
num_channels=1,
|
| 63 |
+
patch_size=[16, 16],
|
| 64 |
+
feature_size=128,
|
| 65 |
+
sampling_rate=44100,
|
| 66 |
+
hop_length_to_sampling_rate=86,
|
| 67 |
+
n_fft=2048,
|
| 68 |
+
padding_value=0.0,
|
| 69 |
+
**kwargs,
|
| 70 |
+
):
|
| 71 |
+
super().__init__(
|
| 72 |
+
feature_size=feature_size,
|
| 73 |
+
sampling_rate=sampling_rate,
|
| 74 |
+
padding_value=padding_value,
|
| 75 |
+
**kwargs,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
self.spectrogram_length = spectrogram_length
|
| 79 |
+
self.num_channels = num_channels
|
| 80 |
+
self.patch_size = patch_size
|
| 81 |
+
self.freq_len = feature_size // self.patch_size[1]
|
| 82 |
+
self.n_fft = n_fft
|
| 83 |
+
self.hop_length = sampling_rate // hop_length_to_sampling_rate
|
| 84 |
+
self.sampling_rate = sampling_rate
|
| 85 |
+
self.padding_value = padding_value
|
| 86 |
+
self.mel_filters = mel_filter_bank(
|
| 87 |
+
num_frequency_bins=1 + n_fft // 2,
|
| 88 |
+
num_mel_filters=feature_size,
|
| 89 |
+
min_frequency=0.0,
|
| 90 |
+
max_frequency=22050.0,
|
| 91 |
+
sampling_rate=sampling_rate,
|
| 92 |
+
norm="slaney",
|
| 93 |
+
mel_scale="slaney",
|
| 94 |
+
).T
|
| 95 |
+
|
| 96 |
+
def _np_extract_fbank_features(self, waveform: np.array) -> np.ndarray:
|
| 97 |
+
"""
|
| 98 |
+
Compute the log-mel spectrogram of the provided audio, gives similar results to Whisper's original torch
|
| 99 |
+
implementation with 1e-5 tolerance.
|
| 100 |
+
"""
|
| 101 |
+
log_spec = spectrogram(
|
| 102 |
+
waveform,
|
| 103 |
+
window_function(self.n_fft, "hann"),
|
| 104 |
+
frame_length=self.n_fft,
|
| 105 |
+
hop_length=self.hop_length,
|
| 106 |
+
power=2.0,
|
| 107 |
+
mel_filters=self.mel_filters.T,
|
| 108 |
+
log_mel="dB",
|
| 109 |
+
db_range=80.0,
|
| 110 |
+
)
|
| 111 |
+
log_spec = log_spec[:, :-1]
|
| 112 |
+
log_spec = log_spec - 20.0
|
| 113 |
+
log_spec = np.clip(log_spec / 40.0, -2.0, 0.0) + 1.0
|
| 114 |
+
return log_spec
|
| 115 |
+
|
| 116 |
+
def __call__(
|
| 117 |
+
self,
|
| 118 |
+
raw_speech: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]],
|
| 119 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 120 |
+
return_attention_mask: Optional[bool] = True,
|
| 121 |
+
sampling_rate: Optional[int] = None,
|
| 122 |
+
resample: bool = False,
|
| 123 |
+
mask_audio: bool = False,
|
| 124 |
+
**kwargs,
|
| 125 |
+
) -> BatchFeature:
|
| 126 |
+
"""
|
| 127 |
+
Main method to prepare one or several audio(s) for the model.
|
| 128 |
+
|
| 129 |
+
Args:
|
| 130 |
+
raw_speech (`np.ndarray`, `List[float]`, `List[np.ndarray]`, `List[List[float]]`):
|
| 131 |
+
The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
|
| 132 |
+
values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
|
| 133 |
+
stereo, i.e. single float per timestep.
|
| 134 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 135 |
+
If set, will return tensors instead of list of python integers. Acceptable values are:
|
| 136 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 137 |
+
- `'np'`: Return Numpy `np.ndarray` objects.
|
| 138 |
+
return_attention_mask (`bool`, *optional*, default to `True`):
|
| 139 |
+
Whether to return the attention mask. If left to the default, will return the attention mask according
|
| 140 |
+
to the specific feature_extractor's default. [What are attention masks?](../glossary#attention-mask)
|
| 141 |
+
|
| 142 |
+
<Tip>
|
| 143 |
+
|
| 144 |
+
For TvltTransformer models, `attention_mask` should alwys be passed for batched inference, to avoid
|
| 145 |
+
subtle bugs.
|
| 146 |
+
|
| 147 |
+
</Tip>
|
| 148 |
+
|
| 149 |
+
sampling_rate (`int`, *optional*):
|
| 150 |
+
The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
|
| 151 |
+
`sampling_rate` at the forward call to prevent silent errors and allow automatic speech recognition
|
| 152 |
+
pipeline. Current model supports sampling rate 16000 and 44100.
|
| 153 |
+
resample (`bool`, *optional*, defaults to `False`):
|
| 154 |
+
If the sampling rate is not matched, resample the input audio to match.
|
| 155 |
+
mask_audio (`bool`, *optional*, defaults to `False`):
|
| 156 |
+
Whether or not to mask input audio for MAE task.
|
| 157 |
+
|
| 158 |
+
Returns:
|
| 159 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 160 |
+
|
| 161 |
+
- **audio_values** -- Audio values to be fed to a model, of shape (batch_size, num_channels, height,
|
| 162 |
+
width).
|
| 163 |
+
|
| 164 |
+
- **audio_mask** -- Audio masks to be fed to a model, of shape (batch_size, num_audio_patches).
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
if sampling_rate is not None:
|
| 168 |
+
if sampling_rate != self.sampling_rate:
|
| 169 |
+
raise ValueError(
|
| 170 |
+
"This feature extractor is set to support sampling rate"
|
| 171 |
+
f" of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled"
|
| 172 |
+
f" with {self.sampling_rate} and not {sampling_rate}."
|
| 173 |
+
)
|
| 174 |
+
else:
|
| 175 |
+
logger.warning(
|
| 176 |
+
"It is strongly recommended to pass the `sampling_rate` argument to this function. "
|
| 177 |
+
"Failing to do so can result in silent errors that might be hard to debug."
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
|
| 181 |
+
if is_batched_numpy and len(raw_speech.shape) > 2:
|
| 182 |
+
raise ValueError(f"Only mono-channel audio is supported for input to {self}")
|
| 183 |
+
is_batched = is_batched_numpy or (
|
| 184 |
+
isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list)))
|
| 185 |
+
)
|
| 186 |
+
if is_batched:
|
| 187 |
+
raw_speech = [np.asarray([speech], dtype=np.float32).T for speech in raw_speech]
|
| 188 |
+
elif not is_batched and not isinstance(raw_speech, np.ndarray):
|
| 189 |
+
raw_speech = np.asarray(raw_speech, dtype=np.float32)
|
| 190 |
+
elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
|
| 191 |
+
raw_speech = raw_speech.astype(np.float32)
|
| 192 |
+
# always return batch
|
| 193 |
+
if not is_batched:
|
| 194 |
+
raw_speech = [np.asarray([raw_speech]).T]
|
| 195 |
+
|
| 196 |
+
# Convert audio signals to log mel spectrograms, truncate by time axis
|
| 197 |
+
audio_features = [
|
| 198 |
+
self._np_extract_fbank_features(waveform.squeeze()).T[: self.spectrogram_length] for waveform in raw_speech
|
| 199 |
+
]
|
| 200 |
+
if isinstance(audio_features[0], List):
|
| 201 |
+
audio_features = [np.asarray(feature, dtype=np.float32) for feature in audio_features]
|
| 202 |
+
|
| 203 |
+
# Create audio attention mask
|
| 204 |
+
max_patch_len = max(
|
| 205 |
+
[ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len for feature in audio_features]
|
| 206 |
+
) # The maximum number of audio patches in a batch
|
| 207 |
+
if return_attention_mask:
|
| 208 |
+
audio_mask = [
|
| 209 |
+
(ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [1]
|
| 210 |
+
+ (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [0]
|
| 211 |
+
for feature in audio_features
|
| 212 |
+
]
|
| 213 |
+
audio_mask = np.array(audio_mask).astype(np.float32)
|
| 214 |
+
|
| 215 |
+
# convert into correct format for padding
|
| 216 |
+
max_time_len = max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch
|
| 217 |
+
padded_audio_features = np.ones([len(audio_features), 1, max_time_len, self.feature_size]).astype(np.float32)
|
| 218 |
+
padded_audio_features = padded_audio_features * self.padding_value
|
| 219 |
+
for i in range(len(audio_features)):
|
| 220 |
+
feature = audio_features[i]
|
| 221 |
+
padded_audio_features[i, :, : feature.shape[0], :] = feature
|
| 222 |
+
|
| 223 |
+
# return as BatchFeature
|
| 224 |
+
if return_attention_mask:
|
| 225 |
+
data = {"audio_values": padded_audio_features, "audio_mask": audio_mask}
|
| 226 |
+
else:
|
| 227 |
+
data = {"audio_values": padded_audio_features}
|
| 228 |
+
|
| 229 |
+
encoded_inputs = BatchFeature(data=data, tensor_type=return_tensors)
|
| 230 |
+
return encoded_inputs
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/tvlt/image_processing_tvlt.py
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Image processor class for TVLT."""
|
| 16 |
+
|
| 17 |
+
from typing import Dict, List, Optional, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from ....image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
| 22 |
+
from ....image_transforms import (
|
| 23 |
+
get_resize_output_image_size,
|
| 24 |
+
resize,
|
| 25 |
+
to_channel_dimension_format,
|
| 26 |
+
)
|
| 27 |
+
from ....image_utils import (
|
| 28 |
+
IMAGENET_STANDARD_MEAN,
|
| 29 |
+
IMAGENET_STANDARD_STD,
|
| 30 |
+
ChannelDimension,
|
| 31 |
+
ImageInput,
|
| 32 |
+
PILImageResampling,
|
| 33 |
+
infer_channel_dimension_format,
|
| 34 |
+
is_scaled_image,
|
| 35 |
+
is_valid_image,
|
| 36 |
+
to_numpy_array,
|
| 37 |
+
valid_images,
|
| 38 |
+
validate_kwargs,
|
| 39 |
+
validate_preprocess_arguments,
|
| 40 |
+
)
|
| 41 |
+
from ....utils import TensorType, logging
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
logger = logging.get_logger(__name__)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def make_batched(videos) -> List[List[ImageInput]]:
|
| 48 |
+
if isinstance(videos, (list, tuple)) and isinstance(videos[0], (list, tuple)):
|
| 49 |
+
return videos
|
| 50 |
+
|
| 51 |
+
elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
|
| 52 |
+
videos_dim = np.array(videos[0]).ndim
|
| 53 |
+
if videos_dim == 3:
|
| 54 |
+
return [videos]
|
| 55 |
+
elif videos_dim == 4:
|
| 56 |
+
return videos
|
| 57 |
+
|
| 58 |
+
elif is_valid_image(videos):
|
| 59 |
+
videos_dim = np.array(videos).ndim
|
| 60 |
+
if videos_dim == 3:
|
| 61 |
+
return [[videos]]
|
| 62 |
+
elif videos_dim == 4:
|
| 63 |
+
return [videos]
|
| 64 |
+
elif videos_dim == 5:
|
| 65 |
+
return videos
|
| 66 |
+
|
| 67 |
+
raise ValueError(f"Could not make batched video from {videos}")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class TvltImageProcessor(BaseImageProcessor):
|
| 71 |
+
r"""
|
| 72 |
+
Constructs a TVLT image processor.
|
| 73 |
+
|
| 74 |
+
This processor can be used to prepare either videos or images for the model by converting images to 1-frame videos.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 78 |
+
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
|
| 79 |
+
`do_resize` parameter in the `preprocess` method.
|
| 80 |
+
size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
|
| 81 |
+
Size of the output image after resizing. The shortest edge of the image will be resized to
|
| 82 |
+
`size["shortest_edge"]` while maintaining the aspect ratio of the original image. Can be overriden by
|
| 83 |
+
`size` in the `preprocess` method.
|
| 84 |
+
patch_size (`List[int]` *optional*, defaults to [16,16]):
|
| 85 |
+
The patch size of image patch embedding.
|
| 86 |
+
num_frames (`int` *optional*, defaults to 8):
|
| 87 |
+
The maximum number of video frames.
|
| 88 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
|
| 89 |
+
Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
|
| 90 |
+
`preprocess` method.
|
| 91 |
+
do_center_crop (`bool`, *optional*, defaults to `True`):
|
| 92 |
+
Whether to center crop the image to the specified `crop_size`. Can be overridden by the `do_center_crop`
|
| 93 |
+
parameter in the `preprocess` method.
|
| 94 |
+
crop_size (`Dict[str, int]`, *optional*, defaults to `{"height": 224, "width": 224}`):
|
| 95 |
+
Size of the image after applying the center crop. Can be overridden by the `crop_size` parameter in the
|
| 96 |
+
`preprocess` method.
|
| 97 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 98 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
|
| 99 |
+
parameter in the `preprocess` method.
|
| 100 |
+
rescale_factor (`int` or `float`, *optional*, defaults to 1/255):
|
| 101 |
+
Defines the scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter
|
| 102 |
+
in the `preprocess` method.
|
| 103 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 104 |
+
Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
|
| 105 |
+
method.
|
| 106 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
|
| 107 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
| 108 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
| 109 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
|
| 110 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
| 111 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
model_input_names = [
|
| 115 |
+
"pixel_values",
|
| 116 |
+
"pixel_mask",
|
| 117 |
+
"pixel_values_mixed",
|
| 118 |
+
"pixel_mask_mixed",
|
| 119 |
+
]
|
| 120 |
+
|
| 121 |
+
def __init__(
|
| 122 |
+
self,
|
| 123 |
+
do_resize: bool = True,
|
| 124 |
+
size: Dict[str, int] = None,
|
| 125 |
+
patch_size: List[int] = [16, 16],
|
| 126 |
+
num_frames: int = 8,
|
| 127 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 128 |
+
do_center_crop: bool = True,
|
| 129 |
+
crop_size: Dict[str, int] = None,
|
| 130 |
+
do_rescale: bool = True,
|
| 131 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 132 |
+
do_normalize: bool = True,
|
| 133 |
+
image_mean: Optional[Union[float, List[float]]] = IMAGENET_STANDARD_MEAN,
|
| 134 |
+
image_std: Optional[Union[float, List[float]]] = IMAGENET_STANDARD_STD,
|
| 135 |
+
init_mask_generator=False,
|
| 136 |
+
**kwargs,
|
| 137 |
+
) -> None:
|
| 138 |
+
super().__init__(**kwargs)
|
| 139 |
+
size = size if size is not None else {"shortest_edge": 224}
|
| 140 |
+
size = get_size_dict(size, default_to_square=False)
|
| 141 |
+
crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
|
| 142 |
+
crop_size = get_size_dict(crop_size, param_name="crop_size")
|
| 143 |
+
|
| 144 |
+
self.do_resize = do_resize
|
| 145 |
+
self.size = size
|
| 146 |
+
self.patch_size = patch_size
|
| 147 |
+
self.num_frames = num_frames
|
| 148 |
+
self.do_center_crop = do_center_crop
|
| 149 |
+
self.crop_size = crop_size
|
| 150 |
+
self.resample = resample
|
| 151 |
+
self.do_rescale = do_rescale
|
| 152 |
+
self.rescale_factor = rescale_factor
|
| 153 |
+
self.do_normalize = do_normalize
|
| 154 |
+
self.image_mean = image_mean
|
| 155 |
+
self.image_std = image_std
|
| 156 |
+
self._valid_processor_keys = [
|
| 157 |
+
"videos",
|
| 158 |
+
"do_resize",
|
| 159 |
+
"size",
|
| 160 |
+
"patch_size",
|
| 161 |
+
"num_frames",
|
| 162 |
+
"resample",
|
| 163 |
+
"do_center_crop",
|
| 164 |
+
"crop_size",
|
| 165 |
+
"do_rescale",
|
| 166 |
+
"rescale_factor",
|
| 167 |
+
"do_normalize",
|
| 168 |
+
"image_mean",
|
| 169 |
+
"image_std",
|
| 170 |
+
"is_mixed",
|
| 171 |
+
"return_tensors",
|
| 172 |
+
"data_format",
|
| 173 |
+
"input_data_format",
|
| 174 |
+
]
|
| 175 |
+
|
| 176 |
+
def resize(
|
| 177 |
+
self,
|
| 178 |
+
image: np.ndarray,
|
| 179 |
+
size: Dict[str, int],
|
| 180 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 181 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 182 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 183 |
+
**kwargs,
|
| 184 |
+
) -> np.ndarray:
|
| 185 |
+
"""
|
| 186 |
+
Resize an image.
|
| 187 |
+
|
| 188 |
+
Args:
|
| 189 |
+
image (`np.ndarray`):
|
| 190 |
+
Image to resize.
|
| 191 |
+
size (`Dict[str, int]`):
|
| 192 |
+
Size of the output image. If `size` is of the form `{"height": h, "width": w}`, the output image will
|
| 193 |
+
have the size `(h, w)`. If `size` is of the form `{"shortest_edge": s}`, the output image will have its
|
| 194 |
+
shortest edge of length `s` while keeping the aspect ratio of the original image.
|
| 195 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
|
| 196 |
+
Resampling filter to use when resiizing the image.
|
| 197 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 198 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
| 199 |
+
input_data_format (`str` or `ChannelDimension`, *optional*):
|
| 200 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 201 |
+
"""
|
| 202 |
+
size = get_size_dict(size, default_to_square=False)
|
| 203 |
+
if "shortest_edge" in size:
|
| 204 |
+
output_size = get_resize_output_image_size(
|
| 205 |
+
image, size["shortest_edge"], default_to_square=False, input_data_format=input_data_format
|
| 206 |
+
)
|
| 207 |
+
elif "height" in size and "width" in size:
|
| 208 |
+
output_size = (size["height"], size["width"])
|
| 209 |
+
else:
|
| 210 |
+
raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}")
|
| 211 |
+
return resize(
|
| 212 |
+
image,
|
| 213 |
+
size=output_size,
|
| 214 |
+
resample=resample,
|
| 215 |
+
data_format=data_format,
|
| 216 |
+
input_data_format=input_data_format,
|
| 217 |
+
**kwargs,
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
def _preprocess_image(
|
| 221 |
+
self,
|
| 222 |
+
image: ImageInput,
|
| 223 |
+
do_resize: bool = None,
|
| 224 |
+
size: Dict[str, int] = None,
|
| 225 |
+
resample: PILImageResampling = None,
|
| 226 |
+
do_center_crop: bool = None,
|
| 227 |
+
crop_size: Dict[str, int] = None,
|
| 228 |
+
do_rescale: bool = None,
|
| 229 |
+
rescale_factor: float = None,
|
| 230 |
+
do_normalize: bool = None,
|
| 231 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 232 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 233 |
+
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
|
| 234 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 235 |
+
) -> np.ndarray:
|
| 236 |
+
"""Preprocesses a single image."""
|
| 237 |
+
|
| 238 |
+
validate_preprocess_arguments(
|
| 239 |
+
do_rescale=do_rescale,
|
| 240 |
+
rescale_factor=rescale_factor,
|
| 241 |
+
do_normalize=do_normalize,
|
| 242 |
+
image_mean=image_mean,
|
| 243 |
+
image_std=image_std,
|
| 244 |
+
do_center_crop=do_center_crop,
|
| 245 |
+
crop_size=crop_size,
|
| 246 |
+
do_resize=do_resize,
|
| 247 |
+
size=size,
|
| 248 |
+
resample=resample,
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
# All transformations expect numpy arrays.
|
| 252 |
+
image = to_numpy_array(image)
|
| 253 |
+
|
| 254 |
+
if do_rescale and is_scaled_image(image):
|
| 255 |
+
logger.warning_once(
|
| 256 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 257 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
if input_data_format is None:
|
| 261 |
+
input_data_format = infer_channel_dimension_format(image)
|
| 262 |
+
|
| 263 |
+
if do_resize:
|
| 264 |
+
image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
|
| 265 |
+
|
| 266 |
+
if do_center_crop:
|
| 267 |
+
image = self.center_crop(image, size=crop_size, input_data_format=input_data_format)
|
| 268 |
+
|
| 269 |
+
if do_rescale:
|
| 270 |
+
image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
| 271 |
+
|
| 272 |
+
if do_normalize:
|
| 273 |
+
image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
|
| 274 |
+
image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
| 275 |
+
return image
|
| 276 |
+
|
| 277 |
+
def preprocess(
|
| 278 |
+
self,
|
| 279 |
+
videos: ImageInput,
|
| 280 |
+
do_resize: bool = None,
|
| 281 |
+
size: Dict[str, int] = None,
|
| 282 |
+
patch_size: List[int] = None,
|
| 283 |
+
num_frames: int = None,
|
| 284 |
+
resample: PILImageResampling = None,
|
| 285 |
+
do_center_crop: bool = None,
|
| 286 |
+
crop_size: Dict[str, int] = None,
|
| 287 |
+
do_rescale: bool = None,
|
| 288 |
+
rescale_factor: float = None,
|
| 289 |
+
do_normalize: bool = None,
|
| 290 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 291 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 292 |
+
is_mixed: bool = False,
|
| 293 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 294 |
+
data_format: ChannelDimension = ChannelDimension.FIRST,
|
| 295 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 296 |
+
**kwargs,
|
| 297 |
+
) -> BatchFeature:
|
| 298 |
+
"""
|
| 299 |
+
Preprocess an videos or image or batch of videos or images.
|
| 300 |
+
|
| 301 |
+
Args:
|
| 302 |
+
videos (`ImageInput`):
|
| 303 |
+
Images or videos to preprocess. Expects a single or batch of frames with pixel values ranging from 0 to
|
| 304 |
+
255. If passing in frames with pixel values between 0 and 1, set `do_rescale=False`.
|
| 305 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 306 |
+
Whether to resize the image.
|
| 307 |
+
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
|
| 308 |
+
Size of the image after applying resize.
|
| 309 |
+
patch_size (`List[int]` *optional*, defaults to self.patch_size):
|
| 310 |
+
The patch size of image patch embedding.
|
| 311 |
+
num_frames (`int` *optional*, defaults to self.num_frames):
|
| 312 |
+
The maximum number of video frames.
|
| 313 |
+
resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
|
| 314 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
|
| 315 |
+
has an effect if `do_resize` is set to `True`.
|
| 316 |
+
do_center_crop (`bool`, *optional*, defaults to `self.do_centre_crop`):
|
| 317 |
+
Whether to centre crop the image.
|
| 318 |
+
crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
|
| 319 |
+
Size of the image after applying the centre crop.
|
| 320 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 321 |
+
Whether to rescale the image values between [0 - 1].
|
| 322 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 323 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 324 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 325 |
+
Whether to normalize the image.
|
| 326 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
| 327 |
+
Image mean.
|
| 328 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
| 329 |
+
Image standard deviation.
|
| 330 |
+
is_mixed (`bool`, *optional*):
|
| 331 |
+
If the input video has negative samples.
|
| 332 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 333 |
+
The type of tensors to return. Can be one of:
|
| 334 |
+
- Unset: Return a list of `np.ndarray`.
|
| 335 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 336 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 337 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 338 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 339 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 340 |
+
The channel dimension format for the output image. Can be one of:
|
| 341 |
+
- `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 342 |
+
- `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 343 |
+
- Unset: Use the inferred channel dimension format of the input image.
|
| 344 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 345 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 346 |
+
from the input image. Can be one of:
|
| 347 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 348 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 349 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 350 |
+
|
| 351 |
+
Returns:
|
| 352 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 353 |
+
|
| 354 |
+
- **pixel_values** -- Pixel values to be fed to a model, of shape (batch_size, num_channels, height,
|
| 355 |
+
width).
|
| 356 |
+
|
| 357 |
+
- **pixel_mask** -- Pixel masks to be fed to a model, of shape (batch_size, num_pixel_patches).
|
| 358 |
+
|
| 359 |
+
- **pixel_values_mixed** -- Pixel values with both postive or negative to be fed to a model, of shape
|
| 360 |
+
(batch_size, num_channels, height, width).
|
| 361 |
+
|
| 362 |
+
- **pixel_mask_mixed** -- Pixel masks with both postive or negative to be fed to a model, of shape
|
| 363 |
+
(batch_size, num_pixel_patches).
|
| 364 |
+
"""
|
| 365 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 366 |
+
resample = resample if resample is not None else self.resample
|
| 367 |
+
do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
|
| 368 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 369 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 370 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 371 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 372 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 373 |
+
|
| 374 |
+
size = size if size is not None else self.size
|
| 375 |
+
size = get_size_dict(size, default_to_square=False)
|
| 376 |
+
crop_size = crop_size if crop_size is not None else self.crop_size
|
| 377 |
+
crop_size = get_size_dict(crop_size, param_name="crop_size")
|
| 378 |
+
patch_size = patch_size if patch_size is not None else self.patch_size
|
| 379 |
+
num_frames = num_frames if patch_size is not None else self.num_frames
|
| 380 |
+
|
| 381 |
+
validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)
|
| 382 |
+
|
| 383 |
+
if not valid_images(videos):
|
| 384 |
+
raise ValueError(
|
| 385 |
+
"Invalid image or video type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 386 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
videos = make_batched(videos)
|
| 390 |
+
|
| 391 |
+
# Check number of frames is fewer than maximum frames
|
| 392 |
+
for video in videos:
|
| 393 |
+
if len(video) > self.num_frames:
|
| 394 |
+
raise ValueError(
|
| 395 |
+
f"number of frames must not be greater than the maximum frames of the model {self.num_frames}."
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
max_num_frames = max([len(video) for video in videos])
|
| 399 |
+
num_patches_per_image = (size["shortest_edge"] // patch_size[0]) ** 2
|
| 400 |
+
video_masks = np.array(
|
| 401 |
+
[
|
| 402 |
+
len(video) * num_patches_per_image * [1] + (max_num_frames - len(video)) * num_patches_per_image * [0]
|
| 403 |
+
for video in videos
|
| 404 |
+
]
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
videos = [
|
| 408 |
+
[
|
| 409 |
+
self._preprocess_image(
|
| 410 |
+
image=img,
|
| 411 |
+
do_resize=do_resize,
|
| 412 |
+
size=size,
|
| 413 |
+
resample=resample,
|
| 414 |
+
do_center_crop=do_center_crop,
|
| 415 |
+
crop_size=crop_size,
|
| 416 |
+
do_rescale=do_rescale,
|
| 417 |
+
rescale_factor=rescale_factor,
|
| 418 |
+
do_normalize=do_normalize,
|
| 419 |
+
image_mean=image_mean,
|
| 420 |
+
image_std=image_std,
|
| 421 |
+
data_format=data_format,
|
| 422 |
+
input_data_format=input_data_format,
|
| 423 |
+
)
|
| 424 |
+
for img in video
|
| 425 |
+
]
|
| 426 |
+
for video in videos
|
| 427 |
+
]
|
| 428 |
+
|
| 429 |
+
# If videos contain both positive/negative, use mixed key for video-audio matching task
|
| 430 |
+
if is_mixed:
|
| 431 |
+
data = {"pixel_values_mixed": videos, "pixel_mask_mixed": video_masks}
|
| 432 |
+
else:
|
| 433 |
+
data = {"pixel_values": videos, "pixel_mask": video_masks}
|
| 434 |
+
|
| 435 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/tvlt/modeling_tvlt.py
ADDED
|
@@ -0,0 +1,1288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 MURGe-Lab and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch TVLT model."""
|
| 16 |
+
|
| 17 |
+
import collections.abc
|
| 18 |
+
import math
|
| 19 |
+
from copy import deepcopy
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from typing import Optional, Tuple, Union
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
import torch.utils.checkpoint
|
| 25 |
+
from torch import nn
|
| 26 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 27 |
+
|
| 28 |
+
from ....activations import ACT2FN
|
| 29 |
+
from ....modeling_outputs import BaseModelOutput, SequenceClassifierOutput
|
| 30 |
+
from ....modeling_utils import PreTrainedModel
|
| 31 |
+
from ....pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
|
| 32 |
+
from ....utils import (
|
| 33 |
+
ModelOutput,
|
| 34 |
+
add_start_docstrings,
|
| 35 |
+
add_start_docstrings_to_model_forward,
|
| 36 |
+
logging,
|
| 37 |
+
replace_return_docstrings,
|
| 38 |
+
)
|
| 39 |
+
from .configuration_tvlt import TvltConfig
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
logger = logging.get_logger(__name__)
|
| 43 |
+
|
| 44 |
+
_CONFIG_FOR_DOC = "TvltConfig"
|
| 45 |
+
_CHECKPOINT_FOR_DOC = "ZinengTang/tvlt-base"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@dataclass
|
| 49 |
+
class TvltModelOutput(ModelOutput):
|
| 50 |
+
"""
|
| 51 |
+
Class for TvltModel's outputs, with potential hidden states and attentions.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 55 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 56 |
+
last_pixel_hidden_state (`torch.FloatTensor` of shape `(batch_size, pixel_sequence_length, hidden_size)`):
|
| 57 |
+
Pixel sequence of hidden-states at the output of the last layer of the model.
|
| 58 |
+
last_audio_hidden_state (`torch.FloatTensor` of shape `(batch_size, audio_sequence_length, hidden_size)`):
|
| 59 |
+
Audio sequence of hidden-states at the output of the last layer of the model.
|
| 60 |
+
pixel_label_masks (`torch.FloatTensor` of shape `(batch_size, pixel_patch_length)`):
|
| 61 |
+
Tensor indicating which pixel patches are masked (1) and which are not (0).
|
| 62 |
+
audio_label_masks (`torch.FloatTensor` of shape `(batch_size, audio_patch_length)`):
|
| 63 |
+
Tensor indicating which audio patches are masked (1) and which are not (0).
|
| 64 |
+
pixel_ids_restore (`torch.LongTensor` of shape `(batch_size, pixel_patch_length)`):
|
| 65 |
+
Tensor containing the ids permutation of pixel masking.
|
| 66 |
+
audio_ids_restore (`torch.LongTensor` of shape `(batch_size, audio_patch_length)`):
|
| 67 |
+
Tensor containing the ids permutation of audio masking.
|
| 68 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 69 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
|
| 70 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 71 |
+
plus the initial embedding outputs.
|
| 72 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 73 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 74 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 75 |
+
the self-attention heads.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
last_hidden_state: torch.FloatTensor = None
|
| 79 |
+
last_pixel_hidden_state: torch.FloatTensor = None
|
| 80 |
+
last_audio_hidden_state: torch.FloatTensor = None
|
| 81 |
+
pixel_label_masks: torch.LongTensor = None
|
| 82 |
+
audio_label_masks: torch.LongTensor = None
|
| 83 |
+
pixel_ids_restore: torch.LongTensor = None
|
| 84 |
+
audio_ids_restore: torch.LongTensor = None
|
| 85 |
+
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 86 |
+
attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@dataclass
|
| 90 |
+
class TvltDecoderOutput(ModelOutput):
|
| 91 |
+
"""
|
| 92 |
+
Class for TvltDecoder's outputs, with potential hidden states and attentions.
|
| 93 |
+
|
| 94 |
+
Args:
|
| 95 |
+
logits (`torch.FloatTensor` of shape `(batch_size, patch_size ** 2 * num_channels)`):
|
| 96 |
+
Pixel reconstruction logits.
|
| 97 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 98 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
|
| 99 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 100 |
+
plus the initial embedding outputs.
|
| 101 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 102 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 103 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 104 |
+
the self-attention heads.
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
logits: torch.FloatTensor = None
|
| 108 |
+
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 109 |
+
attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@dataclass
|
| 113 |
+
class TvltForPreTrainingOutput(ModelOutput):
|
| 114 |
+
"""
|
| 115 |
+
Class for TvltForPreTraining's outputs, with potential hidden states and attentions.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
loss (`torch.FloatTensor` of shape `(1,)`):
|
| 119 |
+
Pixel reconstruction loss.
|
| 120 |
+
matching_logits (`torch.FloatTensor` of shape `(batch_size, 1)`):
|
| 121 |
+
Matching objective logits.
|
| 122 |
+
pixel_logits (`torch.FloatTensor` of shape
|
| 123 |
+
`(batch_size, pixel_patch_length, image_patch_size ** 3 * pixel_num_channels)`): Pixel reconstruction
|
| 124 |
+
logits.
|
| 125 |
+
audio_logits (`torch.FloatTensor` of shape
|
| 126 |
+
`(batch_size, audio_patch_length, image_patch_size[0] * image_patch_size[1])`): Audio reconstruction
|
| 127 |
+
logits.
|
| 128 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 129 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
|
| 130 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 131 |
+
plus the initial embedding outputs.
|
| 132 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 133 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 134 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 135 |
+
the self-attention heads.
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
loss: Optional[torch.FloatTensor] = None
|
| 139 |
+
matching_logits: torch.FloatTensor = None
|
| 140 |
+
pixel_logits: torch.FloatTensor = None
|
| 141 |
+
audio_logits: torch.FloatTensor = None
|
| 142 |
+
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 143 |
+
attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def generate_pixel_mask_noise(pixel_values, pixel_mask=None, mask_ratio=0.75):
|
| 147 |
+
"""Generate noise for audio masking."""
|
| 148 |
+
|
| 149 |
+
batch_size, seq_len = pixel_values.shape[:2]
|
| 150 |
+
noise = torch.rand((batch_size, seq_len), device=pixel_values.device) # noise in [0, 1]
|
| 151 |
+
len_keep = int(seq_len * (1 - mask_ratio))
|
| 152 |
+
return noise, len_keep
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def generate_audio_mask_noise(audio_values, audio_mask=None, mask_ratio=0.75, mask_type="patch-level", freq_len=8):
|
| 156 |
+
"""Generate noise for audio masking."""
|
| 157 |
+
|
| 158 |
+
batch_size, seq_len = audio_values.shape[:2]
|
| 159 |
+
if mask_type == "frame-level":
|
| 160 |
+
num_time_patches = seq_len // freq_len
|
| 161 |
+
noise = (
|
| 162 |
+
torch.rand(batch_size, num_time_patches, device=audio_values.device)
|
| 163 |
+
.unsqueeze(-1)
|
| 164 |
+
.repeat(1, 1, freq_len)
|
| 165 |
+
.view(batch_size, seq_len)
|
| 166 |
+
) # noise in [0, 1]
|
| 167 |
+
elif mask_type == "patch-level":
|
| 168 |
+
noise = torch.rand(batch_size, seq_len, device=audio_values.device) # noise in [0, 1]
|
| 169 |
+
len_keep = int(seq_len * (1 - mask_ratio))
|
| 170 |
+
return noise, len_keep
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def random_masking(sequence, noise, len_keep, attention_masks=None):
|
| 174 |
+
"""
|
| 175 |
+
Perform random masking by per-sample shuffling on frame-level. Per-sample shuffling is done by argsort random
|
| 176 |
+
noise. sequence: [batch_size, seq_len, hidden_dim], sequence
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
batch_size, seq_len, hidden_dim = sequence.shape
|
| 180 |
+
|
| 181 |
+
# sort noise for each sample
|
| 182 |
+
ids_shuffle = torch.argsort(noise, dim=1) # ascend: small is keep, large is remove
|
| 183 |
+
ids_restore = torch.argsort(ids_shuffle, dim=1)
|
| 184 |
+
|
| 185 |
+
# keep the first subset
|
| 186 |
+
ids_keep = ids_shuffle[:, :len_keep]
|
| 187 |
+
sequence_masked = torch.gather(sequence, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, hidden_dim))
|
| 188 |
+
|
| 189 |
+
# generate the binary mask: 0 is keep, 1 is remove
|
| 190 |
+
label_masks = torch.ones([batch_size, seq_len], device=sequence.device)
|
| 191 |
+
label_masks[:, :len_keep] = 0
|
| 192 |
+
# unshuffle to get the binary mask
|
| 193 |
+
label_masks = torch.gather(label_masks, dim=1, index=ids_restore)
|
| 194 |
+
|
| 195 |
+
if attention_masks is not None:
|
| 196 |
+
label_masks *= attention_masks
|
| 197 |
+
attention_masks = torch.gather(attention_masks, dim=1, index=ids_keep)
|
| 198 |
+
|
| 199 |
+
return sequence_masked, attention_masks, label_masks, ids_restore
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
class TvltPixelEmbeddings(nn.Module):
|
| 203 |
+
"""Construct the patch and position embeddings."""
|
| 204 |
+
|
| 205 |
+
def __init__(self, config):
|
| 206 |
+
super().__init__()
|
| 207 |
+
|
| 208 |
+
self.patch_embeddings = TvltPixelPatchEmbeddings(config)
|
| 209 |
+
self.num_patches_per_image = self.patch_embeddings.num_patches_per_image
|
| 210 |
+
|
| 211 |
+
self.type_embed_v = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 212 |
+
self.temporal_embed = nn.Parameter(torch.zeros(1, config.num_frames, config.hidden_size))
|
| 213 |
+
self.pos_embed_v = nn.Parameter(torch.zeros(1, self.num_patches_per_image, config.hidden_size))
|
| 214 |
+
|
| 215 |
+
self.config = config
|
| 216 |
+
|
| 217 |
+
def forward(self, pixel_values, attention_masks=None):
|
| 218 |
+
# create patch embeddings
|
| 219 |
+
batch_size, num_frames, num_channels, height, width = pixel_values.shape
|
| 220 |
+
|
| 221 |
+
embeddings = self.patch_embeddings(pixel_values)
|
| 222 |
+
embeddings += self.pos_embed_v.repeat(1, num_frames, 1)
|
| 223 |
+
embeddings += torch.repeat_interleave(self.temporal_embed[:, :num_frames], self.num_patches_per_image, dim=1)
|
| 224 |
+
embeddings += self.type_embed_v
|
| 225 |
+
|
| 226 |
+
return embeddings, attention_masks
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
class TvltAudioEmbeddings(nn.Module):
|
| 230 |
+
"""Construct the patch and position embeddings."""
|
| 231 |
+
|
| 232 |
+
def __init__(self, config):
|
| 233 |
+
super().__init__()
|
| 234 |
+
|
| 235 |
+
self.patch_embeddings = TvltAudioPatchEmbeddings(config)
|
| 236 |
+
self.num_patches = self.patch_embeddings.num_patches
|
| 237 |
+
|
| 238 |
+
self.type_embed_a = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 239 |
+
self.num_freq_patches = config.frequency_length // config.audio_patch_size[1]
|
| 240 |
+
self.pos_embed_a = nn.Parameter(torch.zeros(1, self.num_patches // self.num_freq_patches, config.hidden_size))
|
| 241 |
+
self.freq_embed = nn.Parameter(torch.zeros(1, self.num_freq_patches, config.hidden_size))
|
| 242 |
+
|
| 243 |
+
self.num_freq_patches = config.frequency_length // config.audio_patch_size[1]
|
| 244 |
+
self.config = config
|
| 245 |
+
|
| 246 |
+
def forward(self, audio_values, attention_masks=None):
|
| 247 |
+
# create patch embeddings
|
| 248 |
+
embeddings = self.patch_embeddings(audio_values)
|
| 249 |
+
|
| 250 |
+
num_time_patches = embeddings.size(1) // self.num_freq_patches
|
| 251 |
+
embeddings += self.freq_embed.repeat(1, num_time_patches, 1)
|
| 252 |
+
embeddings += torch.repeat_interleave(self.pos_embed_a[:, :num_time_patches], self.num_freq_patches, dim=1)
|
| 253 |
+
embeddings += self.type_embed_a
|
| 254 |
+
|
| 255 |
+
return embeddings, attention_masks
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
class TvltPixelPatchEmbeddings(nn.Module):
|
| 259 |
+
"""
|
| 260 |
+
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
| 261 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
| 262 |
+
Transformer.
|
| 263 |
+
"""
|
| 264 |
+
|
| 265 |
+
def __init__(self, config):
|
| 266 |
+
super().__init__()
|
| 267 |
+
image_size, patch_size = config.image_size, config.image_patch_size
|
| 268 |
+
num_channels, hidden_size = config.num_image_channels, config.hidden_size
|
| 269 |
+
|
| 270 |
+
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
|
| 271 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 272 |
+
num_patches_per_image = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 273 |
+
self.image_size = image_size
|
| 274 |
+
self.patch_size = patch_size
|
| 275 |
+
self.num_channels = num_channels
|
| 276 |
+
self.num_patches_per_image = num_patches_per_image
|
| 277 |
+
self.hidden_size = hidden_size
|
| 278 |
+
|
| 279 |
+
self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
|
| 280 |
+
|
| 281 |
+
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
|
| 282 |
+
batch_size, num_frames, num_channels, height, width = pixel_values.shape
|
| 283 |
+
if num_channels != self.num_channels:
|
| 284 |
+
raise ValueError(
|
| 285 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 286 |
+
)
|
| 287 |
+
if height != self.image_size[0] or width != self.image_size[1]:
|
| 288 |
+
raise ValueError(
|
| 289 |
+
f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
pixel_values = pixel_values.reshape(batch_size * num_frames, num_channels, height, width)
|
| 293 |
+
embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
|
| 294 |
+
embeddings = embeddings.reshape(batch_size, num_frames * self.num_patches_per_image, self.hidden_size)
|
| 295 |
+
|
| 296 |
+
return embeddings
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
class TvltAudioPatchEmbeddings(nn.Module):
|
| 300 |
+
"""
|
| 301 |
+
This class turns `audio_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
| 302 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
| 303 |
+
Transformer.
|
| 304 |
+
"""
|
| 305 |
+
|
| 306 |
+
def __init__(self, config):
|
| 307 |
+
super().__init__()
|
| 308 |
+
spectrogram_length, frequency_length, patch_size = (
|
| 309 |
+
config.spectrogram_length,
|
| 310 |
+
config.frequency_length,
|
| 311 |
+
config.audio_patch_size,
|
| 312 |
+
)
|
| 313 |
+
num_channels, hidden_size = config.num_audio_channels, config.hidden_size
|
| 314 |
+
|
| 315 |
+
spectrogram_size = (spectrogram_length, frequency_length)
|
| 316 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 317 |
+
num_patches = (spectrogram_size[1] // patch_size[1]) * (spectrogram_size[0] // patch_size[0])
|
| 318 |
+
patch_shape = (spectrogram_size[0] // patch_size[0], spectrogram_size[1] // patch_size[1])
|
| 319 |
+
self.spectrogram_size = spectrogram_size
|
| 320 |
+
self.patch_size = patch_size
|
| 321 |
+
self.num_channels = num_channels
|
| 322 |
+
self.num_patches = num_patches
|
| 323 |
+
self.patch_shape = patch_shape
|
| 324 |
+
|
| 325 |
+
self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
|
| 326 |
+
|
| 327 |
+
def forward(self, audio_values: torch.Tensor) -> torch.Tensor:
|
| 328 |
+
batch_size, num_channels, height, width = audio_values.shape
|
| 329 |
+
if num_channels != self.num_channels:
|
| 330 |
+
raise ValueError(
|
| 331 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 332 |
+
)
|
| 333 |
+
if height > self.spectrogram_size[0] or width != self.spectrogram_size[1]:
|
| 334 |
+
raise ValueError(
|
| 335 |
+
f"Input audio size ({height}*{width}) doesn't match model"
|
| 336 |
+
f" ({self.spectrogram_size[0]}*{self.spectrogram_size[1]})."
|
| 337 |
+
)
|
| 338 |
+
embeddings = self.projection(audio_values).flatten(2).transpose(1, 2)
|
| 339 |
+
|
| 340 |
+
return embeddings
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
class TvltSelfAttention(nn.Module):
|
| 344 |
+
def __init__(self, config):
|
| 345 |
+
super().__init__()
|
| 346 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 347 |
+
raise ValueError(
|
| 348 |
+
f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
|
| 349 |
+
f"heads {config.num_attention_heads}."
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
self.num_attention_heads = config.num_attention_heads
|
| 353 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 354 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 355 |
+
|
| 356 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 357 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 358 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 359 |
+
|
| 360 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 361 |
+
|
| 362 |
+
def transpose_for_scores(self, x):
|
| 363 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 364 |
+
x = x.view(*new_x_shape)
|
| 365 |
+
return x.permute(0, 2, 1, 3)
|
| 366 |
+
|
| 367 |
+
def forward(self, hidden_states, attention_mask=None, head_mask=None, output_attentions=False):
|
| 368 |
+
mixed_query_layer = self.query(hidden_states)
|
| 369 |
+
|
| 370 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 371 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 372 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 373 |
+
|
| 374 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 375 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 376 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 377 |
+
if attention_mask is not None:
|
| 378 |
+
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
|
| 379 |
+
attention_scores = attention_scores + attention_mask
|
| 380 |
+
|
| 381 |
+
# Normalize the attention scores to probabilities.
|
| 382 |
+
attention_probs = nn.Softmax(dim=-1)(attention_scores)
|
| 383 |
+
|
| 384 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 385 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 386 |
+
attention_probs = self.dropout(attention_probs)
|
| 387 |
+
|
| 388 |
+
# Mask heads if we want to
|
| 389 |
+
if head_mask is not None:
|
| 390 |
+
attention_probs = attention_probs * head_mask
|
| 391 |
+
|
| 392 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 393 |
+
|
| 394 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 395 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 396 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
| 397 |
+
|
| 398 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 399 |
+
|
| 400 |
+
return outputs
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
class TvltSelfOutput(nn.Module):
|
| 404 |
+
"""
|
| 405 |
+
The residual connection is defined in TvltLayer instead of here (as is the case with other models), due to the
|
| 406 |
+
layernorm applied before each block.
|
| 407 |
+
"""
|
| 408 |
+
|
| 409 |
+
def __init__(self, config: TvltConfig) -> None:
|
| 410 |
+
super().__init__()
|
| 411 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 412 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 413 |
+
|
| 414 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 415 |
+
hidden_states = self.dense(hidden_states)
|
| 416 |
+
hidden_states = self.dropout(hidden_states)
|
| 417 |
+
|
| 418 |
+
return hidden_states
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
class TvltAttention(nn.Module):
|
| 422 |
+
def __init__(self, config):
|
| 423 |
+
super().__init__()
|
| 424 |
+
self.attention = TvltSelfAttention(config)
|
| 425 |
+
self.output = TvltSelfOutput(config)
|
| 426 |
+
self.pruned_heads = set()
|
| 427 |
+
|
| 428 |
+
def prune_heads(self, heads):
|
| 429 |
+
if len(heads) == 0:
|
| 430 |
+
return
|
| 431 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 432 |
+
heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
# Prune linear layers
|
| 436 |
+
self.attention.query = prune_linear_layer(self.attention.query, index)
|
| 437 |
+
self.attention.key = prune_linear_layer(self.attention.key, index)
|
| 438 |
+
self.attention.value = prune_linear_layer(self.attention.value, index)
|
| 439 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 440 |
+
|
| 441 |
+
# Update hyper params and store pruned heads
|
| 442 |
+
self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
|
| 443 |
+
self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
|
| 444 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 445 |
+
|
| 446 |
+
def forward(self, hidden_states, attention_mask=None, head_mask=None, output_attentions=False):
|
| 447 |
+
self_outputs = self.attention(hidden_states, attention_mask, head_mask, output_attentions)
|
| 448 |
+
|
| 449 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 450 |
+
|
| 451 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 452 |
+
return outputs
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
class TvltIntermediate(nn.Module):
|
| 456 |
+
def __init__(self, config: TvltConfig) -> None:
|
| 457 |
+
super().__init__()
|
| 458 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 459 |
+
if isinstance(config.hidden_act, str):
|
| 460 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 461 |
+
else:
|
| 462 |
+
self.intermediate_act_fn = config.hidden_act
|
| 463 |
+
|
| 464 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 465 |
+
hidden_states = self.dense(hidden_states)
|
| 466 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 467 |
+
|
| 468 |
+
return hidden_states
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
class TvltOutput(nn.Module):
|
| 472 |
+
def __init__(self, config: TvltConfig) -> None:
|
| 473 |
+
super().__init__()
|
| 474 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 475 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 476 |
+
|
| 477 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 478 |
+
hidden_states = self.dense(hidden_states)
|
| 479 |
+
hidden_states = self.dropout(hidden_states)
|
| 480 |
+
|
| 481 |
+
hidden_states = hidden_states + input_tensor
|
| 482 |
+
|
| 483 |
+
return hidden_states
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
class TvltLayer(nn.Module):
|
| 487 |
+
"""This corresponds to the Block class in the timm implementation."""
|
| 488 |
+
|
| 489 |
+
def __init__(self, config):
|
| 490 |
+
super().__init__()
|
| 491 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 492 |
+
self.seq_len_dim = 1
|
| 493 |
+
self.attention = TvltAttention(config)
|
| 494 |
+
self.intermediate = TvltIntermediate(config)
|
| 495 |
+
self.output = TvltOutput(config)
|
| 496 |
+
self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 497 |
+
self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 498 |
+
|
| 499 |
+
def forward(self, hidden_states, attention_mask=None, head_mask=None, output_attentions=False):
|
| 500 |
+
self_attention_outputs = self.attention(
|
| 501 |
+
self.layernorm_before(hidden_states), # in ViLT, layernorm is applied before self-attention
|
| 502 |
+
attention_mask,
|
| 503 |
+
head_mask,
|
| 504 |
+
output_attentions=output_attentions,
|
| 505 |
+
)
|
| 506 |
+
attention_output = self_attention_outputs[0]
|
| 507 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 508 |
+
|
| 509 |
+
# first residual connection
|
| 510 |
+
hidden_states = attention_output + hidden_states.to(attention_output.device)
|
| 511 |
+
|
| 512 |
+
# in ViLT, layernorm is also applied after self-attention
|
| 513 |
+
layer_output = self.layernorm_after(hidden_states)
|
| 514 |
+
layer_output = self.intermediate(layer_output)
|
| 515 |
+
|
| 516 |
+
# second residual connection is done here
|
| 517 |
+
layer_output = self.output(layer_output, hidden_states)
|
| 518 |
+
|
| 519 |
+
outputs = (layer_output,) + outputs
|
| 520 |
+
|
| 521 |
+
return outputs
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
class TvltEncoder(nn.Module):
|
| 525 |
+
def __init__(self, config):
|
| 526 |
+
super().__init__()
|
| 527 |
+
self.config = config
|
| 528 |
+
self.layer = nn.ModuleList([TvltLayer(config) for _ in range(config.num_hidden_layers)])
|
| 529 |
+
self.gradient_checkpointing = False
|
| 530 |
+
|
| 531 |
+
def forward(
|
| 532 |
+
self,
|
| 533 |
+
hidden_states,
|
| 534 |
+
attention_mask=None,
|
| 535 |
+
head_mask=None,
|
| 536 |
+
output_attentions=False,
|
| 537 |
+
output_hidden_states=False,
|
| 538 |
+
return_dict=True,
|
| 539 |
+
):
|
| 540 |
+
all_hidden_states = () if output_hidden_states else None
|
| 541 |
+
all_self_attentions = () if output_attentions else None
|
| 542 |
+
|
| 543 |
+
for i, layer_module in enumerate(self.layer):
|
| 544 |
+
if output_hidden_states:
|
| 545 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 546 |
+
|
| 547 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 548 |
+
|
| 549 |
+
if self.gradient_checkpointing and self.training:
|
| 550 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 551 |
+
layer_module.__call__,
|
| 552 |
+
hidden_states,
|
| 553 |
+
attention_mask,
|
| 554 |
+
layer_head_mask,
|
| 555 |
+
output_attentions,
|
| 556 |
+
)
|
| 557 |
+
else:
|
| 558 |
+
layer_outputs = layer_module(hidden_states, attention_mask, layer_head_mask, output_attentions)
|
| 559 |
+
|
| 560 |
+
hidden_states = layer_outputs[0]
|
| 561 |
+
|
| 562 |
+
if output_attentions:
|
| 563 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 564 |
+
|
| 565 |
+
if output_hidden_states:
|
| 566 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 567 |
+
|
| 568 |
+
if not return_dict:
|
| 569 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
|
| 570 |
+
return BaseModelOutput(
|
| 571 |
+
last_hidden_state=hidden_states,
|
| 572 |
+
hidden_states=all_hidden_states,
|
| 573 |
+
attentions=all_self_attentions,
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
class TvltPreTrainedModel(PreTrainedModel):
|
| 578 |
+
"""
|
| 579 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 580 |
+
models.
|
| 581 |
+
"""
|
| 582 |
+
|
| 583 |
+
config_class = TvltConfig
|
| 584 |
+
base_model_prefix = "tvlt"
|
| 585 |
+
main_input_name = "pixel_values"
|
| 586 |
+
supports_gradient_checkpointing = True
|
| 587 |
+
|
| 588 |
+
def _init_weights(self, module):
|
| 589 |
+
"""Initialize the weights"""
|
| 590 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 591 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 592 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 593 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 594 |
+
if module.bias is not None:
|
| 595 |
+
module.bias.data.zero_()
|
| 596 |
+
elif isinstance(module, nn.LayerNorm):
|
| 597 |
+
module.bias.data.zero_()
|
| 598 |
+
module.weight.data.fill_(1.0)
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
TVLT_START_DOCSTRING = r"""
|
| 602 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 603 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 604 |
+
behavior.
|
| 605 |
+
|
| 606 |
+
Parameters:
|
| 607 |
+
config ([`TvltConfig`]): Model configuration class with all the parameters of the model.
|
| 608 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 609 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 610 |
+
"""
|
| 611 |
+
|
| 612 |
+
TVLT_INPUTS_DOCSTRING = r"""
|
| 613 |
+
Args:
|
| 614 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
|
| 615 |
+
Pixel values. Pixel values can be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for
|
| 616 |
+
details.
|
| 617 |
+
|
| 618 |
+
audio_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 619 |
+
Audio values. Audio values can be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for
|
| 620 |
+
details.
|
| 621 |
+
|
| 622 |
+
pixel_mask (`torch.FloatTensor` of shape `(batch_size, num_pixel_patches)`):
|
| 623 |
+
Pixel masks. Pixel masks can be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for
|
| 624 |
+
details.
|
| 625 |
+
|
| 626 |
+
audio_mask (`torch.FloatTensor` of shape `(batch_size, num_audio_patches)`):
|
| 627 |
+
Audio masks. Audio masks can be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for
|
| 628 |
+
details.
|
| 629 |
+
|
| 630 |
+
pixel_values_mixed (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
|
| 631 |
+
Pixel values that mix positive and negative samples in Tvlt vision-audio matching. Pixel values mixed can
|
| 632 |
+
be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for details.
|
| 633 |
+
|
| 634 |
+
pixel_mask_mixed (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 635 |
+
Pixel masks of pixel_values_mixed. Pixel masks mixed can be obtained using [`TvltProcessor`]. See
|
| 636 |
+
[`TvltProcessor.__call__`] for details.
|
| 637 |
+
|
| 638 |
+
mask_pixel (`bool`, *optional*):
|
| 639 |
+
Whether to mask pixel for MAE tasks. Only set to True in TvltForPreTraining.
|
| 640 |
+
|
| 641 |
+
mask_audio (`bool`, *optional*):
|
| 642 |
+
Whether to mask audio for MAE tasks. Only set to True in TvltForPreTraining.
|
| 643 |
+
|
| 644 |
+
output_attentions (`bool`, *optional*):
|
| 645 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 646 |
+
tensors for more detail.
|
| 647 |
+
|
| 648 |
+
output_hidden_states (`bool`, *optional*):
|
| 649 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 650 |
+
more detail.
|
| 651 |
+
|
| 652 |
+
return_dict (`bool`, *optional*):
|
| 653 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 654 |
+
"""
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
@add_start_docstrings(
|
| 658 |
+
"The bare TVLT Model transformer outputting raw hidden-states without any specific head on top.",
|
| 659 |
+
TVLT_START_DOCSTRING,
|
| 660 |
+
)
|
| 661 |
+
class TvltModel(TvltPreTrainedModel):
|
| 662 |
+
def __init__(self, config):
|
| 663 |
+
super().__init__(config)
|
| 664 |
+
self.config = config
|
| 665 |
+
|
| 666 |
+
self.pixel_embeddings = TvltPixelEmbeddings(config)
|
| 667 |
+
self.audio_embeddings = TvltAudioEmbeddings(config)
|
| 668 |
+
self.encoder = TvltEncoder(config)
|
| 669 |
+
|
| 670 |
+
self.cls_embedding = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 671 |
+
|
| 672 |
+
if config.use_mean_pooling:
|
| 673 |
+
self.layernorm = None
|
| 674 |
+
else:
|
| 675 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 676 |
+
|
| 677 |
+
# Initialize weights and apply final processing
|
| 678 |
+
self.post_init()
|
| 679 |
+
|
| 680 |
+
def get_input_embeddings(self):
|
| 681 |
+
return self.pixel_embeddings.patch_embeddings, self.audio_embeddings.patch_embeddings
|
| 682 |
+
|
| 683 |
+
def _prune_heads(self, heads_to_prune):
|
| 684 |
+
"""
|
| 685 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 686 |
+
class PreTrainedModel
|
| 687 |
+
"""
|
| 688 |
+
for layer, heads in heads_to_prune.items():
|
| 689 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 690 |
+
|
| 691 |
+
@add_start_docstrings_to_model_forward(TVLT_INPUTS_DOCSTRING)
|
| 692 |
+
@replace_return_docstrings(output_type=TvltModelOutput, config_class=_CONFIG_FOR_DOC)
|
| 693 |
+
def forward(
|
| 694 |
+
self,
|
| 695 |
+
pixel_values: torch.FloatTensor,
|
| 696 |
+
audio_values: torch.FloatTensor,
|
| 697 |
+
pixel_mask: Optional[torch.FloatTensor] = None,
|
| 698 |
+
audio_mask: Optional[torch.FloatTensor] = None,
|
| 699 |
+
mask_pixel: bool = False,
|
| 700 |
+
mask_audio: bool = False,
|
| 701 |
+
output_attentions: Optional[bool] = None,
|
| 702 |
+
output_hidden_states: Optional[bool] = None,
|
| 703 |
+
return_dict: Optional[bool] = None,
|
| 704 |
+
) -> Union[Tuple[torch.FloatTensor], TvltModelOutput]:
|
| 705 |
+
r"""
|
| 706 |
+
Returns:
|
| 707 |
+
|
| 708 |
+
Examples:
|
| 709 |
+
|
| 710 |
+
```python
|
| 711 |
+
>>> from transformers import TvltProcessor, TvltModel
|
| 712 |
+
>>> import numpy as np
|
| 713 |
+
>>> import torch
|
| 714 |
+
|
| 715 |
+
>>> num_frames = 8
|
| 716 |
+
>>> images = list(np.random.randn(num_frames, 3, 224, 224))
|
| 717 |
+
>>> audio = list(np.random.randn(10000))
|
| 718 |
+
|
| 719 |
+
>>> processor = TvltProcessor.from_pretrained("ZinengTang/tvlt-base")
|
| 720 |
+
>>> model = TvltModel.from_pretrained("ZinengTang/tvlt-base")
|
| 721 |
+
|
| 722 |
+
>>> input_dict = processor(images, audio, sampling_rate=44100, return_tensors="pt")
|
| 723 |
+
|
| 724 |
+
>>> outputs = model(**input_dict)
|
| 725 |
+
>>> loss = outputs.loss
|
| 726 |
+
```"""
|
| 727 |
+
|
| 728 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 729 |
+
output_hidden_states = (
|
| 730 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 731 |
+
)
|
| 732 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 733 |
+
|
| 734 |
+
pixel_embedding_output, pixel_mask = self.pixel_embeddings(pixel_values, pixel_mask)
|
| 735 |
+
|
| 736 |
+
audio_embedding_output, audio_mask = self.audio_embeddings(audio_values, audio_mask)
|
| 737 |
+
|
| 738 |
+
# Mask pixel if mask_pixel is True
|
| 739 |
+
pixel_label_masks = None
|
| 740 |
+
pixel_ids_restore = None
|
| 741 |
+
if mask_pixel:
|
| 742 |
+
pixel_mask_noise, pixel_len_keep = generate_pixel_mask_noise(
|
| 743 |
+
pixel_embedding_output, pixel_mask=pixel_mask, mask_ratio=self.config.pixel_mask_ratio
|
| 744 |
+
)
|
| 745 |
+
pixel_embedding_output, pixel_mask, pixel_label_masks, pixel_ids_restore = random_masking(
|
| 746 |
+
pixel_embedding_output,
|
| 747 |
+
pixel_mask_noise,
|
| 748 |
+
pixel_len_keep,
|
| 749 |
+
attention_masks=pixel_mask,
|
| 750 |
+
)
|
| 751 |
+
|
| 752 |
+
# Mask audio if mask_audio is True
|
| 753 |
+
audio_label_masks = None
|
| 754 |
+
audio_ids_restore = None
|
| 755 |
+
if mask_audio:
|
| 756 |
+
num_freq_patches = self.config.frequency_length // self.config.audio_patch_size[1]
|
| 757 |
+
audio_mask_noise, audio_len_keep = generate_audio_mask_noise(
|
| 758 |
+
audio_embedding_output,
|
| 759 |
+
audio_mask=audio_mask,
|
| 760 |
+
mask_ratio=self.config.audio_mask_ratio,
|
| 761 |
+
mask_type=self.config.audio_mask_type,
|
| 762 |
+
freq_len=num_freq_patches,
|
| 763 |
+
)
|
| 764 |
+
audio_embedding_output, audio_mask, audio_label_masks, audio_ids_restore = random_masking(
|
| 765 |
+
audio_embedding_output,
|
| 766 |
+
audio_mask_noise,
|
| 767 |
+
audio_len_keep,
|
| 768 |
+
attention_masks=audio_mask,
|
| 769 |
+
)
|
| 770 |
+
|
| 771 |
+
# Prepare for encoder inputs and attention masks
|
| 772 |
+
batch_size = pixel_values.size(0)
|
| 773 |
+
embedding_output = torch.cat(
|
| 774 |
+
[self.cls_embedding.repeat(batch_size, 1, 1), pixel_embedding_output, audio_embedding_output], 1
|
| 775 |
+
)
|
| 776 |
+
masked_pixel_len = pixel_embedding_output.size(1)
|
| 777 |
+
|
| 778 |
+
attention_mask = None
|
| 779 |
+
if pixel_mask is not None and audio_mask is not None:
|
| 780 |
+
attention_mask = torch.cat([pixel_mask[:, :1], pixel_mask, audio_mask], 1)
|
| 781 |
+
|
| 782 |
+
input_shape = embedding_output.size()
|
| 783 |
+
extended_attention_mask = None
|
| 784 |
+
if attention_mask is not None:
|
| 785 |
+
extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
|
| 786 |
+
|
| 787 |
+
encoder_outputs = self.encoder(
|
| 788 |
+
embedding_output,
|
| 789 |
+
attention_mask=extended_attention_mask,
|
| 790 |
+
output_attentions=output_attentions,
|
| 791 |
+
output_hidden_states=output_hidden_states,
|
| 792 |
+
return_dict=return_dict,
|
| 793 |
+
)
|
| 794 |
+
sequence_output = encoder_outputs[0]
|
| 795 |
+
if self.layernorm is not None:
|
| 796 |
+
sequence_output = self.layernorm(sequence_output)
|
| 797 |
+
|
| 798 |
+
pixel_sequence_output = sequence_output[:, 1 : 1 + masked_pixel_len]
|
| 799 |
+
audio_sequence_output = sequence_output[:, 1 + masked_pixel_len :]
|
| 800 |
+
if not return_dict:
|
| 801 |
+
return (
|
| 802 |
+
sequence_output,
|
| 803 |
+
pixel_sequence_output,
|
| 804 |
+
audio_sequence_output,
|
| 805 |
+
pixel_label_masks,
|
| 806 |
+
audio_label_masks,
|
| 807 |
+
pixel_ids_restore,
|
| 808 |
+
audio_ids_restore,
|
| 809 |
+
) + encoder_outputs[1:]
|
| 810 |
+
|
| 811 |
+
return TvltModelOutput(
|
| 812 |
+
last_hidden_state=sequence_output,
|
| 813 |
+
last_pixel_hidden_state=pixel_sequence_output,
|
| 814 |
+
last_audio_hidden_state=audio_sequence_output,
|
| 815 |
+
pixel_label_masks=pixel_label_masks,
|
| 816 |
+
audio_label_masks=audio_label_masks,
|
| 817 |
+
pixel_ids_restore=pixel_ids_restore,
|
| 818 |
+
audio_ids_restore=audio_ids_restore,
|
| 819 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 820 |
+
attentions=encoder_outputs.attentions,
|
| 821 |
+
)
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
class TvltDecoder(nn.Module):
|
| 825 |
+
def __init__(self, config):
|
| 826 |
+
super().__init__()
|
| 827 |
+
|
| 828 |
+
decoder_config = deepcopy(config)
|
| 829 |
+
decoder_config.hidden_size = config.decoder_hidden_size
|
| 830 |
+
decoder_config.num_hidden_layers = config.decoder_num_hidden_layers
|
| 831 |
+
decoder_config.num_attention_heads = config.decoder_num_attention_heads
|
| 832 |
+
decoder_config.intermediate_size = config.decoder_intermediate_size
|
| 833 |
+
self.decoder_layers = nn.ModuleList(
|
| 834 |
+
[TvltLayer(decoder_config) for _ in range(config.decoder_num_hidden_layers)]
|
| 835 |
+
)
|
| 836 |
+
|
| 837 |
+
self.layernorm = nn.LayerNorm(config.decoder_hidden_size, eps=config.layer_norm_eps)
|
| 838 |
+
|
| 839 |
+
self.gradient_checkpointing = False
|
| 840 |
+
self.config = config
|
| 841 |
+
|
| 842 |
+
def forward(
|
| 843 |
+
self,
|
| 844 |
+
hidden_states,
|
| 845 |
+
output_attentions=False,
|
| 846 |
+
output_hidden_states=False,
|
| 847 |
+
return_dict=True,
|
| 848 |
+
):
|
| 849 |
+
# apply Transformer layers (blocks)
|
| 850 |
+
all_hidden_states = () if output_hidden_states else None
|
| 851 |
+
all_self_attentions = () if output_attentions else None
|
| 852 |
+
for i, layer_module in enumerate(self.decoder_layers):
|
| 853 |
+
if output_hidden_states:
|
| 854 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 855 |
+
|
| 856 |
+
if self.gradient_checkpointing and self.training:
|
| 857 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 858 |
+
layer_module.__call__,
|
| 859 |
+
hidden_states,
|
| 860 |
+
None,
|
| 861 |
+
output_attentions,
|
| 862 |
+
)
|
| 863 |
+
else:
|
| 864 |
+
layer_outputs = layer_module(hidden_states, output_attentions=output_attentions)
|
| 865 |
+
|
| 866 |
+
hidden_states = layer_outputs[0]
|
| 867 |
+
|
| 868 |
+
if output_attentions:
|
| 869 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 870 |
+
|
| 871 |
+
if output_hidden_states:
|
| 872 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 873 |
+
|
| 874 |
+
# predictor projection
|
| 875 |
+
logits = self.layernorm(hidden_states)
|
| 876 |
+
|
| 877 |
+
if not return_dict:
|
| 878 |
+
return tuple(v for v in [logits, all_hidden_states, all_self_attentions] if v is not None)
|
| 879 |
+
return TvltDecoderOutput(logits=logits, hidden_states=all_hidden_states, attentions=all_self_attentions)
|
| 880 |
+
|
| 881 |
+
|
| 882 |
+
@add_start_docstrings(
|
| 883 |
+
"The TVLT Model transformer with the decoder on top for self-supervised pre-training.",
|
| 884 |
+
TVLT_START_DOCSTRING,
|
| 885 |
+
)
|
| 886 |
+
class TvltForPreTraining(TvltPreTrainedModel):
|
| 887 |
+
def __init__(self, config):
|
| 888 |
+
super().__init__(config)
|
| 889 |
+
self.config = config
|
| 890 |
+
|
| 891 |
+
self.task_matching = config.task_matching
|
| 892 |
+
self.task_mae = config.task_mae
|
| 893 |
+
if not (self.task_matching or self.task_mae):
|
| 894 |
+
raise ValueError("Must set at least one of matching task and MAE task to true")
|
| 895 |
+
|
| 896 |
+
self.tvlt = TvltModel(config)
|
| 897 |
+
|
| 898 |
+
if self.task_matching:
|
| 899 |
+
self.matching_head = TvltMatchingHead(config)
|
| 900 |
+
|
| 901 |
+
if self.task_mae:
|
| 902 |
+
self.encoder_to_decoder = nn.Linear(config.hidden_size, config.decoder_hidden_size, bias=True)
|
| 903 |
+
|
| 904 |
+
self.pixel_mask_token = nn.Parameter(torch.zeros(1, 1, config.decoder_hidden_size))
|
| 905 |
+
self.audio_mask_token = nn.Parameter(torch.zeros(1, 1, config.decoder_hidden_size))
|
| 906 |
+
|
| 907 |
+
self.decoder = TvltDecoder(config)
|
| 908 |
+
|
| 909 |
+
decoder_hidden_size = config.decoder_hidden_size
|
| 910 |
+
|
| 911 |
+
num_frames = config.num_frames
|
| 912 |
+
num_patches_per_image = self.tvlt.pixel_embeddings.num_patches_per_image
|
| 913 |
+
self.decoder_pixel_pos_embed = nn.Parameter(torch.zeros(1, num_patches_per_image, decoder_hidden_size))
|
| 914 |
+
self.decoder_temporal_embed = nn.Parameter(torch.zeros(1, config.num_frames, decoder_hidden_size))
|
| 915 |
+
self.decoder_pixel_type_embed = nn.Parameter(torch.zeros(1, 1, decoder_hidden_size))
|
| 916 |
+
|
| 917 |
+
num_audio_patches = self.tvlt.audio_embeddings.num_patches
|
| 918 |
+
num_freq_patches = config.frequency_length // config.audio_patch_size[1]
|
| 919 |
+
self.decoder_audio_pos_embed = nn.Parameter(
|
| 920 |
+
torch.zeros(1, num_audio_patches // num_freq_patches, decoder_hidden_size)
|
| 921 |
+
)
|
| 922 |
+
self.decoder_freq_embed = nn.Parameter(torch.zeros(1, num_freq_patches, decoder_hidden_size))
|
| 923 |
+
self.decoder_audio_type_embed = nn.Parameter(torch.zeros(1, 1, decoder_hidden_size))
|
| 924 |
+
|
| 925 |
+
pixel_mae_output_dim = self.config.image_patch_size[0] ** 2 * self.config.num_image_channels
|
| 926 |
+
self.pixel_mae_head = TvltMAEHead(config, pixel_mae_output_dim)
|
| 927 |
+
audio_mae_output_dim = (
|
| 928 |
+
self.config.audio_patch_size[0] * self.config.audio_patch_size[1] * self.config.num_audio_channels
|
| 929 |
+
)
|
| 930 |
+
self.audio_mae_head = TvltMAEHead(config, audio_mae_output_dim)
|
| 931 |
+
|
| 932 |
+
self.num_frames = num_frames
|
| 933 |
+
self.num_patches_per_image = num_patches_per_image
|
| 934 |
+
self.num_freq_patches = num_freq_patches
|
| 935 |
+
self.image_patch_size = config.image_patch_size
|
| 936 |
+
self.audio_patch_size = config.audio_patch_size
|
| 937 |
+
|
| 938 |
+
# Initialize weights and apply final processing
|
| 939 |
+
self.post_init()
|
| 940 |
+
|
| 941 |
+
def patchify_pixel(self, pixel_values):
|
| 942 |
+
"""
|
| 943 |
+
pixel_values: [batch_size, num_frames, 3, height, width]
|
| 944 |
+
"""
|
| 945 |
+
batch_size, num_frames, num_channels, height, width = pixel_values.shape
|
| 946 |
+
num_patches_height = pixel_values.shape[3] // self.image_patch_size[0]
|
| 947 |
+
num_patches_width = pixel_values.shape[4] // self.image_patch_size[1]
|
| 948 |
+
patchified_pixel_values = pixel_values.reshape(
|
| 949 |
+
shape=(
|
| 950 |
+
batch_size,
|
| 951 |
+
num_frames,
|
| 952 |
+
num_channels,
|
| 953 |
+
num_patches_height,
|
| 954 |
+
self.image_patch_size[0],
|
| 955 |
+
num_patches_width,
|
| 956 |
+
self.image_patch_size[1],
|
| 957 |
+
)
|
| 958 |
+
)
|
| 959 |
+
patchified_pixel_values = torch.einsum("ntchpwq->nthwpqc", patchified_pixel_values)
|
| 960 |
+
patchified_pixel_values = patchified_pixel_values.reshape(
|
| 961 |
+
shape=(
|
| 962 |
+
batch_size,
|
| 963 |
+
num_patches_height * num_patches_width * num_frames,
|
| 964 |
+
self.image_patch_size[0] * self.image_patch_size[1] * num_channels,
|
| 965 |
+
)
|
| 966 |
+
)
|
| 967 |
+
return patchified_pixel_values
|
| 968 |
+
|
| 969 |
+
def patchify_audio(self, audio_values):
|
| 970 |
+
"""
|
| 971 |
+
audio_values: [batch_size, 1, height, width]
|
| 972 |
+
"""
|
| 973 |
+
batch_size, num_channels, height, width = audio_values.shape
|
| 974 |
+
num_patches_height = height // self.audio_patch_size[0]
|
| 975 |
+
num_patches_width = width // self.audio_patch_size[1]
|
| 976 |
+
patchified_audio_values = audio_values.reshape(
|
| 977 |
+
shape=(
|
| 978 |
+
batch_size,
|
| 979 |
+
num_channels,
|
| 980 |
+
num_patches_height,
|
| 981 |
+
self.audio_patch_size[0],
|
| 982 |
+
num_patches_width,
|
| 983 |
+
self.audio_patch_size[1],
|
| 984 |
+
)
|
| 985 |
+
)
|
| 986 |
+
patchified_audio_values = torch.einsum("nchpwq->nhwpqc", patchified_audio_values)
|
| 987 |
+
patchified_audio_values = patchified_audio_values.reshape(
|
| 988 |
+
shape=(
|
| 989 |
+
batch_size,
|
| 990 |
+
num_patches_height * num_patches_width,
|
| 991 |
+
self.audio_patch_size[0] * self.audio_patch_size[1] * num_channels,
|
| 992 |
+
)
|
| 993 |
+
)
|
| 994 |
+
return patchified_audio_values
|
| 995 |
+
|
| 996 |
+
def pixel_mae_loss(self, pixel_values, pixel_predictions, mask):
|
| 997 |
+
patchified_pixel_values = self.patchify_pixel(pixel_values)
|
| 998 |
+
loss = (pixel_predictions - patchified_pixel_values) ** 2
|
| 999 |
+
loss = loss.mean(dim=-1) # [batch_size, pixel_pixel_length], mean loss per patch
|
| 1000 |
+
loss = (loss * mask).sum() / mask.sum() # mean loss on removed patches
|
| 1001 |
+
return loss
|
| 1002 |
+
|
| 1003 |
+
def audio_mae_loss(self, audio_values, audio_predictions, mask):
|
| 1004 |
+
patchified_audio_values = self.patchify_audio(audio_values)
|
| 1005 |
+
loss = (audio_predictions - patchified_audio_values) ** 2
|
| 1006 |
+
loss = loss.mean(dim=-1) # [batch_size, audio_pixel_length], mean loss per patch
|
| 1007 |
+
loss = (loss * mask).sum() / mask.sum() # mean loss on removed patches
|
| 1008 |
+
return loss
|
| 1009 |
+
|
| 1010 |
+
def concatenate_mask(self, mask_token, sequence, ids_restore):
|
| 1011 |
+
batch_size, seq_length, dim = sequence.shape
|
| 1012 |
+
mask_tokens = mask_token.repeat(batch_size, ids_restore.shape[1] - seq_length, 1)
|
| 1013 |
+
padded_sequence = torch.cat([sequence, mask_tokens], dim=1)
|
| 1014 |
+
padded_sequence = torch.gather(
|
| 1015 |
+
padded_sequence, dim=1, index=ids_restore.unsqueeze(-1).repeat(1, 1, dim)
|
| 1016 |
+
) # unshuffle
|
| 1017 |
+
return padded_sequence
|
| 1018 |
+
|
| 1019 |
+
@add_start_docstrings_to_model_forward(TVLT_INPUTS_DOCSTRING)
|
| 1020 |
+
@replace_return_docstrings(output_type=TvltForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
|
| 1021 |
+
def forward(
|
| 1022 |
+
self,
|
| 1023 |
+
pixel_values: torch.FloatTensor,
|
| 1024 |
+
audio_values: torch.FloatTensor,
|
| 1025 |
+
pixel_mask: Optional[torch.FloatTensor] = None,
|
| 1026 |
+
audio_mask: Optional[torch.FloatTensor] = None,
|
| 1027 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1028 |
+
pixel_values_mixed: Optional[torch.FloatTensor] = None,
|
| 1029 |
+
pixel_mask_mixed: Optional[torch.FloatTensor] = None,
|
| 1030 |
+
output_attentions: Optional[bool] = None,
|
| 1031 |
+
output_hidden_states: Optional[bool] = None,
|
| 1032 |
+
return_dict: Optional[bool] = None,
|
| 1033 |
+
) -> Union[Tuple[torch.FloatTensor], TvltForPreTrainingOutput]:
|
| 1034 |
+
r"""
|
| 1035 |
+
pixel_values_mixed (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
|
| 1036 |
+
Pixel values that mix positive and negative samples in Tvlt vision-audio matching. Audio values can be
|
| 1037 |
+
obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for details.
|
| 1038 |
+
|
| 1039 |
+
pixel_mask_mixed (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 1040 |
+
Pixel masks of pixel_values_mixed. Pixel values mixed can be obtained using [`TvltProcessor`]. See
|
| 1041 |
+
[`TvltProcessor.__call__`] for details.
|
| 1042 |
+
|
| 1043 |
+
labels (`torch.LongTensor` of shape `(batch_size, num_labels)`, *optional*):
|
| 1044 |
+
Labels for computing the vision audio matching loss. Indices should be in `[0, 1]`. num_labels has to be 1.
|
| 1045 |
+
|
| 1046 |
+
Return:
|
| 1047 |
+
|
| 1048 |
+
Examples:
|
| 1049 |
+
|
| 1050 |
+
```python
|
| 1051 |
+
>>> from transformers import TvltProcessor, TvltForPreTraining
|
| 1052 |
+
>>> import numpy as np
|
| 1053 |
+
>>> import torch
|
| 1054 |
+
|
| 1055 |
+
>>> num_frames = 8
|
| 1056 |
+
>>> images = list(np.random.randn(num_frames, 3, 224, 224))
|
| 1057 |
+
>>> images_mixed = list(np.random.randn(num_frames, 3, 224, 224))
|
| 1058 |
+
>>> audio = list(np.random.randn(10000))
|
| 1059 |
+
>>> processor = TvltProcessor.from_pretrained("ZinengTang/tvlt-base")
|
| 1060 |
+
>>> model = TvltForPreTraining.from_pretrained("ZinengTang/tvlt-base")
|
| 1061 |
+
>>> input_dict = processor(
|
| 1062 |
+
... images, audio, images_mixed, sampling_rate=44100, mask_pixel=True, mask_audio=True, return_tensors="pt"
|
| 1063 |
+
... )
|
| 1064 |
+
|
| 1065 |
+
>>> outputs = model(**input_dict)
|
| 1066 |
+
>>> loss = outputs.loss
|
| 1067 |
+
```"""
|
| 1068 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1069 |
+
total_loss = 0.0
|
| 1070 |
+
|
| 1071 |
+
if self.task_matching:
|
| 1072 |
+
if labels is None:
|
| 1073 |
+
raise ValueError("Matching task requires labels")
|
| 1074 |
+
if pixel_values_mixed is None:
|
| 1075 |
+
raise ValueError("Matching task requires pixel_values_mixed")
|
| 1076 |
+
|
| 1077 |
+
outputs = self.tvlt(
|
| 1078 |
+
pixel_values_mixed,
|
| 1079 |
+
audio_values,
|
| 1080 |
+
pixel_mask=pixel_mask_mixed,
|
| 1081 |
+
audio_mask=audio_mask,
|
| 1082 |
+
output_attentions=output_attentions,
|
| 1083 |
+
output_hidden_states=output_hidden_states,
|
| 1084 |
+
return_dict=return_dict,
|
| 1085 |
+
)
|
| 1086 |
+
|
| 1087 |
+
sequence_output = outputs[0]
|
| 1088 |
+
matching_logits = self.matching_head(sequence_output)
|
| 1089 |
+
|
| 1090 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1091 |
+
loss = loss_fct(matching_logits.view(-1), labels.view(-1))
|
| 1092 |
+
total_loss += loss
|
| 1093 |
+
|
| 1094 |
+
pixel_logits = None
|
| 1095 |
+
audio_logits = None
|
| 1096 |
+
if self.task_mae and self.training:
|
| 1097 |
+
outputs = self.tvlt(
|
| 1098 |
+
pixel_values,
|
| 1099 |
+
audio_values,
|
| 1100 |
+
pixel_mask=pixel_mask,
|
| 1101 |
+
audio_mask=audio_mask,
|
| 1102 |
+
mask_pixel=True,
|
| 1103 |
+
mask_audio=True,
|
| 1104 |
+
output_attentions=output_attentions,
|
| 1105 |
+
output_hidden_states=output_hidden_states,
|
| 1106 |
+
return_dict=return_dict,
|
| 1107 |
+
)
|
| 1108 |
+
pixel_sequence_output = outputs.last_pixel_hidden_state if return_dict else outputs[1]
|
| 1109 |
+
audio_sequence_output = outputs.last_audio_hidden_state if return_dict else outputs[2]
|
| 1110 |
+
pixel_label_masks = outputs.pixel_label_masks if return_dict else outputs[3]
|
| 1111 |
+
audio_label_masks = outputs.audio_label_masks if return_dict else outputs[4]
|
| 1112 |
+
pixel_ids_restore = outputs.pixel_ids_restore if return_dict else outputs[5]
|
| 1113 |
+
audio_ids_restore = outputs.audio_ids_restore if return_dict else outputs[6]
|
| 1114 |
+
|
| 1115 |
+
pixel_decoder_input = self.encoder_to_decoder(
|
| 1116 |
+
pixel_sequence_output
|
| 1117 |
+
) # [batch_size, num_masked_pixel_patches, decoder_hidden_size]
|
| 1118 |
+
audio_decoder_input = self.encoder_to_decoder(
|
| 1119 |
+
audio_sequence_output
|
| 1120 |
+
) # [batch_size, num_masked_audio_patches, decoder_hidden_size]
|
| 1121 |
+
num_frames = pixel_values.size(1)
|
| 1122 |
+
pixel_decoder_input = self.concatenate_mask(self.pixel_mask_token, pixel_decoder_input, pixel_ids_restore)
|
| 1123 |
+
pixel_decoder_input = pixel_decoder_input + self.decoder_pixel_pos_embed.repeat(1, num_frames, 1)
|
| 1124 |
+
pixel_decoder_input = pixel_decoder_input + torch.repeat_interleave(
|
| 1125 |
+
self.decoder_temporal_embed[:, :num_frames], self.num_patches_per_image, dim=1
|
| 1126 |
+
)
|
| 1127 |
+
pixel_decoder_input = pixel_decoder_input + self.decoder_pixel_type_embed
|
| 1128 |
+
pixel_decoder_outputs = self.decoder(pixel_decoder_input)
|
| 1129 |
+
pixel_logits = self.pixel_mae_head(pixel_decoder_outputs.logits)
|
| 1130 |
+
|
| 1131 |
+
audio_decoder_input = self.concatenate_mask(self.audio_mask_token, audio_decoder_input, audio_ids_restore)
|
| 1132 |
+
num_time_patches = audio_decoder_input.size(1) // self.num_freq_patches
|
| 1133 |
+
audio_decoder_input = audio_decoder_input + self.decoder_freq_embed.repeat(1, num_time_patches, 1)
|
| 1134 |
+
audio_decoder_input = audio_decoder_input + torch.repeat_interleave(
|
| 1135 |
+
self.decoder_audio_pos_embed[:, :num_time_patches], self.num_freq_patches, dim=1
|
| 1136 |
+
)
|
| 1137 |
+
audio_decoder_input = audio_decoder_input + self.decoder_audio_type_embed
|
| 1138 |
+
audio_decoder_outputs = self.decoder(audio_decoder_input)
|
| 1139 |
+
audio_logits = self.audio_mae_head(audio_decoder_outputs.logits)
|
| 1140 |
+
|
| 1141 |
+
loss = self.pixel_mae_loss(pixel_values, pixel_logits, pixel_label_masks) + self.audio_mae_loss(
|
| 1142 |
+
audio_values, audio_logits, audio_label_masks
|
| 1143 |
+
)
|
| 1144 |
+
total_loss += loss
|
| 1145 |
+
|
| 1146 |
+
if not return_dict:
|
| 1147 |
+
output = (matching_logits, pixel_logits, audio_logits) + outputs[7:]
|
| 1148 |
+
return ((total_loss,) + output) if loss is not None else output
|
| 1149 |
+
|
| 1150 |
+
return TvltForPreTrainingOutput(
|
| 1151 |
+
loss=total_loss,
|
| 1152 |
+
matching_logits=matching_logits,
|
| 1153 |
+
pixel_logits=pixel_logits,
|
| 1154 |
+
audio_logits=audio_logits,
|
| 1155 |
+
hidden_states=outputs.hidden_states,
|
| 1156 |
+
attentions=outputs.attentions,
|
| 1157 |
+
)
|
| 1158 |
+
|
| 1159 |
+
|
| 1160 |
+
class TvltPooler(nn.Module):
|
| 1161 |
+
def __init__(self, config):
|
| 1162 |
+
super().__init__()
|
| 1163 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 1164 |
+
self.activation = nn.Tanh()
|
| 1165 |
+
|
| 1166 |
+
def forward(self, hidden_states):
|
| 1167 |
+
first_token_tensor = hidden_states[:, 0]
|
| 1168 |
+
pooled_output = self.dense(first_token_tensor)
|
| 1169 |
+
pooled_output = self.activation(pooled_output)
|
| 1170 |
+
return pooled_output
|
| 1171 |
+
|
| 1172 |
+
|
| 1173 |
+
class TvltMatchingHead(nn.Module):
|
| 1174 |
+
def __init__(self, config):
|
| 1175 |
+
super().__init__()
|
| 1176 |
+
self.pooler = TvltPooler(config)
|
| 1177 |
+
self.fc = nn.Linear(config.hidden_size, 1)
|
| 1178 |
+
|
| 1179 |
+
def forward(self, hidden_states):
|
| 1180 |
+
hidden_states = self.fc(self.pooler(hidden_states))
|
| 1181 |
+
return hidden_states
|
| 1182 |
+
|
| 1183 |
+
|
| 1184 |
+
class TvltMAEHead(nn.Module):
|
| 1185 |
+
def __init__(self, config, output_dim=None):
|
| 1186 |
+
super().__init__()
|
| 1187 |
+
self.config = config
|
| 1188 |
+
self.decoder = nn.Linear(config.decoder_hidden_size, output_dim)
|
| 1189 |
+
|
| 1190 |
+
def forward(self, hidden_states):
|
| 1191 |
+
hidden_states = self.decoder(hidden_states)
|
| 1192 |
+
return hidden_states
|
| 1193 |
+
|
| 1194 |
+
|
| 1195 |
+
@add_start_docstrings(
|
| 1196 |
+
"""
|
| 1197 |
+
Tvlt Model transformer with a classifier head on top (an MLP on top of the final hidden state of the [CLS] token)
|
| 1198 |
+
for audiovisual classification tasks, e.g. CMU-MOSEI Sentiment Analysis and Audio to Video Retrieval.
|
| 1199 |
+
""",
|
| 1200 |
+
TVLT_START_DOCSTRING,
|
| 1201 |
+
)
|
| 1202 |
+
class TvltForAudioVisualClassification(TvltPreTrainedModel):
|
| 1203 |
+
def __init__(self, config):
|
| 1204 |
+
super().__init__(config)
|
| 1205 |
+
|
| 1206 |
+
self.tvlt = TvltModel(config)
|
| 1207 |
+
|
| 1208 |
+
# Classifier head
|
| 1209 |
+
self.classifier = nn.Sequential(
|
| 1210 |
+
nn.Linear(config.hidden_size, config.hidden_size * 2),
|
| 1211 |
+
nn.LayerNorm(config.hidden_size * 2, eps=config.layer_norm_eps),
|
| 1212 |
+
nn.GELU(),
|
| 1213 |
+
nn.Linear(config.hidden_size * 2, config.num_labels),
|
| 1214 |
+
)
|
| 1215 |
+
self.config = config
|
| 1216 |
+
|
| 1217 |
+
# Initialize weights and apply final processing
|
| 1218 |
+
self.post_init()
|
| 1219 |
+
|
| 1220 |
+
@add_start_docstrings_to_model_forward(TVLT_INPUTS_DOCSTRING)
|
| 1221 |
+
@replace_return_docstrings(output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC)
|
| 1222 |
+
def forward(
|
| 1223 |
+
self,
|
| 1224 |
+
pixel_values: torch.FloatTensor,
|
| 1225 |
+
audio_values: torch.FloatTensor,
|
| 1226 |
+
pixel_mask: Optional[torch.FloatTensor] = None,
|
| 1227 |
+
audio_mask: Optional[torch.FloatTensor] = None,
|
| 1228 |
+
output_attentions: Optional[bool] = None,
|
| 1229 |
+
output_hidden_states: Optional[bool] = None,
|
| 1230 |
+
return_dict: Optional[bool] = None,
|
| 1231 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1232 |
+
) -> Union[Tuple[torch.FloatTensor], SequenceClassifierOutput]:
|
| 1233 |
+
r"""
|
| 1234 |
+
labels (`torch.LongTensor` of shape `(batch_size, num_labels)`, *optional*):
|
| 1235 |
+
Labels for computing the audiovisual loss. Indices should be in `[0, ..., num_classes-1]` where num_classes
|
| 1236 |
+
refers to the number of classes in audiovisual tasks.
|
| 1237 |
+
|
| 1238 |
+
Return:
|
| 1239 |
+
|
| 1240 |
+
Examples:
|
| 1241 |
+
```python
|
| 1242 |
+
>>> from transformers import TvltProcessor, TvltForAudioVisualClassification
|
| 1243 |
+
>>> import numpy as np
|
| 1244 |
+
>>> import torch
|
| 1245 |
+
|
| 1246 |
+
>>> num_frames = 8
|
| 1247 |
+
>>> images = list(np.random.randn(num_frames, 3, 224, 224))
|
| 1248 |
+
>>> audio = list(np.random.randn(10000))
|
| 1249 |
+
>>> processor = TvltProcessor.from_pretrained("ZinengTang/tvlt-base")
|
| 1250 |
+
>>> model = TvltForAudioVisualClassification.from_pretrained("ZinengTang/tvlt-base")
|
| 1251 |
+
>>> input_dict = processor(images, audio, sampling_rate=44100, return_tensors="pt")
|
| 1252 |
+
|
| 1253 |
+
>>> outputs = model(**input_dict)
|
| 1254 |
+
>>> loss = outputs.loss
|
| 1255 |
+
```"""
|
| 1256 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1257 |
+
|
| 1258 |
+
outputs = self.tvlt(
|
| 1259 |
+
pixel_values,
|
| 1260 |
+
audio_values,
|
| 1261 |
+
pixel_mask=pixel_mask,
|
| 1262 |
+
audio_mask=audio_mask,
|
| 1263 |
+
output_attentions=output_attentions,
|
| 1264 |
+
output_hidden_states=output_hidden_states,
|
| 1265 |
+
return_dict=return_dict,
|
| 1266 |
+
)
|
| 1267 |
+
sequence_output = outputs[0][:, 0]
|
| 1268 |
+
logits = self.classifier(sequence_output) # rank value
|
| 1269 |
+
|
| 1270 |
+
loss = None
|
| 1271 |
+
if labels is not None:
|
| 1272 |
+
if self.config.loss_type == "regression":
|
| 1273 |
+
loss_fct = MSELoss()
|
| 1274 |
+
loss = loss_fct(logits, labels)
|
| 1275 |
+
elif self.config.loss_type == "classification":
|
| 1276 |
+
loss_fct = CrossEntropyLoss()
|
| 1277 |
+
loss = loss_fct(logits, labels)
|
| 1278 |
+
|
| 1279 |
+
if not return_dict:
|
| 1280 |
+
output = (logits,) + outputs[4:]
|
| 1281 |
+
return ((loss,) + output) if loss is not None else output
|
| 1282 |
+
|
| 1283 |
+
return SequenceClassifierOutput(
|
| 1284 |
+
loss=loss,
|
| 1285 |
+
logits=logits,
|
| 1286 |
+
hidden_states=outputs.hidden_states,
|
| 1287 |
+
attentions=outputs.attentions,
|
| 1288 |
+
)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/tvlt/processing_tvlt.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Processor class for TVLT.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from ....processing_utils import ProcessorMixin
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class TvltProcessor(ProcessorMixin):
|
| 23 |
+
r"""
|
| 24 |
+
Constructs a TVLT processor which wraps a TVLT image processor and TVLT feature extractor into a single processor.
|
| 25 |
+
|
| 26 |
+
[`TvltProcessor`] offers all the functionalities of [`TvltImageProcessor`] and [`TvltFeatureExtractor`]. See the
|
| 27 |
+
docstring of [`~TvltProcessor.__call__`] for more information.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
image_processor (`TvltImageProcessor`):
|
| 31 |
+
An instance of [`TvltImageProcessor`]. The image processor is a required input.
|
| 32 |
+
feature_extractor (`TvltFeatureExtractor`):
|
| 33 |
+
An instance of [`TvltFeatureExtractor`]. The feature extractor is a required input.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
attributes = ["image_processor", "feature_extractor"]
|
| 37 |
+
image_processor_class = "TvltImageProcessor"
|
| 38 |
+
feature_extractor_class = "TvltFeatureExtractor"
|
| 39 |
+
|
| 40 |
+
def __init__(self, image_processor, feature_extractor):
|
| 41 |
+
super().__init__(image_processor=image_processor, feature_extractor=feature_extractor)
|
| 42 |
+
|
| 43 |
+
self.image_processor = image_processor
|
| 44 |
+
self.feature_extractor = feature_extractor
|
| 45 |
+
|
| 46 |
+
def __call__(
|
| 47 |
+
self,
|
| 48 |
+
images=None,
|
| 49 |
+
audio=None,
|
| 50 |
+
images_mixed=None,
|
| 51 |
+
sampling_rate=None,
|
| 52 |
+
mask_audio=False,
|
| 53 |
+
mask_pixel=False,
|
| 54 |
+
*args,
|
| 55 |
+
**kwargs,
|
| 56 |
+
):
|
| 57 |
+
"""
|
| 58 |
+
Forwards the `images` argument to TvltImageProcessor's [`~TvltImageProcessor.preprocess`] and the `audio`
|
| 59 |
+
argument to TvltFeatureExtractor's [`~TvltFeatureExtractor.__call__`]. Please refer to the docstring of the
|
| 60 |
+
above two methods for more information.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
if images is None and audio is None:
|
| 64 |
+
raise ValueError("You need to specify either an `images` or `audio` input to process.")
|
| 65 |
+
|
| 66 |
+
images_mixed_dict = None
|
| 67 |
+
if images is not None:
|
| 68 |
+
images_dict = self.image_processor(images, mask_pixel=mask_pixel, *args, **kwargs)
|
| 69 |
+
if images_mixed is not None:
|
| 70 |
+
images_mixed_dict = self.image_processor(images_mixed, is_mixed=True, *args, **kwargs)
|
| 71 |
+
if audio is not None:
|
| 72 |
+
audio_dict = self.feature_extractor(
|
| 73 |
+
audio, *args, sampling_rate=sampling_rate, mask_audio=mask_audio, **kwargs
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
output_dict = {}
|
| 77 |
+
if audio is not None:
|
| 78 |
+
output_dict.update(audio_dict)
|
| 79 |
+
if images is not None:
|
| 80 |
+
output_dict.update(images_dict)
|
| 81 |
+
if images_mixed_dict is not None:
|
| 82 |
+
output_dict.update(images_mixed_dict)
|
| 83 |
+
return output_dict
|
| 84 |
+
|
| 85 |
+
@property
|
| 86 |
+
def model_input_names(self):
|
| 87 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 88 |
+
feature_extractor_input_names = self.feature_extractor.model_input_names
|
| 89 |
+
return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names))
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/van/__init__.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_import_structure = {"configuration_van": ["VanConfig"]}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
if not is_torch_available():
|
| 24 |
+
raise OptionalDependencyNotAvailable()
|
| 25 |
+
except OptionalDependencyNotAvailable:
|
| 26 |
+
pass
|
| 27 |
+
else:
|
| 28 |
+
_import_structure["modeling_van"] = [
|
| 29 |
+
"VanForImageClassification",
|
| 30 |
+
"VanModel",
|
| 31 |
+
"VanPreTrainedModel",
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
if TYPE_CHECKING:
|
| 35 |
+
from .configuration_van import VanConfig
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
if not is_torch_available():
|
| 39 |
+
raise OptionalDependencyNotAvailable()
|
| 40 |
+
except OptionalDependencyNotAvailable:
|
| 41 |
+
pass
|
| 42 |
+
else:
|
| 43 |
+
from .modeling_van import (
|
| 44 |
+
VanForImageClassification,
|
| 45 |
+
VanModel,
|
| 46 |
+
VanPreTrainedModel,
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
else:
|
| 50 |
+
import sys
|
| 51 |
+
|
| 52 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/van/configuration_van.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""VAN model configuration"""
|
| 16 |
+
|
| 17 |
+
from ....configuration_utils import PretrainedConfig
|
| 18 |
+
from ....utils import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class VanConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`VanModel`]. It is used to instantiate a VAN model
|
| 27 |
+
according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 28 |
+
defaults will yield a similar configuration to that of the VAN
|
| 29 |
+
[Visual-Attention-Network/van-base](https://huggingface.co/Visual-Attention-Network/van-base) architecture.
|
| 30 |
+
|
| 31 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 32 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 36 |
+
The size (resolution) of each image.
|
| 37 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 38 |
+
The number of input channels.
|
| 39 |
+
patch_sizes (`List[int]`, *optional*, defaults to `[7, 3, 3, 3]`):
|
| 40 |
+
Patch size to use in each stage's embedding layer.
|
| 41 |
+
strides (`List[int]`, *optional*, defaults to `[4, 2, 2, 2]`):
|
| 42 |
+
Stride size to use in each stage's embedding layer to downsample the input.
|
| 43 |
+
hidden_sizes (`List[int]`, *optional*, defaults to `[64, 128, 320, 512]`):
|
| 44 |
+
Dimensionality (hidden size) at each stage.
|
| 45 |
+
depths (`List[int]`, *optional*, defaults to `[3, 3, 12, 3]`):
|
| 46 |
+
Depth (number of layers) for each stage.
|
| 47 |
+
mlp_ratios (`List[int]`, *optional*, defaults to `[8, 8, 4, 4]`):
|
| 48 |
+
The expansion ratio for mlp layer at each stage.
|
| 49 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 50 |
+
The non-linear activation function (function or string) in each layer. If string, `"gelu"`, `"relu"`,
|
| 51 |
+
`"selu"` and `"gelu_new"` are supported.
|
| 52 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 53 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 54 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 55 |
+
The epsilon used by the layer normalization layers.
|
| 56 |
+
layer_scale_init_value (`float`, *optional*, defaults to 0.01):
|
| 57 |
+
The initial value for layer scaling.
|
| 58 |
+
drop_path_rate (`float`, *optional*, defaults to 0.0):
|
| 59 |
+
The dropout probability for stochastic depth.
|
| 60 |
+
dropout_rate (`float`, *optional*, defaults to 0.0):
|
| 61 |
+
The dropout probability for dropout.
|
| 62 |
+
|
| 63 |
+
Example:
|
| 64 |
+
```python
|
| 65 |
+
>>> from transformers import VanModel, VanConfig
|
| 66 |
+
|
| 67 |
+
>>> # Initializing a VAN van-base style configuration
|
| 68 |
+
>>> configuration = VanConfig()
|
| 69 |
+
>>> # Initializing a model from the van-base style configuration
|
| 70 |
+
>>> model = VanModel(configuration)
|
| 71 |
+
>>> # Accessing the model configuration
|
| 72 |
+
>>> configuration = model.config
|
| 73 |
+
```"""
|
| 74 |
+
|
| 75 |
+
model_type = "van"
|
| 76 |
+
|
| 77 |
+
def __init__(
|
| 78 |
+
self,
|
| 79 |
+
image_size=224,
|
| 80 |
+
num_channels=3,
|
| 81 |
+
patch_sizes=[7, 3, 3, 3],
|
| 82 |
+
strides=[4, 2, 2, 2],
|
| 83 |
+
hidden_sizes=[64, 128, 320, 512],
|
| 84 |
+
depths=[3, 3, 12, 3],
|
| 85 |
+
mlp_ratios=[8, 8, 4, 4],
|
| 86 |
+
hidden_act="gelu",
|
| 87 |
+
initializer_range=0.02,
|
| 88 |
+
layer_norm_eps=1e-6,
|
| 89 |
+
layer_scale_init_value=1e-2,
|
| 90 |
+
drop_path_rate=0.0,
|
| 91 |
+
dropout_rate=0.0,
|
| 92 |
+
**kwargs,
|
| 93 |
+
):
|
| 94 |
+
super().__init__(**kwargs)
|
| 95 |
+
self.image_size = image_size
|
| 96 |
+
self.num_channels = num_channels
|
| 97 |
+
self.patch_sizes = patch_sizes
|
| 98 |
+
self.strides = strides
|
| 99 |
+
self.hidden_sizes = hidden_sizes
|
| 100 |
+
self.depths = depths
|
| 101 |
+
self.mlp_ratios = mlp_ratios
|
| 102 |
+
self.hidden_act = hidden_act
|
| 103 |
+
self.initializer_range = initializer_range
|
| 104 |
+
self.layer_norm_eps = layer_norm_eps
|
| 105 |
+
self.layer_scale_init_value = layer_scale_init_value
|
| 106 |
+
self.drop_path_rate = drop_path_rate
|
| 107 |
+
self.dropout_rate = dropout_rate
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/van/convert_van_to_pytorch.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 BNRist (Tsinghua University), TKLNDST (Nankai University) 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 |
+
"""Convert VAN checkpoints from the original repository.
|
| 16 |
+
|
| 17 |
+
URL: https://github.com/Visual-Attention-Network/VAN-Classification"""
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import json
|
| 21 |
+
import sys
|
| 22 |
+
from dataclasses import dataclass, field
|
| 23 |
+
from functools import partial
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
from typing import List
|
| 26 |
+
|
| 27 |
+
import torch
|
| 28 |
+
import torch.nn as nn
|
| 29 |
+
from huggingface_hub import cached_download, hf_hub_download
|
| 30 |
+
from torch import Tensor
|
| 31 |
+
|
| 32 |
+
from transformers import AutoImageProcessor, VanConfig, VanForImageClassification
|
| 33 |
+
from transformers.models.deprecated.van.modeling_van import VanLayerScaling
|
| 34 |
+
from transformers.utils import logging
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
logging.set_verbosity_info()
|
| 38 |
+
logger = logging.get_logger(__name__)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@dataclass
|
| 42 |
+
class Tracker:
|
| 43 |
+
module: nn.Module
|
| 44 |
+
traced: List[nn.Module] = field(default_factory=list)
|
| 45 |
+
handles: list = field(default_factory=list)
|
| 46 |
+
|
| 47 |
+
def _forward_hook(self, m, inputs: Tensor, outputs: Tensor):
|
| 48 |
+
has_not_submodules = len(list(m.modules())) == 1 or isinstance(m, nn.Conv2d) or isinstance(m, nn.BatchNorm2d)
|
| 49 |
+
if has_not_submodules:
|
| 50 |
+
if not isinstance(m, VanLayerScaling):
|
| 51 |
+
self.traced.append(m)
|
| 52 |
+
|
| 53 |
+
def __call__(self, x: Tensor):
|
| 54 |
+
for m in self.module.modules():
|
| 55 |
+
self.handles.append(m.register_forward_hook(self._forward_hook))
|
| 56 |
+
self.module(x)
|
| 57 |
+
[x.remove() for x in self.handles]
|
| 58 |
+
return self
|
| 59 |
+
|
| 60 |
+
@property
|
| 61 |
+
def parametrized(self):
|
| 62 |
+
# check the len of the state_dict keys to see if we have learnable params
|
| 63 |
+
return list(filter(lambda x: len(list(x.state_dict().keys())) > 0, self.traced))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@dataclass
|
| 67 |
+
class ModuleTransfer:
|
| 68 |
+
src: nn.Module
|
| 69 |
+
dest: nn.Module
|
| 70 |
+
verbose: int = 0
|
| 71 |
+
src_skip: List = field(default_factory=list)
|
| 72 |
+
dest_skip: List = field(default_factory=list)
|
| 73 |
+
|
| 74 |
+
def __call__(self, x: Tensor):
|
| 75 |
+
"""
|
| 76 |
+
Transfer the weights of `self.src` to `self.dest` by performing a forward pass using `x` as input. Under the
|
| 77 |
+
hood we tracked all the operations in both modules.
|
| 78 |
+
"""
|
| 79 |
+
dest_traced = Tracker(self.dest)(x).parametrized
|
| 80 |
+
src_traced = Tracker(self.src)(x).parametrized
|
| 81 |
+
|
| 82 |
+
src_traced = list(filter(lambda x: type(x) not in self.src_skip, src_traced))
|
| 83 |
+
dest_traced = list(filter(lambda x: type(x) not in self.dest_skip, dest_traced))
|
| 84 |
+
|
| 85 |
+
if len(dest_traced) != len(src_traced):
|
| 86 |
+
raise Exception(
|
| 87 |
+
f"Numbers of operations are different. Source module has {len(src_traced)} operations while"
|
| 88 |
+
f" destination module has {len(dest_traced)}."
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
for dest_m, src_m in zip(dest_traced, src_traced):
|
| 92 |
+
dest_m.load_state_dict(src_m.state_dict())
|
| 93 |
+
if self.verbose == 1:
|
| 94 |
+
print(f"Transfered from={src_m} to={dest_m}")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def copy_parameters(from_model: nn.Module, our_model: nn.Module) -> nn.Module:
|
| 98 |
+
# nn.Parameter cannot be tracked by the Tracker, thus we need to manually convert them
|
| 99 |
+
from_state_dict = from_model.state_dict()
|
| 100 |
+
our_state_dict = our_model.state_dict()
|
| 101 |
+
config = our_model.config
|
| 102 |
+
all_keys = []
|
| 103 |
+
for stage_idx in range(len(config.hidden_sizes)):
|
| 104 |
+
for block_id in range(config.depths[stage_idx]):
|
| 105 |
+
from_key = f"block{stage_idx + 1}.{block_id}.layer_scale_1"
|
| 106 |
+
to_key = f"van.encoder.stages.{stage_idx}.layers.{block_id}.attention_scaling.weight"
|
| 107 |
+
|
| 108 |
+
all_keys.append((from_key, to_key))
|
| 109 |
+
from_key = f"block{stage_idx + 1}.{block_id}.layer_scale_2"
|
| 110 |
+
to_key = f"van.encoder.stages.{stage_idx}.layers.{block_id}.mlp_scaling.weight"
|
| 111 |
+
|
| 112 |
+
all_keys.append((from_key, to_key))
|
| 113 |
+
|
| 114 |
+
for from_key, to_key in all_keys:
|
| 115 |
+
our_state_dict[to_key] = from_state_dict.pop(from_key)
|
| 116 |
+
|
| 117 |
+
our_model.load_state_dict(our_state_dict)
|
| 118 |
+
return our_model
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def convert_weight_and_push(
|
| 122 |
+
name: str,
|
| 123 |
+
config: VanConfig,
|
| 124 |
+
checkpoint: str,
|
| 125 |
+
from_model: nn.Module,
|
| 126 |
+
save_directory: Path,
|
| 127 |
+
push_to_hub: bool = True,
|
| 128 |
+
):
|
| 129 |
+
print(f"Downloading weights for {name}...")
|
| 130 |
+
checkpoint_path = cached_download(checkpoint)
|
| 131 |
+
print(f"Converting {name}...")
|
| 132 |
+
from_state_dict = torch.load(checkpoint_path)["state_dict"]
|
| 133 |
+
from_model.load_state_dict(from_state_dict)
|
| 134 |
+
from_model.eval()
|
| 135 |
+
with torch.no_grad():
|
| 136 |
+
our_model = VanForImageClassification(config).eval()
|
| 137 |
+
module_transfer = ModuleTransfer(src=from_model, dest=our_model)
|
| 138 |
+
x = torch.randn((1, 3, 224, 224))
|
| 139 |
+
module_transfer(x)
|
| 140 |
+
our_model = copy_parameters(from_model, our_model)
|
| 141 |
+
|
| 142 |
+
if not torch.allclose(from_model(x), our_model(x).logits):
|
| 143 |
+
raise ValueError("The model logits don't match the original one.")
|
| 144 |
+
|
| 145 |
+
checkpoint_name = name
|
| 146 |
+
print(checkpoint_name)
|
| 147 |
+
|
| 148 |
+
if push_to_hub:
|
| 149 |
+
our_model.push_to_hub(
|
| 150 |
+
repo_path_or_name=save_directory / checkpoint_name,
|
| 151 |
+
commit_message="Add model",
|
| 152 |
+
use_temp_dir=True,
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
# we can use the convnext one
|
| 156 |
+
image_processor = AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k")
|
| 157 |
+
image_processor.push_to_hub(
|
| 158 |
+
repo_path_or_name=save_directory / checkpoint_name,
|
| 159 |
+
commit_message="Add image processor",
|
| 160 |
+
use_temp_dir=True,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
print(f"Pushed {checkpoint_name}")
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def convert_weights_and_push(save_directory: Path, model_name: str = None, push_to_hub: bool = True):
|
| 167 |
+
filename = "imagenet-1k-id2label.json"
|
| 168 |
+
num_labels = 1000
|
| 169 |
+
|
| 170 |
+
repo_id = "huggingface/label-files"
|
| 171 |
+
num_labels = num_labels
|
| 172 |
+
id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
|
| 173 |
+
id2label = {int(k): v for k, v in id2label.items()}
|
| 174 |
+
|
| 175 |
+
id2label = id2label
|
| 176 |
+
label2id = {v: k for k, v in id2label.items()}
|
| 177 |
+
|
| 178 |
+
ImageNetPreTrainedConfig = partial(VanConfig, num_labels=num_labels, id2label=id2label, label2id=label2id)
|
| 179 |
+
|
| 180 |
+
names_to_config = {
|
| 181 |
+
"van-tiny": ImageNetPreTrainedConfig(
|
| 182 |
+
hidden_sizes=[32, 64, 160, 256],
|
| 183 |
+
depths=[3, 3, 5, 2],
|
| 184 |
+
mlp_ratios=[8, 8, 4, 4],
|
| 185 |
+
),
|
| 186 |
+
"van-small": ImageNetPreTrainedConfig(
|
| 187 |
+
hidden_sizes=[64, 128, 320, 512],
|
| 188 |
+
depths=[2, 2, 4, 2],
|
| 189 |
+
mlp_ratios=[8, 8, 4, 4],
|
| 190 |
+
),
|
| 191 |
+
"van-base": ImageNetPreTrainedConfig(
|
| 192 |
+
hidden_sizes=[64, 128, 320, 512],
|
| 193 |
+
depths=[3, 3, 12, 3],
|
| 194 |
+
mlp_ratios=[8, 8, 4, 4],
|
| 195 |
+
),
|
| 196 |
+
"van-large": ImageNetPreTrainedConfig(
|
| 197 |
+
hidden_sizes=[64, 128, 320, 512],
|
| 198 |
+
depths=[3, 5, 27, 3],
|
| 199 |
+
mlp_ratios=[8, 8, 4, 4],
|
| 200 |
+
),
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
names_to_original_models = {
|
| 204 |
+
"van-tiny": van_tiny,
|
| 205 |
+
"van-small": van_small,
|
| 206 |
+
"van-base": van_base,
|
| 207 |
+
"van-large": van_large,
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
names_to_original_checkpoints = {
|
| 211 |
+
"van-tiny": (
|
| 212 |
+
"https://huggingface.co/Visual-Attention-Network/VAN-Tiny-original/resolve/main/van_tiny_754.pth.tar"
|
| 213 |
+
),
|
| 214 |
+
"van-small": (
|
| 215 |
+
"https://huggingface.co/Visual-Attention-Network/VAN-Small-original/resolve/main/van_small_811.pth.tar"
|
| 216 |
+
),
|
| 217 |
+
"van-base": (
|
| 218 |
+
"https://huggingface.co/Visual-Attention-Network/VAN-Base-original/resolve/main/van_base_828.pth.tar"
|
| 219 |
+
),
|
| 220 |
+
"van-large": (
|
| 221 |
+
"https://huggingface.co/Visual-Attention-Network/VAN-Large-original/resolve/main/van_large_839.pth.tar"
|
| 222 |
+
),
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
if model_name:
|
| 226 |
+
convert_weight_and_push(
|
| 227 |
+
model_name,
|
| 228 |
+
names_to_config[model_name],
|
| 229 |
+
checkpoint=names_to_original_checkpoints[model_name],
|
| 230 |
+
from_model=names_to_original_models[model_name](),
|
| 231 |
+
save_directory=save_directory,
|
| 232 |
+
push_to_hub=push_to_hub,
|
| 233 |
+
)
|
| 234 |
+
else:
|
| 235 |
+
for model_name, config in names_to_config.items():
|
| 236 |
+
convert_weight_and_push(
|
| 237 |
+
model_name,
|
| 238 |
+
config,
|
| 239 |
+
checkpoint=names_to_original_checkpoints[model_name],
|
| 240 |
+
from_model=names_to_original_models[model_name](),
|
| 241 |
+
save_directory=save_directory,
|
| 242 |
+
push_to_hub=push_to_hub,
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
if __name__ == "__main__":
|
| 247 |
+
parser = argparse.ArgumentParser()
|
| 248 |
+
# Required parameters
|
| 249 |
+
parser.add_argument(
|
| 250 |
+
"--model-name",
|
| 251 |
+
default=None,
|
| 252 |
+
type=str,
|
| 253 |
+
help=(
|
| 254 |
+
"The name of the model you wish to convert, it must be one of the supported resnet* architecture,"
|
| 255 |
+
" currently: van-tiny/small/base/large. If `None`, all of them will the converted."
|
| 256 |
+
),
|
| 257 |
+
)
|
| 258 |
+
parser.add_argument(
|
| 259 |
+
"--pytorch_dump_folder_path",
|
| 260 |
+
default=None,
|
| 261 |
+
type=Path,
|
| 262 |
+
required=True,
|
| 263 |
+
help="Path to the output PyTorch model directory.",
|
| 264 |
+
)
|
| 265 |
+
parser.add_argument(
|
| 266 |
+
"--van_dir",
|
| 267 |
+
required=True,
|
| 268 |
+
type=Path,
|
| 269 |
+
help=(
|
| 270 |
+
"A path to VAN's original implementation directory. You can download from here:"
|
| 271 |
+
" https://github.com/Visual-Attention-Network/VAN-Classification"
|
| 272 |
+
),
|
| 273 |
+
)
|
| 274 |
+
parser.add_argument(
|
| 275 |
+
"--push_to_hub",
|
| 276 |
+
default=True,
|
| 277 |
+
type=bool,
|
| 278 |
+
required=False,
|
| 279 |
+
help="If True, push model and image processor to the hub.",
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
args = parser.parse_args()
|
| 283 |
+
pytorch_dump_folder_path: Path = args.pytorch_dump_folder_path
|
| 284 |
+
pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
|
| 285 |
+
van_dir = args.van_dir
|
| 286 |
+
# append the path to the parents to maskformer dir
|
| 287 |
+
sys.path.append(str(van_dir.parent))
|
| 288 |
+
from van.models.van import van_base, van_large, van_small, van_tiny
|
| 289 |
+
|
| 290 |
+
convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/van/modeling_van.py
ADDED
|
@@ -0,0 +1,536 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 BNRist (Tsinghua University), TKLNDST (Nankai University) and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch Visual Attention Network (VAN) model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from collections import OrderedDict
|
| 19 |
+
from typing import Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.utils.checkpoint
|
| 23 |
+
from torch import nn
|
| 24 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 25 |
+
|
| 26 |
+
from ....activations import ACT2FN
|
| 27 |
+
from ....modeling_outputs import (
|
| 28 |
+
BaseModelOutputWithNoAttention,
|
| 29 |
+
BaseModelOutputWithPoolingAndNoAttention,
|
| 30 |
+
ImageClassifierOutputWithNoAttention,
|
| 31 |
+
)
|
| 32 |
+
from ....modeling_utils import PreTrainedModel
|
| 33 |
+
from ....utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
|
| 34 |
+
from .configuration_van import VanConfig
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
logger = logging.get_logger(__name__)
|
| 38 |
+
|
| 39 |
+
# General docstring
|
| 40 |
+
_CONFIG_FOR_DOC = "VanConfig"
|
| 41 |
+
|
| 42 |
+
# Base docstring
|
| 43 |
+
_CHECKPOINT_FOR_DOC = "Visual-Attention-Network/van-base"
|
| 44 |
+
_EXPECTED_OUTPUT_SHAPE = [1, 512, 7, 7]
|
| 45 |
+
|
| 46 |
+
# Image classification docstring
|
| 47 |
+
_IMAGE_CLASS_CHECKPOINT = "Visual-Attention-Network/van-base"
|
| 48 |
+
_IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
|
| 52 |
+
"""
|
| 53 |
+
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 54 |
+
|
| 55 |
+
Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
|
| 56 |
+
however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
|
| 57 |
+
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
|
| 58 |
+
layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
|
| 59 |
+
argument.
|
| 60 |
+
"""
|
| 61 |
+
if drop_prob == 0.0 or not training:
|
| 62 |
+
return input
|
| 63 |
+
keep_prob = 1 - drop_prob
|
| 64 |
+
shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 65 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
|
| 66 |
+
random_tensor.floor_() # binarize
|
| 67 |
+
output = input.div(keep_prob) * random_tensor
|
| 68 |
+
return output
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class VanDropPath(nn.Module):
|
| 72 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 73 |
+
|
| 74 |
+
def __init__(self, drop_prob: Optional[float] = None) -> None:
|
| 75 |
+
super().__init__()
|
| 76 |
+
self.drop_prob = drop_prob
|
| 77 |
+
|
| 78 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 79 |
+
return drop_path(hidden_states, self.drop_prob, self.training)
|
| 80 |
+
|
| 81 |
+
def extra_repr(self) -> str:
|
| 82 |
+
return "p={}".format(self.drop_prob)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class VanOverlappingPatchEmbedder(nn.Module):
|
| 86 |
+
"""
|
| 87 |
+
Downsamples the input using a patchify operation with a `stride` of 4 by default making adjacent windows overlap by
|
| 88 |
+
half of the area. From [PVTv2: Improved Baselines with Pyramid Vision
|
| 89 |
+
Transformer](https://arxiv.org/abs/2106.13797).
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
def __init__(self, in_channels: int, hidden_size: int, patch_size: int = 7, stride: int = 4):
|
| 93 |
+
super().__init__()
|
| 94 |
+
self.convolution = nn.Conv2d(
|
| 95 |
+
in_channels, hidden_size, kernel_size=patch_size, stride=stride, padding=patch_size // 2
|
| 96 |
+
)
|
| 97 |
+
self.normalization = nn.BatchNorm2d(hidden_size)
|
| 98 |
+
|
| 99 |
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
|
| 100 |
+
hidden_state = self.convolution(input)
|
| 101 |
+
hidden_state = self.normalization(hidden_state)
|
| 102 |
+
return hidden_state
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class VanMlpLayer(nn.Module):
|
| 106 |
+
"""
|
| 107 |
+
MLP with depth-wise convolution, from [PVTv2: Improved Baselines with Pyramid Vision
|
| 108 |
+
Transformer](https://arxiv.org/abs/2106.13797).
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
def __init__(
|
| 112 |
+
self,
|
| 113 |
+
in_channels: int,
|
| 114 |
+
hidden_size: int,
|
| 115 |
+
out_channels: int,
|
| 116 |
+
hidden_act: str = "gelu",
|
| 117 |
+
dropout_rate: float = 0.5,
|
| 118 |
+
):
|
| 119 |
+
super().__init__()
|
| 120 |
+
self.in_dense = nn.Conv2d(in_channels, hidden_size, kernel_size=1)
|
| 121 |
+
self.depth_wise = nn.Conv2d(hidden_size, hidden_size, kernel_size=3, padding=1, groups=hidden_size)
|
| 122 |
+
self.activation = ACT2FN[hidden_act]
|
| 123 |
+
self.dropout1 = nn.Dropout(dropout_rate)
|
| 124 |
+
self.out_dense = nn.Conv2d(hidden_size, out_channels, kernel_size=1)
|
| 125 |
+
self.dropout2 = nn.Dropout(dropout_rate)
|
| 126 |
+
|
| 127 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 128 |
+
hidden_state = self.in_dense(hidden_state)
|
| 129 |
+
hidden_state = self.depth_wise(hidden_state)
|
| 130 |
+
hidden_state = self.activation(hidden_state)
|
| 131 |
+
hidden_state = self.dropout1(hidden_state)
|
| 132 |
+
hidden_state = self.out_dense(hidden_state)
|
| 133 |
+
hidden_state = self.dropout2(hidden_state)
|
| 134 |
+
return hidden_state
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class VanLargeKernelAttention(nn.Module):
|
| 138 |
+
"""
|
| 139 |
+
Basic Large Kernel Attention (LKA).
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
def __init__(self, hidden_size: int):
|
| 143 |
+
super().__init__()
|
| 144 |
+
self.depth_wise = nn.Conv2d(hidden_size, hidden_size, kernel_size=5, padding=2, groups=hidden_size)
|
| 145 |
+
self.depth_wise_dilated = nn.Conv2d(
|
| 146 |
+
hidden_size, hidden_size, kernel_size=7, dilation=3, padding=9, groups=hidden_size
|
| 147 |
+
)
|
| 148 |
+
self.point_wise = nn.Conv2d(hidden_size, hidden_size, kernel_size=1)
|
| 149 |
+
|
| 150 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 151 |
+
hidden_state = self.depth_wise(hidden_state)
|
| 152 |
+
hidden_state = self.depth_wise_dilated(hidden_state)
|
| 153 |
+
hidden_state = self.point_wise(hidden_state)
|
| 154 |
+
return hidden_state
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class VanLargeKernelAttentionLayer(nn.Module):
|
| 158 |
+
"""
|
| 159 |
+
Computes attention using Large Kernel Attention (LKA) and attends the input.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
def __init__(self, hidden_size: int):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.attention = VanLargeKernelAttention(hidden_size)
|
| 165 |
+
|
| 166 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 167 |
+
attention = self.attention(hidden_state)
|
| 168 |
+
attended = hidden_state * attention
|
| 169 |
+
return attended
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class VanSpatialAttentionLayer(nn.Module):
|
| 173 |
+
"""
|
| 174 |
+
Van spatial attention layer composed by projection (via conv) -> act -> Large Kernel Attention (LKA) attention ->
|
| 175 |
+
projection (via conv) + residual connection.
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
def __init__(self, hidden_size: int, hidden_act: str = "gelu"):
|
| 179 |
+
super().__init__()
|
| 180 |
+
self.pre_projection = nn.Sequential(
|
| 181 |
+
OrderedDict(
|
| 182 |
+
[
|
| 183 |
+
("conv", nn.Conv2d(hidden_size, hidden_size, kernel_size=1)),
|
| 184 |
+
("act", ACT2FN[hidden_act]),
|
| 185 |
+
]
|
| 186 |
+
)
|
| 187 |
+
)
|
| 188 |
+
self.attention_layer = VanLargeKernelAttentionLayer(hidden_size)
|
| 189 |
+
self.post_projection = nn.Conv2d(hidden_size, hidden_size, kernel_size=1)
|
| 190 |
+
|
| 191 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 192 |
+
residual = hidden_state
|
| 193 |
+
hidden_state = self.pre_projection(hidden_state)
|
| 194 |
+
hidden_state = self.attention_layer(hidden_state)
|
| 195 |
+
hidden_state = self.post_projection(hidden_state)
|
| 196 |
+
hidden_state = hidden_state + residual
|
| 197 |
+
return hidden_state
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class VanLayerScaling(nn.Module):
|
| 201 |
+
"""
|
| 202 |
+
Scales the inputs by a learnable parameter initialized by `initial_value`.
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
def __init__(self, hidden_size: int, initial_value: float = 1e-2):
|
| 206 |
+
super().__init__()
|
| 207 |
+
self.weight = nn.Parameter(initial_value * torch.ones((hidden_size)), requires_grad=True)
|
| 208 |
+
|
| 209 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 210 |
+
# unsqueezing for broadcasting
|
| 211 |
+
hidden_state = self.weight.unsqueeze(-1).unsqueeze(-1) * hidden_state
|
| 212 |
+
return hidden_state
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class VanLayer(nn.Module):
|
| 216 |
+
"""
|
| 217 |
+
Van layer composed by normalization layers, large kernel attention (LKA) and a multi layer perceptron (MLP).
|
| 218 |
+
"""
|
| 219 |
+
|
| 220 |
+
def __init__(
|
| 221 |
+
self,
|
| 222 |
+
config: VanConfig,
|
| 223 |
+
hidden_size: int,
|
| 224 |
+
mlp_ratio: int = 4,
|
| 225 |
+
drop_path_rate: float = 0.5,
|
| 226 |
+
):
|
| 227 |
+
super().__init__()
|
| 228 |
+
self.drop_path = VanDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
|
| 229 |
+
self.pre_normomalization = nn.BatchNorm2d(hidden_size)
|
| 230 |
+
self.attention = VanSpatialAttentionLayer(hidden_size, config.hidden_act)
|
| 231 |
+
self.attention_scaling = VanLayerScaling(hidden_size, config.layer_scale_init_value)
|
| 232 |
+
self.post_normalization = nn.BatchNorm2d(hidden_size)
|
| 233 |
+
self.mlp = VanMlpLayer(
|
| 234 |
+
hidden_size, hidden_size * mlp_ratio, hidden_size, config.hidden_act, config.dropout_rate
|
| 235 |
+
)
|
| 236 |
+
self.mlp_scaling = VanLayerScaling(hidden_size, config.layer_scale_init_value)
|
| 237 |
+
|
| 238 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 239 |
+
residual = hidden_state
|
| 240 |
+
# attention
|
| 241 |
+
hidden_state = self.pre_normomalization(hidden_state)
|
| 242 |
+
hidden_state = self.attention(hidden_state)
|
| 243 |
+
hidden_state = self.attention_scaling(hidden_state)
|
| 244 |
+
hidden_state = self.drop_path(hidden_state)
|
| 245 |
+
# residual connection
|
| 246 |
+
hidden_state = residual + hidden_state
|
| 247 |
+
residual = hidden_state
|
| 248 |
+
# mlp
|
| 249 |
+
hidden_state = self.post_normalization(hidden_state)
|
| 250 |
+
hidden_state = self.mlp(hidden_state)
|
| 251 |
+
hidden_state = self.mlp_scaling(hidden_state)
|
| 252 |
+
hidden_state = self.drop_path(hidden_state)
|
| 253 |
+
# residual connection
|
| 254 |
+
hidden_state = residual + hidden_state
|
| 255 |
+
return hidden_state
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
class VanStage(nn.Module):
|
| 259 |
+
"""
|
| 260 |
+
VanStage, consisting of multiple layers.
|
| 261 |
+
"""
|
| 262 |
+
|
| 263 |
+
def __init__(
|
| 264 |
+
self,
|
| 265 |
+
config: VanConfig,
|
| 266 |
+
in_channels: int,
|
| 267 |
+
hidden_size: int,
|
| 268 |
+
patch_size: int,
|
| 269 |
+
stride: int,
|
| 270 |
+
depth: int,
|
| 271 |
+
mlp_ratio: int = 4,
|
| 272 |
+
drop_path_rate: float = 0.0,
|
| 273 |
+
):
|
| 274 |
+
super().__init__()
|
| 275 |
+
self.embeddings = VanOverlappingPatchEmbedder(in_channels, hidden_size, patch_size, stride)
|
| 276 |
+
self.layers = nn.Sequential(
|
| 277 |
+
*[
|
| 278 |
+
VanLayer(
|
| 279 |
+
config,
|
| 280 |
+
hidden_size,
|
| 281 |
+
mlp_ratio=mlp_ratio,
|
| 282 |
+
drop_path_rate=drop_path_rate,
|
| 283 |
+
)
|
| 284 |
+
for _ in range(depth)
|
| 285 |
+
]
|
| 286 |
+
)
|
| 287 |
+
self.normalization = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
|
| 288 |
+
|
| 289 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 290 |
+
hidden_state = self.embeddings(hidden_state)
|
| 291 |
+
hidden_state = self.layers(hidden_state)
|
| 292 |
+
# rearrange b c h w -> b (h w) c
|
| 293 |
+
batch_size, hidden_size, height, width = hidden_state.shape
|
| 294 |
+
hidden_state = hidden_state.flatten(2).transpose(1, 2)
|
| 295 |
+
hidden_state = self.normalization(hidden_state)
|
| 296 |
+
# rearrange b (h w) c- > b c h w
|
| 297 |
+
hidden_state = hidden_state.view(batch_size, height, width, hidden_size).permute(0, 3, 1, 2)
|
| 298 |
+
return hidden_state
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
class VanEncoder(nn.Module):
|
| 302 |
+
"""
|
| 303 |
+
VanEncoder, consisting of multiple stages.
|
| 304 |
+
"""
|
| 305 |
+
|
| 306 |
+
def __init__(self, config: VanConfig):
|
| 307 |
+
super().__init__()
|
| 308 |
+
self.stages = nn.ModuleList([])
|
| 309 |
+
patch_sizes = config.patch_sizes
|
| 310 |
+
strides = config.strides
|
| 311 |
+
hidden_sizes = config.hidden_sizes
|
| 312 |
+
depths = config.depths
|
| 313 |
+
mlp_ratios = config.mlp_ratios
|
| 314 |
+
drop_path_rates = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths))]
|
| 315 |
+
|
| 316 |
+
for num_stage, (patch_size, stride, hidden_size, depth, mlp_expantion, drop_path_rate) in enumerate(
|
| 317 |
+
zip(patch_sizes, strides, hidden_sizes, depths, mlp_ratios, drop_path_rates)
|
| 318 |
+
):
|
| 319 |
+
is_first_stage = num_stage == 0
|
| 320 |
+
in_channels = hidden_sizes[num_stage - 1]
|
| 321 |
+
if is_first_stage:
|
| 322 |
+
in_channels = config.num_channels
|
| 323 |
+
self.stages.append(
|
| 324 |
+
VanStage(
|
| 325 |
+
config,
|
| 326 |
+
in_channels,
|
| 327 |
+
hidden_size,
|
| 328 |
+
patch_size=patch_size,
|
| 329 |
+
stride=stride,
|
| 330 |
+
depth=depth,
|
| 331 |
+
mlp_ratio=mlp_expantion,
|
| 332 |
+
drop_path_rate=drop_path_rate,
|
| 333 |
+
)
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
def forward(
|
| 337 |
+
self,
|
| 338 |
+
hidden_state: torch.Tensor,
|
| 339 |
+
output_hidden_states: Optional[bool] = False,
|
| 340 |
+
return_dict: Optional[bool] = True,
|
| 341 |
+
) -> Union[Tuple, BaseModelOutputWithNoAttention]:
|
| 342 |
+
all_hidden_states = () if output_hidden_states else None
|
| 343 |
+
|
| 344 |
+
for _, stage_module in enumerate(self.stages):
|
| 345 |
+
hidden_state = stage_module(hidden_state)
|
| 346 |
+
|
| 347 |
+
if output_hidden_states:
|
| 348 |
+
all_hidden_states = all_hidden_states + (hidden_state,)
|
| 349 |
+
|
| 350 |
+
if not return_dict:
|
| 351 |
+
return tuple(v for v in [hidden_state, all_hidden_states] if v is not None)
|
| 352 |
+
|
| 353 |
+
return BaseModelOutputWithNoAttention(last_hidden_state=hidden_state, hidden_states=all_hidden_states)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
class VanPreTrainedModel(PreTrainedModel):
|
| 357 |
+
"""
|
| 358 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 359 |
+
models.
|
| 360 |
+
"""
|
| 361 |
+
|
| 362 |
+
config_class = VanConfig
|
| 363 |
+
base_model_prefix = "van"
|
| 364 |
+
main_input_name = "pixel_values"
|
| 365 |
+
supports_gradient_checkpointing = True
|
| 366 |
+
|
| 367 |
+
def _init_weights(self, module):
|
| 368 |
+
"""Initialize the weights"""
|
| 369 |
+
if isinstance(module, nn.Linear):
|
| 370 |
+
nn.init.trunc_normal_(module.weight, std=self.config.initializer_range)
|
| 371 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
| 372 |
+
nn.init.constant_(module.bias, 0)
|
| 373 |
+
elif isinstance(module, nn.LayerNorm):
|
| 374 |
+
nn.init.constant_(module.bias, 0)
|
| 375 |
+
nn.init.constant_(module.weight, 1.0)
|
| 376 |
+
elif isinstance(module, nn.Conv2d):
|
| 377 |
+
fan_out = module.kernel_size[0] * module.kernel_size[1] * module.out_channels
|
| 378 |
+
fan_out //= module.groups
|
| 379 |
+
module.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
|
| 380 |
+
if module.bias is not None:
|
| 381 |
+
module.bias.data.zero_()
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
VAN_START_DOCSTRING = r"""
|
| 385 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 386 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 387 |
+
behavior.
|
| 388 |
+
|
| 389 |
+
Parameters:
|
| 390 |
+
config ([`VanConfig`]): Model configuration class with all the parameters of the model.
|
| 391 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 392 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 393 |
+
"""
|
| 394 |
+
|
| 395 |
+
VAN_INPUTS_DOCSTRING = r"""
|
| 396 |
+
Args:
|
| 397 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 398 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
|
| 399 |
+
[`ConvNextImageProcessor.__call__`] for details.
|
| 400 |
+
|
| 401 |
+
output_hidden_states (`bool`, *optional*):
|
| 402 |
+
Whether or not to return the hidden states of all stages. See `hidden_states` under returned tensors for
|
| 403 |
+
more detail.
|
| 404 |
+
return_dict (`bool`, *optional*):
|
| 405 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 406 |
+
"""
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
@add_start_docstrings(
|
| 410 |
+
"The bare VAN model outputting raw features without any specific head on top. Note, VAN does not have an embedding"
|
| 411 |
+
" layer.",
|
| 412 |
+
VAN_START_DOCSTRING,
|
| 413 |
+
)
|
| 414 |
+
class VanModel(VanPreTrainedModel):
|
| 415 |
+
def __init__(self, config):
|
| 416 |
+
super().__init__(config)
|
| 417 |
+
self.config = config
|
| 418 |
+
self.encoder = VanEncoder(config)
|
| 419 |
+
# final layernorm layer
|
| 420 |
+
self.layernorm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)
|
| 421 |
+
# Initialize weights and apply final processing
|
| 422 |
+
self.post_init()
|
| 423 |
+
|
| 424 |
+
@add_start_docstrings_to_model_forward(VAN_INPUTS_DOCSTRING)
|
| 425 |
+
@add_code_sample_docstrings(
|
| 426 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 427 |
+
output_type=BaseModelOutputWithPoolingAndNoAttention,
|
| 428 |
+
config_class=_CONFIG_FOR_DOC,
|
| 429 |
+
modality="vision",
|
| 430 |
+
expected_output=_EXPECTED_OUTPUT_SHAPE,
|
| 431 |
+
)
|
| 432 |
+
def forward(
|
| 433 |
+
self,
|
| 434 |
+
pixel_values: Optional[torch.FloatTensor],
|
| 435 |
+
output_hidden_states: Optional[bool] = None,
|
| 436 |
+
return_dict: Optional[bool] = None,
|
| 437 |
+
) -> Union[Tuple, BaseModelOutputWithPoolingAndNoAttention]:
|
| 438 |
+
output_hidden_states = (
|
| 439 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 440 |
+
)
|
| 441 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 442 |
+
|
| 443 |
+
encoder_outputs = self.encoder(
|
| 444 |
+
pixel_values,
|
| 445 |
+
output_hidden_states=output_hidden_states,
|
| 446 |
+
return_dict=return_dict,
|
| 447 |
+
)
|
| 448 |
+
last_hidden_state = encoder_outputs[0]
|
| 449 |
+
# global average pooling, n c w h -> n c
|
| 450 |
+
pooled_output = last_hidden_state.mean(dim=[-2, -1])
|
| 451 |
+
|
| 452 |
+
if not return_dict:
|
| 453 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 454 |
+
|
| 455 |
+
return BaseModelOutputWithPoolingAndNoAttention(
|
| 456 |
+
last_hidden_state=last_hidden_state,
|
| 457 |
+
pooler_output=pooled_output,
|
| 458 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
@add_start_docstrings(
|
| 463 |
+
"""
|
| 464 |
+
VAN Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
|
| 465 |
+
ImageNet.
|
| 466 |
+
""",
|
| 467 |
+
VAN_START_DOCSTRING,
|
| 468 |
+
)
|
| 469 |
+
class VanForImageClassification(VanPreTrainedModel):
|
| 470 |
+
def __init__(self, config):
|
| 471 |
+
super().__init__(config)
|
| 472 |
+
self.van = VanModel(config)
|
| 473 |
+
# Classifier head
|
| 474 |
+
self.classifier = (
|
| 475 |
+
nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
# Initialize weights and apply final processing
|
| 479 |
+
self.post_init()
|
| 480 |
+
|
| 481 |
+
@add_start_docstrings_to_model_forward(VAN_INPUTS_DOCSTRING)
|
| 482 |
+
@add_code_sample_docstrings(
|
| 483 |
+
checkpoint=_IMAGE_CLASS_CHECKPOINT,
|
| 484 |
+
output_type=ImageClassifierOutputWithNoAttention,
|
| 485 |
+
config_class=_CONFIG_FOR_DOC,
|
| 486 |
+
expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
|
| 487 |
+
)
|
| 488 |
+
def forward(
|
| 489 |
+
self,
|
| 490 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 491 |
+
labels: Optional[torch.LongTensor] = None,
|
| 492 |
+
output_hidden_states: Optional[bool] = None,
|
| 493 |
+
return_dict: Optional[bool] = None,
|
| 494 |
+
) -> Union[Tuple, ImageClassifierOutputWithNoAttention]:
|
| 495 |
+
r"""
|
| 496 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 497 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 498 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 499 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 500 |
+
"""
|
| 501 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 502 |
+
|
| 503 |
+
outputs = self.van(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
|
| 504 |
+
|
| 505 |
+
pooled_output = outputs.pooler_output if return_dict else outputs[1]
|
| 506 |
+
|
| 507 |
+
logits = self.classifier(pooled_output)
|
| 508 |
+
|
| 509 |
+
loss = None
|
| 510 |
+
if labels is not None:
|
| 511 |
+
if self.config.problem_type is None:
|
| 512 |
+
if self.config.num_labels == 1:
|
| 513 |
+
self.config.problem_type = "regression"
|
| 514 |
+
elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 515 |
+
self.config.problem_type = "single_label_classification"
|
| 516 |
+
else:
|
| 517 |
+
self.config.problem_type = "multi_label_classification"
|
| 518 |
+
|
| 519 |
+
if self.config.problem_type == "regression":
|
| 520 |
+
loss_fct = MSELoss()
|
| 521 |
+
if self.config.num_labels == 1:
|
| 522 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 523 |
+
else:
|
| 524 |
+
loss = loss_fct(logits, labels)
|
| 525 |
+
elif self.config.problem_type == "single_label_classification":
|
| 526 |
+
loss_fct = CrossEntropyLoss()
|
| 527 |
+
loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
|
| 528 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 529 |
+
loss_fct = BCEWithLogitsLoss()
|
| 530 |
+
loss = loss_fct(logits, labels)
|
| 531 |
+
|
| 532 |
+
if not return_dict:
|
| 533 |
+
output = (logits,) + outputs[2:]
|
| 534 |
+
return ((loss,) + output) if loss is not None else output
|
| 535 |
+
|
| 536 |
+
return ImageClassifierOutputWithNoAttention(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/vit_hybrid/__init__.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_import_structure = {"configuration_vit_hybrid": ["ViTHybridConfig"]}
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
if not is_torch_available():
|
| 23 |
+
raise OptionalDependencyNotAvailable()
|
| 24 |
+
except OptionalDependencyNotAvailable:
|
| 25 |
+
pass
|
| 26 |
+
else:
|
| 27 |
+
_import_structure["modeling_vit_hybrid"] = [
|
| 28 |
+
"ViTHybridForImageClassification",
|
| 29 |
+
"ViTHybridModel",
|
| 30 |
+
"ViTHybridPreTrainedModel",
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
if not is_vision_available():
|
| 35 |
+
raise OptionalDependencyNotAvailable()
|
| 36 |
+
except OptionalDependencyNotAvailable:
|
| 37 |
+
pass
|
| 38 |
+
else:
|
| 39 |
+
_import_structure["image_processing_vit_hybrid"] = ["ViTHybridImageProcessor"]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
if TYPE_CHECKING:
|
| 43 |
+
from .configuration_vit_hybrid import ViTHybridConfig
|
| 44 |
+
|
| 45 |
+
try:
|
| 46 |
+
if not is_torch_available():
|
| 47 |
+
raise OptionalDependencyNotAvailable()
|
| 48 |
+
except OptionalDependencyNotAvailable:
|
| 49 |
+
pass
|
| 50 |
+
else:
|
| 51 |
+
from .modeling_vit_hybrid import (
|
| 52 |
+
ViTHybridForImageClassification,
|
| 53 |
+
ViTHybridModel,
|
| 54 |
+
ViTHybridPreTrainedModel,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
try:
|
| 58 |
+
if not is_vision_available():
|
| 59 |
+
raise OptionalDependencyNotAvailable()
|
| 60 |
+
except OptionalDependencyNotAvailable:
|
| 61 |
+
pass
|
| 62 |
+
else:
|
| 63 |
+
from .image_processing_vit_hybrid import ViTHybridImageProcessor
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
else:
|
| 67 |
+
import sys
|
| 68 |
+
|
| 69 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/vit_hybrid/configuration_vit_hybrid.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""ViT Hybrid model configuration"""
|
| 16 |
+
|
| 17 |
+
from ....configuration_utils import PretrainedConfig
|
| 18 |
+
from ....utils import logging
|
| 19 |
+
from ...auto.configuration_auto import CONFIG_MAPPING
|
| 20 |
+
from ...bit import BitConfig
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ViTHybridConfig(PretrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
This is the configuration class to store the configuration of a [`ViTHybridModel`]. It is used to instantiate a ViT
|
| 29 |
+
Hybrid model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 30 |
+
with the defaults will yield a similar configuration to that of the ViT Hybrid
|
| 31 |
+
[google/vit-hybrid-base-bit-384](https://huggingface.co/google/vit-hybrid-base-bit-384) architecture.
|
| 32 |
+
|
| 33 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 34 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
backbone_config (`Union[Dict[str, Any], PretrainedConfig]`, *optional*):
|
| 38 |
+
The configuration of the backbone in a dictionary or the config object of the backbone.
|
| 39 |
+
backbone (`str`, *optional*):
|
| 40 |
+
Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
|
| 41 |
+
will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
|
| 42 |
+
is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
|
| 43 |
+
use_pretrained_backbone (`bool`, *optional*, defaults to `False`):
|
| 44 |
+
Whether to use pretrained weights for the backbone.
|
| 45 |
+
use_timm_backbone (`bool`, *optional*, defaults to `False`):
|
| 46 |
+
Whether to load `backbone` from the timm library. If `False`, the backbone is loaded from the transformers
|
| 47 |
+
library.
|
| 48 |
+
backbone_kwargs (`dict`, *optional*):
|
| 49 |
+
Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
|
| 50 |
+
e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
|
| 51 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 52 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 53 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 54 |
+
Number of hidden layers in the Transformer encoder.
|
| 55 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 56 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 57 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 58 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 59 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 60 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 61 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 62 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 63 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 64 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 65 |
+
The dropout ratio for the attention probabilities.
|
| 66 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 67 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 68 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 69 |
+
The epsilon used by the layer normalization layers.
|
| 70 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 71 |
+
The size (resolution) of each image.
|
| 72 |
+
patch_size (`int`, *optional*, defaults to 1):
|
| 73 |
+
The size (resolution) of each patch.
|
| 74 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 75 |
+
The number of input channels.
|
| 76 |
+
backbone_featmap_shape (`List[int]`, *optional*, defaults to `[1, 1024, 24, 24]`):
|
| 77 |
+
Used only for the `hybrid` embedding type. The shape of the feature maps of the backbone.
|
| 78 |
+
qkv_bias (`bool`, *optional*, defaults to `True`):
|
| 79 |
+
Whether to add a bias to the queries, keys and values.
|
| 80 |
+
|
| 81 |
+
Example:
|
| 82 |
+
|
| 83 |
+
```python
|
| 84 |
+
>>> from transformers import ViTHybridConfig, ViTHybridModel
|
| 85 |
+
|
| 86 |
+
>>> # Initializing a ViT Hybrid vit-hybrid-base-bit-384 style configuration
|
| 87 |
+
>>> configuration = ViTHybridConfig()
|
| 88 |
+
|
| 89 |
+
>>> # Initializing a model (with random weights) from the vit-hybrid-base-bit-384 style configuration
|
| 90 |
+
>>> model = ViTHybridModel(configuration)
|
| 91 |
+
|
| 92 |
+
>>> # Accessing the model configuration
|
| 93 |
+
>>> configuration = model.config
|
| 94 |
+
```"""
|
| 95 |
+
|
| 96 |
+
model_type = "vit-hybrid"
|
| 97 |
+
|
| 98 |
+
def __init__(
|
| 99 |
+
self,
|
| 100 |
+
backbone_config=None,
|
| 101 |
+
backbone=None,
|
| 102 |
+
use_pretrained_backbone=False,
|
| 103 |
+
use_timm_backbone=False,
|
| 104 |
+
backbone_kwargs=None,
|
| 105 |
+
hidden_size=768,
|
| 106 |
+
num_hidden_layers=12,
|
| 107 |
+
num_attention_heads=12,
|
| 108 |
+
intermediate_size=3072,
|
| 109 |
+
hidden_act="gelu",
|
| 110 |
+
hidden_dropout_prob=0.0,
|
| 111 |
+
attention_probs_dropout_prob=0.0,
|
| 112 |
+
initializer_range=0.02,
|
| 113 |
+
layer_norm_eps=1e-12,
|
| 114 |
+
image_size=224,
|
| 115 |
+
patch_size=1,
|
| 116 |
+
num_channels=3,
|
| 117 |
+
backbone_featmap_shape=[1, 1024, 24, 24],
|
| 118 |
+
qkv_bias=True,
|
| 119 |
+
**kwargs,
|
| 120 |
+
):
|
| 121 |
+
super().__init__(**kwargs)
|
| 122 |
+
if use_pretrained_backbone:
|
| 123 |
+
raise ValueError("Pretrained backbones are not supported yet.")
|
| 124 |
+
|
| 125 |
+
if backbone_config is not None and backbone is not None:
|
| 126 |
+
raise ValueError("You can't specify both `backbone` and `backbone_config`.")
|
| 127 |
+
|
| 128 |
+
if backbone_config is None and backbone is None:
|
| 129 |
+
logger.info("`backbone_config` is `None`. Initializing the config with a `BiT` backbone.")
|
| 130 |
+
backbone_config = {
|
| 131 |
+
"global_padding": "same",
|
| 132 |
+
"layer_type": "bottleneck",
|
| 133 |
+
"depths": [3, 4, 9],
|
| 134 |
+
"out_features": ["stage3"],
|
| 135 |
+
"embedding_dynamic_padding": True,
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
if backbone_kwargs is not None and backbone_kwargs and backbone_config is not None:
|
| 139 |
+
raise ValueError("You can't specify both `backbone_kwargs` and `backbone_config`.")
|
| 140 |
+
|
| 141 |
+
if isinstance(backbone_config, dict):
|
| 142 |
+
if "model_type" in backbone_config:
|
| 143 |
+
backbone_config_class = CONFIG_MAPPING[backbone_config["model_type"]]
|
| 144 |
+
else:
|
| 145 |
+
logger.info(
|
| 146 |
+
"`model_type` is not found in `backbone_config`. Use `Bit` as the backbone configuration class."
|
| 147 |
+
)
|
| 148 |
+
backbone_config_class = BitConfig
|
| 149 |
+
backbone_config = backbone_config_class(**backbone_config)
|
| 150 |
+
|
| 151 |
+
self.backbone_featmap_shape = backbone_featmap_shape
|
| 152 |
+
self.backbone_config = backbone_config
|
| 153 |
+
self.backbone = backbone
|
| 154 |
+
self.use_pretrained_backbone = use_pretrained_backbone
|
| 155 |
+
self.use_timm_backbone = use_timm_backbone
|
| 156 |
+
self.backbone_kwargs = backbone_kwargs
|
| 157 |
+
self.hidden_size = hidden_size
|
| 158 |
+
self.num_hidden_layers = num_hidden_layers
|
| 159 |
+
self.num_attention_heads = num_attention_heads
|
| 160 |
+
self.intermediate_size = intermediate_size
|
| 161 |
+
self.hidden_act = hidden_act
|
| 162 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 163 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 164 |
+
self.initializer_range = initializer_range
|
| 165 |
+
self.layer_norm_eps = layer_norm_eps
|
| 166 |
+
self.image_size = image_size
|
| 167 |
+
self.patch_size = patch_size
|
| 168 |
+
self.num_channels = num_channels
|
| 169 |
+
self.qkv_bias = qkv_bias
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/vit_hybrid/convert_vit_hybrid_timm_to_pytorch.py
ADDED
|
@@ -0,0 +1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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 ViT hybrid checkpoints from the timm library."""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import json
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
import requests
|
| 22 |
+
import timm
|
| 23 |
+
import torch
|
| 24 |
+
from huggingface_hub import hf_hub_download
|
| 25 |
+
from PIL import Image
|
| 26 |
+
from timm.data import resolve_data_config
|
| 27 |
+
from timm.data.transforms_factory import create_transform
|
| 28 |
+
|
| 29 |
+
from transformers import (
|
| 30 |
+
BitConfig,
|
| 31 |
+
ViTHybridConfig,
|
| 32 |
+
ViTHybridForImageClassification,
|
| 33 |
+
ViTHybridImageProcessor,
|
| 34 |
+
ViTHybridModel,
|
| 35 |
+
)
|
| 36 |
+
from transformers.image_utils import PILImageResampling
|
| 37 |
+
from transformers.utils import logging
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
logging.set_verbosity_info()
|
| 41 |
+
logger = logging.get_logger(__name__)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# here we list all keys to be renamed (original name on the left, our name on the right)
|
| 45 |
+
def create_rename_keys(config, base_model=False):
|
| 46 |
+
rename_keys = []
|
| 47 |
+
|
| 48 |
+
# fmt: off
|
| 49 |
+
# stem:
|
| 50 |
+
rename_keys.append(("cls_token", "vit.embeddings.cls_token"))
|
| 51 |
+
rename_keys.append(("pos_embed", "vit.embeddings.position_embeddings"))
|
| 52 |
+
|
| 53 |
+
rename_keys.append(("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight"))
|
| 54 |
+
rename_keys.append(("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias"))
|
| 55 |
+
|
| 56 |
+
# backbone
|
| 57 |
+
rename_keys.append(("patch_embed.backbone.stem.conv.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight"))
|
| 58 |
+
rename_keys.append(("patch_embed.backbone.stem.norm.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight"))
|
| 59 |
+
rename_keys.append(("patch_embed.backbone.stem.norm.bias", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias"))
|
| 60 |
+
|
| 61 |
+
for stage_idx in range(len(config.backbone_config.depths)):
|
| 62 |
+
for layer_idx in range(config.backbone_config.depths[stage_idx]):
|
| 63 |
+
rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight"))
|
| 64 |
+
rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight"))
|
| 65 |
+
rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias"))
|
| 66 |
+
rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight"))
|
| 67 |
+
rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight"))
|
| 68 |
+
rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias"))
|
| 69 |
+
rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight"))
|
| 70 |
+
rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight"))
|
| 71 |
+
rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias"))
|
| 72 |
+
|
| 73 |
+
rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight"))
|
| 74 |
+
rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight"))
|
| 75 |
+
rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias"))
|
| 76 |
+
|
| 77 |
+
# transformer encoder
|
| 78 |
+
for i in range(config.num_hidden_layers):
|
| 79 |
+
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
|
| 80 |
+
rename_keys.append((f"blocks.{i}.norm1.weight", f"vit.encoder.layer.{i}.layernorm_before.weight"))
|
| 81 |
+
rename_keys.append((f"blocks.{i}.norm1.bias", f"vit.encoder.layer.{i}.layernorm_before.bias"))
|
| 82 |
+
rename_keys.append((f"blocks.{i}.attn.proj.weight", f"vit.encoder.layer.{i}.attention.output.dense.weight"))
|
| 83 |
+
rename_keys.append((f"blocks.{i}.attn.proj.bias", f"vit.encoder.layer.{i}.attention.output.dense.bias"))
|
| 84 |
+
rename_keys.append((f"blocks.{i}.norm2.weight", f"vit.encoder.layer.{i}.layernorm_after.weight"))
|
| 85 |
+
rename_keys.append((f"blocks.{i}.norm2.bias", f"vit.encoder.layer.{i}.layernorm_after.bias"))
|
| 86 |
+
rename_keys.append((f"blocks.{i}.mlp.fc1.weight", f"vit.encoder.layer.{i}.intermediate.dense.weight"))
|
| 87 |
+
rename_keys.append((f"blocks.{i}.mlp.fc1.bias", f"vit.encoder.layer.{i}.intermediate.dense.bias"))
|
| 88 |
+
rename_keys.append((f"blocks.{i}.mlp.fc2.weight", f"vit.encoder.layer.{i}.output.dense.weight"))
|
| 89 |
+
rename_keys.append((f"blocks.{i}.mlp.fc2.bias", f"vit.encoder.layer.{i}.output.dense.bias"))
|
| 90 |
+
|
| 91 |
+
if base_model:
|
| 92 |
+
# layernorm + pooler
|
| 93 |
+
rename_keys.extend(
|
| 94 |
+
[
|
| 95 |
+
("norm.weight", "layernorm.weight"),
|
| 96 |
+
("norm.bias", "layernorm.bias"),
|
| 97 |
+
("pre_logits.fc.weight", "pooler.dense.weight"),
|
| 98 |
+
("pre_logits.fc.bias", "pooler.dense.bias"),
|
| 99 |
+
]
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
# if just the base model, we should remove "vit" from all keys that start with "vit"
|
| 103 |
+
rename_keys = [(pair[0], pair[1][4:]) if pair[1].startswith("vit") else pair for pair in rename_keys]
|
| 104 |
+
else:
|
| 105 |
+
# layernorm + classification head
|
| 106 |
+
rename_keys.extend(
|
| 107 |
+
[
|
| 108 |
+
("norm.weight", "vit.layernorm.weight"),
|
| 109 |
+
("norm.bias", "vit.layernorm.bias"),
|
| 110 |
+
("head.weight", "classifier.weight"),
|
| 111 |
+
("head.bias", "classifier.bias"),
|
| 112 |
+
]
|
| 113 |
+
)
|
| 114 |
+
# fmt: on
|
| 115 |
+
|
| 116 |
+
return rename_keys
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# we split up the matrix of each encoder layer into queries, keys and values
|
| 120 |
+
def read_in_q_k_v(state_dict, config, base_model=False):
|
| 121 |
+
for i in range(config.num_hidden_layers):
|
| 122 |
+
if base_model:
|
| 123 |
+
prefix = ""
|
| 124 |
+
else:
|
| 125 |
+
prefix = "vit."
|
| 126 |
+
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
|
| 127 |
+
in_proj_weight = state_dict.pop(f"blocks.{i}.attn.qkv.weight")
|
| 128 |
+
in_proj_bias = state_dict.pop(f"blocks.{i}.attn.qkv.bias")
|
| 129 |
+
# next, add query, keys and values (in that order) to the state dict
|
| 130 |
+
state_dict[f"{prefix}encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[
|
| 131 |
+
: config.hidden_size, :
|
| 132 |
+
]
|
| 133 |
+
state_dict[f"{prefix}encoder.layer.{i}.attention.attention.query.bias"] = in_proj_bias[: config.hidden_size]
|
| 134 |
+
state_dict[f"{prefix}encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[
|
| 135 |
+
config.hidden_size : config.hidden_size * 2, :
|
| 136 |
+
]
|
| 137 |
+
state_dict[f"{prefix}encoder.layer.{i}.attention.attention.key.bias"] = in_proj_bias[
|
| 138 |
+
config.hidden_size : config.hidden_size * 2
|
| 139 |
+
]
|
| 140 |
+
state_dict[f"{prefix}encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[
|
| 141 |
+
-config.hidden_size :, :
|
| 142 |
+
]
|
| 143 |
+
state_dict[f"{prefix}encoder.layer.{i}.attention.attention.value.bias"] = in_proj_bias[-config.hidden_size :]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def remove_classification_head_(state_dict):
|
| 147 |
+
ignore_keys = ["head.weight", "head.bias"]
|
| 148 |
+
for k in ignore_keys:
|
| 149 |
+
state_dict.pop(k, None)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def rename_key(dct, old, new):
|
| 153 |
+
val = dct.pop(old)
|
| 154 |
+
dct[new] = val
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
# We will verify our results on an image of cute cats
|
| 158 |
+
def prepare_img():
|
| 159 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 160 |
+
im = Image.open(requests.get(url, stream=True).raw)
|
| 161 |
+
return im
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@torch.no_grad()
|
| 165 |
+
def convert_vit_checkpoint(vit_name, pytorch_dump_folder_path, push_to_hub=False):
|
| 166 |
+
"""
|
| 167 |
+
Copy/paste/tweak model's weights to our ViT structure.
|
| 168 |
+
"""
|
| 169 |
+
|
| 170 |
+
# define default ViT hybrid configuration
|
| 171 |
+
backbone_config = BitConfig(
|
| 172 |
+
global_padding="same",
|
| 173 |
+
layer_type="bottleneck",
|
| 174 |
+
depths=(3, 4, 9),
|
| 175 |
+
out_features=["stage3"],
|
| 176 |
+
embedding_dynamic_padding=True,
|
| 177 |
+
)
|
| 178 |
+
config = ViTHybridConfig(backbone_config=backbone_config, image_size=384, num_labels=1000)
|
| 179 |
+
base_model = False
|
| 180 |
+
|
| 181 |
+
# load original model from timm
|
| 182 |
+
timm_model = timm.create_model(vit_name, pretrained=True)
|
| 183 |
+
timm_model.eval()
|
| 184 |
+
|
| 185 |
+
# load state_dict of original model, remove and rename some keys
|
| 186 |
+
state_dict = timm_model.state_dict()
|
| 187 |
+
if base_model:
|
| 188 |
+
remove_classification_head_(state_dict)
|
| 189 |
+
rename_keys = create_rename_keys(config, base_model)
|
| 190 |
+
for src, dest in rename_keys:
|
| 191 |
+
rename_key(state_dict, src, dest)
|
| 192 |
+
read_in_q_k_v(state_dict, config, base_model)
|
| 193 |
+
|
| 194 |
+
repo_id = "huggingface/label-files"
|
| 195 |
+
filename = "imagenet-1k-id2label.json"
|
| 196 |
+
id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
|
| 197 |
+
id2label = {int(k): v for k, v in id2label.items()}
|
| 198 |
+
config.id2label = id2label
|
| 199 |
+
config.label2id = {v: k for k, v in id2label.items()}
|
| 200 |
+
|
| 201 |
+
# load HuggingFace model
|
| 202 |
+
if vit_name[-5:] == "in21k":
|
| 203 |
+
model = ViTHybridModel(config).eval()
|
| 204 |
+
else:
|
| 205 |
+
model = ViTHybridForImageClassification(config).eval()
|
| 206 |
+
model.load_state_dict(state_dict)
|
| 207 |
+
|
| 208 |
+
# create image processor
|
| 209 |
+
transform = create_transform(**resolve_data_config({}, model=timm_model))
|
| 210 |
+
timm_transforms = transform.transforms
|
| 211 |
+
|
| 212 |
+
pillow_resamplings = {
|
| 213 |
+
"bilinear": PILImageResampling.BILINEAR,
|
| 214 |
+
"bicubic": PILImageResampling.BICUBIC,
|
| 215 |
+
"nearest": PILImageResampling.NEAREST,
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
processor = ViTHybridImageProcessor(
|
| 219 |
+
do_resize=True,
|
| 220 |
+
size={"shortest_edge": timm_transforms[0].size},
|
| 221 |
+
resample=pillow_resamplings[timm_transforms[0].interpolation.value],
|
| 222 |
+
do_center_crop=True,
|
| 223 |
+
crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]},
|
| 224 |
+
do_normalize=True,
|
| 225 |
+
image_mean=timm_transforms[-1].mean.tolist(),
|
| 226 |
+
image_std=timm_transforms[-1].std.tolist(),
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
image = prepare_img()
|
| 230 |
+
timm_pixel_values = transform(image).unsqueeze(0)
|
| 231 |
+
pixel_values = processor(image, return_tensors="pt").pixel_values
|
| 232 |
+
|
| 233 |
+
# verify pixel values
|
| 234 |
+
assert torch.allclose(timm_pixel_values, pixel_values)
|
| 235 |
+
|
| 236 |
+
# verify logits
|
| 237 |
+
with torch.no_grad():
|
| 238 |
+
outputs = model(pixel_values)
|
| 239 |
+
logits = outputs.logits
|
| 240 |
+
|
| 241 |
+
print("Predicted class:", logits.argmax(-1).item())
|
| 242 |
+
if base_model:
|
| 243 |
+
timm_pooled_output = timm_model.forward_features(pixel_values)
|
| 244 |
+
assert timm_pooled_output.shape == outputs.pooler_output.shape
|
| 245 |
+
assert torch.allclose(timm_pooled_output, outputs.pooler_output, atol=1e-3)
|
| 246 |
+
else:
|
| 247 |
+
timm_logits = timm_model(pixel_values)
|
| 248 |
+
assert timm_logits.shape == outputs.logits.shape
|
| 249 |
+
assert torch.allclose(timm_logits, outputs.logits, atol=1e-3)
|
| 250 |
+
print("Looks ok!")
|
| 251 |
+
|
| 252 |
+
if pytorch_dump_folder_path is not None:
|
| 253 |
+
Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
|
| 254 |
+
print(f"Saving model {vit_name} to {pytorch_dump_folder_path}")
|
| 255 |
+
model.save_pretrained(pytorch_dump_folder_path)
|
| 256 |
+
print(f"Saving processor to {pytorch_dump_folder_path}")
|
| 257 |
+
processor.save_pretrained(pytorch_dump_folder_path)
|
| 258 |
+
|
| 259 |
+
if push_to_hub:
|
| 260 |
+
print(f"Pushing model and processor to the hub {vit_name}")
|
| 261 |
+
model.push_to_hub(f"ybelkada/{vit_name}")
|
| 262 |
+
processor.push_to_hub(f"ybelkada/{vit_name}")
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
if __name__ == "__main__":
|
| 266 |
+
parser = argparse.ArgumentParser()
|
| 267 |
+
# Required parameters
|
| 268 |
+
parser.add_argument(
|
| 269 |
+
"--vit_name",
|
| 270 |
+
default="vit_base_r50_s16_384",
|
| 271 |
+
type=str,
|
| 272 |
+
help="Name of the hybrid ViT timm model you'd like to convert.",
|
| 273 |
+
)
|
| 274 |
+
parser.add_argument(
|
| 275 |
+
"--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
|
| 276 |
+
)
|
| 277 |
+
parser.add_argument(
|
| 278 |
+
"--push_to_hub", action="store_true", help="Whether to upload the model to the HuggingFace hub."
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
args = parser.parse_args()
|
| 282 |
+
convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/vit_hybrid/image_processing_vit_hybrid.py
ADDED
|
@@ -0,0 +1,338 @@
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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 ViT hybrid."""
|
| 16 |
+
|
| 17 |
+
from typing import Dict, List, Optional, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from ....image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
| 22 |
+
from ....image_transforms import (
|
| 23 |
+
convert_to_rgb,
|
| 24 |
+
get_resize_output_image_size,
|
| 25 |
+
resize,
|
| 26 |
+
to_channel_dimension_format,
|
| 27 |
+
)
|
| 28 |
+
from ....image_utils import (
|
| 29 |
+
OPENAI_CLIP_MEAN,
|
| 30 |
+
OPENAI_CLIP_STD,
|
| 31 |
+
ChannelDimension,
|
| 32 |
+
ImageInput,
|
| 33 |
+
PILImageResampling,
|
| 34 |
+
infer_channel_dimension_format,
|
| 35 |
+
is_scaled_image,
|
| 36 |
+
make_list_of_images,
|
| 37 |
+
to_numpy_array,
|
| 38 |
+
valid_images,
|
| 39 |
+
validate_kwargs,
|
| 40 |
+
validate_preprocess_arguments,
|
| 41 |
+
)
|
| 42 |
+
from ....utils import TensorType, is_vision_available, logging
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
logger = logging.get_logger(__name__)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if is_vision_available():
|
| 49 |
+
import PIL
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class ViTHybridImageProcessor(BaseImageProcessor):
|
| 53 |
+
r"""
|
| 54 |
+
Constructs a ViT Hybrid image processor.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 58 |
+
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
|
| 59 |
+
`do_resize` in the `preprocess` method.
|
| 60 |
+
size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
|
| 61 |
+
Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with
|
| 62 |
+
the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess`
|
| 63 |
+
method.
|
| 64 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
| 65 |
+
Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
|
| 66 |
+
do_center_crop (`bool`, *optional*, defaults to `True`):
|
| 67 |
+
Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
|
| 68 |
+
`preprocess` method.
|
| 69 |
+
crop_size (`Dict[str, int]` *optional*, defaults to 224):
|
| 70 |
+
Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
|
| 71 |
+
method.
|
| 72 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 73 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
|
| 74 |
+
the `preprocess` method.
|
| 75 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
| 76 |
+
Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
|
| 77 |
+
method.
|
| 78 |
+
do_normalize:
|
| 79 |
+
Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
|
| 80 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
|
| 81 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
| 82 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
| 83 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
|
| 84 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
| 85 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 86 |
+
Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 87 |
+
do_convert_rgb (`bool`, *optional*, defaults to `True`):
|
| 88 |
+
Whether to convert the image to RGB.
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
model_input_names = ["pixel_values"]
|
| 92 |
+
|
| 93 |
+
def __init__(
|
| 94 |
+
self,
|
| 95 |
+
do_resize: bool = True,
|
| 96 |
+
size: Dict[str, int] = None,
|
| 97 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 98 |
+
do_center_crop: bool = True,
|
| 99 |
+
crop_size: Dict[str, int] = None,
|
| 100 |
+
do_rescale: bool = True,
|
| 101 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 102 |
+
do_normalize: bool = True,
|
| 103 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 104 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 105 |
+
do_convert_rgb: bool = True,
|
| 106 |
+
**kwargs,
|
| 107 |
+
) -> None:
|
| 108 |
+
super().__init__(**kwargs)
|
| 109 |
+
size = size if size is not None else {"shortest_edge": 224}
|
| 110 |
+
size = get_size_dict(size, default_to_square=False)
|
| 111 |
+
crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
|
| 112 |
+
crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
|
| 113 |
+
|
| 114 |
+
self.do_resize = do_resize
|
| 115 |
+
self.size = size
|
| 116 |
+
self.resample = resample
|
| 117 |
+
self.do_center_crop = do_center_crop
|
| 118 |
+
self.crop_size = crop_size
|
| 119 |
+
self.do_rescale = do_rescale
|
| 120 |
+
self.rescale_factor = rescale_factor
|
| 121 |
+
self.do_normalize = do_normalize
|
| 122 |
+
self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
|
| 123 |
+
self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
|
| 124 |
+
self.do_convert_rgb = do_convert_rgb
|
| 125 |
+
self._valid_processor_keys = [
|
| 126 |
+
"images",
|
| 127 |
+
"do_resize",
|
| 128 |
+
"size",
|
| 129 |
+
"resample",
|
| 130 |
+
"do_center_crop",
|
| 131 |
+
"crop_size",
|
| 132 |
+
"do_rescale",
|
| 133 |
+
"rescale_factor",
|
| 134 |
+
"do_normalize",
|
| 135 |
+
"image_mean",
|
| 136 |
+
"image_std",
|
| 137 |
+
"do_convert_rgb",
|
| 138 |
+
"return_tensors",
|
| 139 |
+
"data_format",
|
| 140 |
+
"input_data_format",
|
| 141 |
+
]
|
| 142 |
+
|
| 143 |
+
def resize(
|
| 144 |
+
self,
|
| 145 |
+
image: np.ndarray,
|
| 146 |
+
size: Dict[str, int],
|
| 147 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 148 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 149 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 150 |
+
**kwargs,
|
| 151 |
+
) -> np.ndarray:
|
| 152 |
+
"""
|
| 153 |
+
Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
|
| 154 |
+
resized to keep the input aspect ratio.
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
image (`np.ndarray`):
|
| 158 |
+
Image to resize.
|
| 159 |
+
size (`Dict[str, int]`):
|
| 160 |
+
Size of the output image.
|
| 161 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
| 162 |
+
Resampling filter to use when resiizing the image.
|
| 163 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 164 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
| 165 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 166 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 167 |
+
"""
|
| 168 |
+
default_to_square = True
|
| 169 |
+
if "shortest_edge" in size:
|
| 170 |
+
size = size["shortest_edge"]
|
| 171 |
+
default_to_square = False
|
| 172 |
+
elif "height" in size and "width" in size:
|
| 173 |
+
size = (size["height"], size["width"])
|
| 174 |
+
else:
|
| 175 |
+
raise ValueError("Size must contain either 'shortest_edge' or 'height' and 'width'.")
|
| 176 |
+
|
| 177 |
+
output_size = get_resize_output_image_size(
|
| 178 |
+
image,
|
| 179 |
+
size=size,
|
| 180 |
+
default_to_square=default_to_square,
|
| 181 |
+
input_data_format=input_data_format,
|
| 182 |
+
)
|
| 183 |
+
return resize(
|
| 184 |
+
image,
|
| 185 |
+
size=output_size,
|
| 186 |
+
resample=resample,
|
| 187 |
+
data_format=data_format,
|
| 188 |
+
input_data_format=input_data_format,
|
| 189 |
+
**kwargs,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
def preprocess(
|
| 193 |
+
self,
|
| 194 |
+
images: ImageInput,
|
| 195 |
+
do_resize: bool = None,
|
| 196 |
+
size: Dict[str, int] = None,
|
| 197 |
+
resample: PILImageResampling = None,
|
| 198 |
+
do_center_crop: bool = None,
|
| 199 |
+
crop_size: int = None,
|
| 200 |
+
do_rescale: bool = None,
|
| 201 |
+
rescale_factor: float = None,
|
| 202 |
+
do_normalize: bool = None,
|
| 203 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 204 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 205 |
+
do_convert_rgb: bool = None,
|
| 206 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 207 |
+
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
|
| 208 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 209 |
+
**kwargs,
|
| 210 |
+
) -> PIL.Image.Image:
|
| 211 |
+
"""
|
| 212 |
+
Preprocess an image or batch of images.
|
| 213 |
+
|
| 214 |
+
Args:
|
| 215 |
+
images (`ImageInput`):
|
| 216 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 217 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 218 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 219 |
+
Whether to resize the image.
|
| 220 |
+
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
|
| 221 |
+
Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
|
| 222 |
+
the longest edge resized to keep the input aspect ratio.
|
| 223 |
+
resample (`int`, *optional*, defaults to `self.resample`):
|
| 224 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
|
| 225 |
+
has an effect if `do_resize` is set to `True`.
|
| 226 |
+
do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
|
| 227 |
+
Whether to center crop the image.
|
| 228 |
+
crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
|
| 229 |
+
Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
|
| 230 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 231 |
+
Whether to rescale the image.
|
| 232 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 233 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 234 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 235 |
+
Whether to normalize the image.
|
| 236 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
| 237 |
+
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
| 238 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
| 239 |
+
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
|
| 240 |
+
`True`.
|
| 241 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
| 242 |
+
Whether to convert the image to RGB.
|
| 243 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 244 |
+
The type of tensors to return. Can be one of:
|
| 245 |
+
- Unset: Return a list of `np.ndarray`.
|
| 246 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 247 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 248 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 249 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 250 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 251 |
+
The channel dimension format for the output image. Can be one of:
|
| 252 |
+
- `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 253 |
+
- `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 254 |
+
- Unset: defaults to the channel dimension format of the input image.
|
| 255 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 256 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 257 |
+
from the input image. Can be one of:
|
| 258 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 259 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 260 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 261 |
+
"""
|
| 262 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 263 |
+
size = size if size is not None else self.size
|
| 264 |
+
size = get_size_dict(size, param_name="size", default_to_square=False)
|
| 265 |
+
resample = resample if resample is not None else self.resample
|
| 266 |
+
do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
|
| 267 |
+
crop_size = crop_size if crop_size is not None else self.crop_size
|
| 268 |
+
crop_size = get_size_dict(crop_size, param_name="crop_size", default_to_square=True)
|
| 269 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 270 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 271 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 272 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 273 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 274 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
| 275 |
+
|
| 276 |
+
images = make_list_of_images(images)
|
| 277 |
+
|
| 278 |
+
validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)
|
| 279 |
+
|
| 280 |
+
if not valid_images(images):
|
| 281 |
+
raise ValueError(
|
| 282 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 283 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 284 |
+
)
|
| 285 |
+
validate_preprocess_arguments(
|
| 286 |
+
do_rescale=do_rescale,
|
| 287 |
+
rescale_factor=rescale_factor,
|
| 288 |
+
do_normalize=do_normalize,
|
| 289 |
+
image_mean=image_mean,
|
| 290 |
+
image_std=image_std,
|
| 291 |
+
do_center_crop=do_center_crop,
|
| 292 |
+
crop_size=crop_size,
|
| 293 |
+
do_resize=do_resize,
|
| 294 |
+
size=size,
|
| 295 |
+
resample=resample,
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
# PIL RGBA images are converted to RGB
|
| 299 |
+
if do_convert_rgb:
|
| 300 |
+
images = [convert_to_rgb(image) for image in images]
|
| 301 |
+
|
| 302 |
+
# All transformations expect numpy arrays.
|
| 303 |
+
images = [to_numpy_array(image) for image in images]
|
| 304 |
+
|
| 305 |
+
if do_rescale and is_scaled_image(images[0]):
|
| 306 |
+
logger.warning_once(
|
| 307 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 308 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
if input_data_format is None:
|
| 312 |
+
# We assume that all images have the same channel dimension format.
|
| 313 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 314 |
+
|
| 315 |
+
all_images = []
|
| 316 |
+
for image in images:
|
| 317 |
+
if do_resize:
|
| 318 |
+
image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
|
| 319 |
+
|
| 320 |
+
if do_center_crop:
|
| 321 |
+
image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)
|
| 322 |
+
|
| 323 |
+
if do_rescale:
|
| 324 |
+
image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
| 325 |
+
|
| 326 |
+
if do_normalize:
|
| 327 |
+
image = self.normalize(
|
| 328 |
+
image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
all_images.append(image)
|
| 332 |
+
images = [
|
| 333 |
+
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
| 334 |
+
for image in all_images
|
| 335 |
+
]
|
| 336 |
+
|
| 337 |
+
data = {"pixel_values": images}
|
| 338 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/vit_hybrid/modeling_vit_hybrid.py
ADDED
|
@@ -0,0 +1,767 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 Google AI, Ross Wightman, The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch ViT Hybrid model."""
|
| 16 |
+
|
| 17 |
+
import collections.abc
|
| 18 |
+
import math
|
| 19 |
+
from typing import Dict, List, Optional, Set, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.utils.checkpoint
|
| 23 |
+
from torch import nn
|
| 24 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 25 |
+
|
| 26 |
+
from ....activations import ACT2FN
|
| 27 |
+
from ....modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
|
| 28 |
+
from ....modeling_utils import PreTrainedModel
|
| 29 |
+
from ....pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
|
| 30 |
+
from ....utils import (
|
| 31 |
+
add_code_sample_docstrings,
|
| 32 |
+
add_start_docstrings,
|
| 33 |
+
add_start_docstrings_to_model_forward,
|
| 34 |
+
logging,
|
| 35 |
+
torch_int,
|
| 36 |
+
)
|
| 37 |
+
from ....utils.backbone_utils import load_backbone
|
| 38 |
+
from .configuration_vit_hybrid import ViTHybridConfig
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
logger = logging.get_logger(__name__)
|
| 42 |
+
|
| 43 |
+
# General docstring
|
| 44 |
+
_CONFIG_FOR_DOC = "ViTHybridConfig"
|
| 45 |
+
|
| 46 |
+
# Base docstring
|
| 47 |
+
_CHECKPOINT_FOR_DOC = "google/vit-hybrid-base-bit-384"
|
| 48 |
+
_EXPECTED_OUTPUT_SHAPE = [1, 197, 768]
|
| 49 |
+
|
| 50 |
+
# Image classification docstring
|
| 51 |
+
_IMAGE_CLASS_CHECKPOINT = "google/vit-hybrid-base-bit-384"
|
| 52 |
+
_IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class ViTHybridEmbeddings(nn.Module):
|
| 56 |
+
"""
|
| 57 |
+
Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
def __init__(self, config: ViTHybridConfig, use_mask_token: bool = False) -> None:
|
| 61 |
+
super().__init__()
|
| 62 |
+
|
| 63 |
+
self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
| 64 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) if use_mask_token else None
|
| 65 |
+
self.patch_embeddings = ViTHybridPatchEmbeddings(config)
|
| 66 |
+
num_patches = self.patch_embeddings.num_patches
|
| 67 |
+
self.position_embeddings = nn.Parameter(torch.randn(1, num_patches + 1, config.hidden_size))
|
| 68 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 69 |
+
self.patch_size = config.patch_size
|
| 70 |
+
self.config = config
|
| 71 |
+
|
| 72 |
+
# Copied from transformers.models.vit.modeling_vit.ViTEmbeddings.interpolate_pos_encoding
|
| 73 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 74 |
+
"""
|
| 75 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
|
| 76 |
+
images. This method is also adapted to support torch.jit tracing.
|
| 77 |
+
|
| 78 |
+
Adapted from:
|
| 79 |
+
- https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
|
| 80 |
+
- https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
num_patches = embeddings.shape[1] - 1
|
| 84 |
+
num_positions = self.position_embeddings.shape[1] - 1
|
| 85 |
+
|
| 86 |
+
# always interpolate when tracing to ensure the exported model works for dynamic input shapes
|
| 87 |
+
if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
|
| 88 |
+
return self.position_embeddings
|
| 89 |
+
|
| 90 |
+
class_pos_embed = self.position_embeddings[:, :1]
|
| 91 |
+
patch_pos_embed = self.position_embeddings[:, 1:]
|
| 92 |
+
|
| 93 |
+
dim = embeddings.shape[-1]
|
| 94 |
+
|
| 95 |
+
new_height = height // self.patch_size
|
| 96 |
+
new_width = width // self.patch_size
|
| 97 |
+
|
| 98 |
+
sqrt_num_positions = torch_int(num_positions**0.5)
|
| 99 |
+
patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
|
| 100 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 101 |
+
|
| 102 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 103 |
+
patch_pos_embed,
|
| 104 |
+
size=(new_height, new_width),
|
| 105 |
+
mode="bicubic",
|
| 106 |
+
align_corners=False,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 110 |
+
|
| 111 |
+
return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
|
| 112 |
+
|
| 113 |
+
def forward(
|
| 114 |
+
self,
|
| 115 |
+
pixel_values: torch.Tensor,
|
| 116 |
+
bool_masked_pos: Optional[torch.BoolTensor] = None,
|
| 117 |
+
interpolate_pos_encoding: bool = False,
|
| 118 |
+
) -> torch.Tensor:
|
| 119 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 120 |
+
embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
|
| 121 |
+
|
| 122 |
+
if bool_masked_pos is not None:
|
| 123 |
+
seq_length = embeddings.shape[1]
|
| 124 |
+
mask_tokens = self.mask_token.expand(batch_size, seq_length, -1)
|
| 125 |
+
# replace the masked visual tokens by mask_tokens
|
| 126 |
+
mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
|
| 127 |
+
embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
|
| 128 |
+
|
| 129 |
+
# add the [CLS] token to the embedded patch tokens
|
| 130 |
+
cls_tokens = self.cls_token.expand(batch_size, -1, -1)
|
| 131 |
+
embeddings = torch.cat((cls_tokens, embeddings), dim=1)
|
| 132 |
+
|
| 133 |
+
# add positional encoding to each token
|
| 134 |
+
if interpolate_pos_encoding:
|
| 135 |
+
embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
|
| 136 |
+
else:
|
| 137 |
+
embeddings = embeddings + self.position_embeddings
|
| 138 |
+
|
| 139 |
+
embeddings = self.dropout(embeddings)
|
| 140 |
+
|
| 141 |
+
return embeddings
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class ViTHybridPatchEmbeddings(nn.Module):
|
| 145 |
+
"""
|
| 146 |
+
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
| 147 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
| 148 |
+
Transformer.
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
def __init__(self, config, feature_size=None):
|
| 152 |
+
super().__init__()
|
| 153 |
+
image_size, patch_size = config.image_size, config.patch_size
|
| 154 |
+
num_channels, hidden_size = config.num_channels, config.hidden_size
|
| 155 |
+
|
| 156 |
+
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
|
| 157 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 158 |
+
|
| 159 |
+
self.backbone = load_backbone(config)
|
| 160 |
+
if self.backbone.config.model_type != "bit":
|
| 161 |
+
raise ValueError(f"Backbone model type {self.backbone.model_type} is not supported.")
|
| 162 |
+
feature_dim = self.backbone.channels[-1]
|
| 163 |
+
|
| 164 |
+
if feature_size is None:
|
| 165 |
+
feature_map = config.backbone_featmap_shape
|
| 166 |
+
|
| 167 |
+
feature_size = feature_map[-2:]
|
| 168 |
+
feature_dim = feature_map[1]
|
| 169 |
+
else:
|
| 170 |
+
feature_size = (
|
| 171 |
+
feature_size if isinstance(feature_size, collections.abc.Iterable) else (feature_size, feature_size)
|
| 172 |
+
)
|
| 173 |
+
feature_dim = self.backbone.channels[-1]
|
| 174 |
+
|
| 175 |
+
self.grid_size = (feature_size[0] // patch_size[0], feature_size[1] // patch_size[1])
|
| 176 |
+
self.num_patches = self.grid_size[0] * self.grid_size[1]
|
| 177 |
+
self.image_size = image_size
|
| 178 |
+
self.patch_size = patch_size
|
| 179 |
+
self.num_channels = num_channels
|
| 180 |
+
|
| 181 |
+
self.projection = nn.Conv2d(feature_dim, hidden_size, kernel_size=patch_size, stride=patch_size)
|
| 182 |
+
|
| 183 |
+
def forward(self, pixel_values: torch.Tensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
|
| 184 |
+
_, num_channels, height, width = pixel_values.shape
|
| 185 |
+
if num_channels != self.num_channels:
|
| 186 |
+
raise ValueError(
|
| 187 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 188 |
+
)
|
| 189 |
+
if not interpolate_pos_encoding:
|
| 190 |
+
if height != self.image_size[0] or width != self.image_size[1]:
|
| 191 |
+
raise ValueError(
|
| 192 |
+
f"Input image size ({height}*{width}) doesn't match model"
|
| 193 |
+
f" ({self.image_size[0]}*{self.image_size[1]})."
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
features = self.backbone(pixel_values).feature_maps[-1]
|
| 197 |
+
embeddings = self.projection(features).flatten(2).transpose(1, 2)
|
| 198 |
+
|
| 199 |
+
return embeddings
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
class ViTHybridSelfAttention(nn.Module):
|
| 203 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 204 |
+
super().__init__()
|
| 205 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 206 |
+
raise ValueError(
|
| 207 |
+
f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
|
| 208 |
+
f"heads {config.num_attention_heads}."
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
self.num_attention_heads = config.num_attention_heads
|
| 212 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 213 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 214 |
+
|
| 215 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 216 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 217 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 218 |
+
|
| 219 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 220 |
+
|
| 221 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 222 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 223 |
+
x = x.view(new_x_shape)
|
| 224 |
+
return x.permute(0, 2, 1, 3)
|
| 225 |
+
|
| 226 |
+
def forward(
|
| 227 |
+
self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
|
| 228 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 229 |
+
mixed_query_layer = self.query(hidden_states)
|
| 230 |
+
|
| 231 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 232 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 233 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 234 |
+
|
| 235 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 236 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 237 |
+
|
| 238 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 239 |
+
|
| 240 |
+
# Normalize the attention scores to probabilities.
|
| 241 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 242 |
+
|
| 243 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 244 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 245 |
+
attention_probs = self.dropout(attention_probs)
|
| 246 |
+
|
| 247 |
+
# Mask heads if we want to
|
| 248 |
+
if head_mask is not None:
|
| 249 |
+
attention_probs = attention_probs * head_mask
|
| 250 |
+
|
| 251 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 252 |
+
|
| 253 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 254 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 255 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 256 |
+
|
| 257 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 258 |
+
|
| 259 |
+
return outputs
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class ViTHybridSdpaSelfAttention(ViTHybridSelfAttention):
|
| 263 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 264 |
+
super().__init__(config)
|
| 265 |
+
self.attention_probs_dropout_prob = config.attention_probs_dropout_prob
|
| 266 |
+
|
| 267 |
+
def forward(
|
| 268 |
+
self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
|
| 269 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 270 |
+
mixed_query_layer = self.query(hidden_states)
|
| 271 |
+
|
| 272 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 273 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 274 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 275 |
+
|
| 276 |
+
context_layer = torch.nn.functional.scaled_dot_product_attention(
|
| 277 |
+
query_layer,
|
| 278 |
+
key_layer,
|
| 279 |
+
value_layer,
|
| 280 |
+
head_mask,
|
| 281 |
+
self.attention_probs_dropout_prob if self.training else 0.0,
|
| 282 |
+
is_causal=False,
|
| 283 |
+
scale=None,
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 287 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 288 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 289 |
+
|
| 290 |
+
return context_layer, None
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
class ViTHybridSelfOutput(nn.Module):
|
| 294 |
+
"""
|
| 295 |
+
The residual connection is defined in ViTHybridLayer instead of here (as is the case with other models), due to the
|
| 296 |
+
layernorm applied before each block.
|
| 297 |
+
"""
|
| 298 |
+
|
| 299 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 300 |
+
super().__init__()
|
| 301 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 302 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 303 |
+
|
| 304 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 305 |
+
hidden_states = self.dense(hidden_states)
|
| 306 |
+
hidden_states = self.dropout(hidden_states)
|
| 307 |
+
|
| 308 |
+
return hidden_states
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class ViTHybridAttention(nn.Module):
|
| 312 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 313 |
+
super().__init__()
|
| 314 |
+
self.attention = ViTHybridSelfAttention(config)
|
| 315 |
+
self.output = ViTHybridSelfOutput(config)
|
| 316 |
+
self.pruned_heads = set()
|
| 317 |
+
|
| 318 |
+
def prune_heads(self, heads: Set[int]) -> None:
|
| 319 |
+
if len(heads) == 0:
|
| 320 |
+
return
|
| 321 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 322 |
+
heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
# Prune linear layers
|
| 326 |
+
self.attention.query = prune_linear_layer(self.attention.query, index)
|
| 327 |
+
self.attention.key = prune_linear_layer(self.attention.key, index)
|
| 328 |
+
self.attention.value = prune_linear_layer(self.attention.value, index)
|
| 329 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 330 |
+
|
| 331 |
+
# Update hyper params and store pruned heads
|
| 332 |
+
self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
|
| 333 |
+
self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
|
| 334 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 335 |
+
|
| 336 |
+
def forward(
|
| 337 |
+
self,
|
| 338 |
+
hidden_states: torch.Tensor,
|
| 339 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 340 |
+
output_attentions: bool = False,
|
| 341 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 342 |
+
self_outputs = self.attention(hidden_states, head_mask, output_attentions)
|
| 343 |
+
|
| 344 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 345 |
+
|
| 346 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 347 |
+
return outputs
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
class ViTHybridSdpaAttention(ViTHybridAttention):
|
| 351 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 352 |
+
super().__init__(config)
|
| 353 |
+
self.attention = ViTHybridSdpaSelfAttention(config)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
class ViTHybridIntermediate(nn.Module):
|
| 357 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 358 |
+
super().__init__()
|
| 359 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 360 |
+
if isinstance(config.hidden_act, str):
|
| 361 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 362 |
+
else:
|
| 363 |
+
self.intermediate_act_fn = config.hidden_act
|
| 364 |
+
|
| 365 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 366 |
+
hidden_states = self.dense(hidden_states)
|
| 367 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 368 |
+
|
| 369 |
+
return hidden_states
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
class ViTHybridOutput(nn.Module):
|
| 373 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 374 |
+
super().__init__()
|
| 375 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 376 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 377 |
+
|
| 378 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 379 |
+
hidden_states = self.dense(hidden_states)
|
| 380 |
+
hidden_states = self.dropout(hidden_states)
|
| 381 |
+
|
| 382 |
+
hidden_states = hidden_states + input_tensor
|
| 383 |
+
|
| 384 |
+
return hidden_states
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
VIT_HYBRID_ATTENTION_CLASSES = {
|
| 388 |
+
"eager": ViTHybridAttention,
|
| 389 |
+
"sdpa": ViTHybridSdpaAttention,
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
class ViTHybridLayer(nn.Module):
|
| 394 |
+
"""This corresponds to the Block class in the timm implementation."""
|
| 395 |
+
|
| 396 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 397 |
+
super().__init__()
|
| 398 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 399 |
+
self.seq_len_dim = 1
|
| 400 |
+
self.attention = VIT_HYBRID_ATTENTION_CLASSES[config._attn_implementation](config)
|
| 401 |
+
self.intermediate = ViTHybridIntermediate(config)
|
| 402 |
+
self.output = ViTHybridOutput(config)
|
| 403 |
+
self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 404 |
+
self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 405 |
+
|
| 406 |
+
def forward(
|
| 407 |
+
self,
|
| 408 |
+
hidden_states: torch.Tensor,
|
| 409 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 410 |
+
output_attentions: bool = False,
|
| 411 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 412 |
+
self_attention_outputs = self.attention(
|
| 413 |
+
self.layernorm_before(hidden_states), # in ViTHybrid, layernorm is applied before self-attention
|
| 414 |
+
head_mask,
|
| 415 |
+
output_attentions=output_attentions,
|
| 416 |
+
)
|
| 417 |
+
attention_output = self_attention_outputs[0]
|
| 418 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 419 |
+
|
| 420 |
+
# first residual connection
|
| 421 |
+
# We assign to correct device for `accelerate`, check: https://github.com/huggingface/transformers/pull/20705/
|
| 422 |
+
hidden_states = attention_output + hidden_states.to(attention_output.device)
|
| 423 |
+
|
| 424 |
+
# in ViTHybrid, layernorm is also applied after self-attention
|
| 425 |
+
layer_output = self.layernorm_after(hidden_states)
|
| 426 |
+
layer_output = self.intermediate(layer_output)
|
| 427 |
+
|
| 428 |
+
# second residual connection is done here
|
| 429 |
+
layer_output = self.output(layer_output, hidden_states)
|
| 430 |
+
|
| 431 |
+
outputs = (layer_output,) + outputs
|
| 432 |
+
|
| 433 |
+
return outputs
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
class ViTHybridEncoder(nn.Module):
|
| 437 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 438 |
+
super().__init__()
|
| 439 |
+
self.config = config
|
| 440 |
+
self.layer = nn.ModuleList([ViTHybridLayer(config) for _ in range(config.num_hidden_layers)])
|
| 441 |
+
self.gradient_checkpointing = False
|
| 442 |
+
|
| 443 |
+
def forward(
|
| 444 |
+
self,
|
| 445 |
+
hidden_states: torch.Tensor,
|
| 446 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 447 |
+
output_attentions: bool = False,
|
| 448 |
+
output_hidden_states: bool = False,
|
| 449 |
+
return_dict: bool = True,
|
| 450 |
+
) -> Union[tuple, BaseModelOutput]:
|
| 451 |
+
all_hidden_states = () if output_hidden_states else None
|
| 452 |
+
all_self_attentions = () if output_attentions else None
|
| 453 |
+
|
| 454 |
+
for i, layer_module in enumerate(self.layer):
|
| 455 |
+
if output_hidden_states:
|
| 456 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 457 |
+
|
| 458 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 459 |
+
|
| 460 |
+
if self.gradient_checkpointing and self.training:
|
| 461 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 462 |
+
layer_module.__call__,
|
| 463 |
+
hidden_states,
|
| 464 |
+
layer_head_mask,
|
| 465 |
+
output_attentions,
|
| 466 |
+
)
|
| 467 |
+
else:
|
| 468 |
+
layer_outputs = layer_module(hidden_states, layer_head_mask, output_attentions)
|
| 469 |
+
|
| 470 |
+
hidden_states = layer_outputs[0]
|
| 471 |
+
|
| 472 |
+
if output_attentions:
|
| 473 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 474 |
+
|
| 475 |
+
if output_hidden_states:
|
| 476 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 477 |
+
|
| 478 |
+
if not return_dict:
|
| 479 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
|
| 480 |
+
return BaseModelOutput(
|
| 481 |
+
last_hidden_state=hidden_states,
|
| 482 |
+
hidden_states=all_hidden_states,
|
| 483 |
+
attentions=all_self_attentions,
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
class ViTHybridPreTrainedModel(PreTrainedModel):
|
| 488 |
+
"""
|
| 489 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 490 |
+
models.
|
| 491 |
+
"""
|
| 492 |
+
|
| 493 |
+
config_class = ViTHybridConfig
|
| 494 |
+
base_model_prefix = "vit"
|
| 495 |
+
main_input_name = "pixel_values"
|
| 496 |
+
supports_gradient_checkpointing = True
|
| 497 |
+
_no_split_modules = ["ViTHybridEmbeddings", "ViTHybridLayer"]
|
| 498 |
+
_supports_sdpa = True
|
| 499 |
+
|
| 500 |
+
def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
|
| 501 |
+
"""Initialize the weights"""
|
| 502 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 503 |
+
# Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
|
| 504 |
+
# `trunc_normal_cpu` not implemented in `half` issues
|
| 505 |
+
module.weight.data = nn.init.trunc_normal_(
|
| 506 |
+
module.weight.data.to(torch.float32), mean=0.0, std=self.config.initializer_range
|
| 507 |
+
).to(module.weight.dtype)
|
| 508 |
+
if module.bias is not None:
|
| 509 |
+
module.bias.data.zero_()
|
| 510 |
+
elif isinstance(module, nn.LayerNorm):
|
| 511 |
+
module.bias.data.zero_()
|
| 512 |
+
module.weight.data.fill_(1.0)
|
| 513 |
+
elif isinstance(module, ViTHybridEmbeddings):
|
| 514 |
+
module.position_embeddings.data = nn.init.trunc_normal_(
|
| 515 |
+
module.position_embeddings.data.to(torch.float32),
|
| 516 |
+
mean=0.0,
|
| 517 |
+
std=self.config.initializer_range,
|
| 518 |
+
).to(module.position_embeddings.dtype)
|
| 519 |
+
|
| 520 |
+
module.cls_token.data = nn.init.trunc_normal_(
|
| 521 |
+
module.cls_token.data.to(torch.float32),
|
| 522 |
+
mean=0.0,
|
| 523 |
+
std=self.config.initializer_range,
|
| 524 |
+
).to(module.cls_token.dtype)
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
VIT_START_DOCSTRING = r"""
|
| 528 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 529 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 530 |
+
behavior.
|
| 531 |
+
|
| 532 |
+
Parameters:
|
| 533 |
+
config ([`ViTHybridConfig`]): Model configuration class with all the parameters of the model.
|
| 534 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 535 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 536 |
+
"""
|
| 537 |
+
|
| 538 |
+
VIT_INPUTS_DOCSTRING = r"""
|
| 539 |
+
Args:
|
| 540 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 541 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
|
| 542 |
+
[`ViTHybridImageProcessor.__call__`] for details.
|
| 543 |
+
|
| 544 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 545 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 546 |
+
|
| 547 |
+
- 1 indicates the head is **not masked**,
|
| 548 |
+
- 0 indicates the head is **masked**.
|
| 549 |
+
|
| 550 |
+
output_attentions (`bool`, *optional*):
|
| 551 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 552 |
+
tensors for more detail.
|
| 553 |
+
output_hidden_states (`bool`, *optional*):
|
| 554 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 555 |
+
more detail.
|
| 556 |
+
return_dict (`bool`, *optional*):
|
| 557 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 558 |
+
"""
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
@add_start_docstrings(
|
| 562 |
+
"The bare ViT Hybrid Model transformer outputting raw hidden-states without any specific head on top.",
|
| 563 |
+
VIT_START_DOCSTRING,
|
| 564 |
+
)
|
| 565 |
+
class ViTHybridModel(ViTHybridPreTrainedModel):
|
| 566 |
+
def __init__(self, config: ViTHybridConfig, add_pooling_layer: bool = True, use_mask_token: bool = False):
|
| 567 |
+
super().__init__(config)
|
| 568 |
+
self.config = config
|
| 569 |
+
|
| 570 |
+
self.embeddings = ViTHybridEmbeddings(config, use_mask_token=use_mask_token)
|
| 571 |
+
self.encoder = ViTHybridEncoder(config)
|
| 572 |
+
|
| 573 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 574 |
+
self.pooler = ViTHybridPooler(config) if add_pooling_layer else None
|
| 575 |
+
|
| 576 |
+
# Initialize weights and apply final processing
|
| 577 |
+
self.post_init()
|
| 578 |
+
|
| 579 |
+
def get_input_embeddings(self) -> ViTHybridPatchEmbeddings:
|
| 580 |
+
return self.embeddings.patch_embeddings
|
| 581 |
+
|
| 582 |
+
def _prune_heads(self, heads_to_prune: Dict[int, List[int]]) -> None:
|
| 583 |
+
"""
|
| 584 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 585 |
+
class PreTrainedModel
|
| 586 |
+
"""
|
| 587 |
+
for layer, heads in heads_to_prune.items():
|
| 588 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 589 |
+
|
| 590 |
+
@add_start_docstrings_to_model_forward(VIT_INPUTS_DOCSTRING)
|
| 591 |
+
@add_code_sample_docstrings(
|
| 592 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 593 |
+
output_type=BaseModelOutputWithPooling,
|
| 594 |
+
config_class=_CONFIG_FOR_DOC,
|
| 595 |
+
modality="vision",
|
| 596 |
+
expected_output=_EXPECTED_OUTPUT_SHAPE,
|
| 597 |
+
)
|
| 598 |
+
def forward(
|
| 599 |
+
self,
|
| 600 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 601 |
+
bool_masked_pos: Optional[torch.BoolTensor] = None,
|
| 602 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 603 |
+
output_attentions: Optional[bool] = None,
|
| 604 |
+
output_hidden_states: Optional[bool] = None,
|
| 605 |
+
interpolate_pos_encoding: Optional[bool] = None,
|
| 606 |
+
return_dict: Optional[bool] = None,
|
| 607 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 608 |
+
r"""
|
| 609 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
|
| 610 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
|
| 611 |
+
"""
|
| 612 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 613 |
+
output_hidden_states = (
|
| 614 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 615 |
+
)
|
| 616 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 617 |
+
|
| 618 |
+
if pixel_values is None:
|
| 619 |
+
raise ValueError("You have to specify pixel_values")
|
| 620 |
+
|
| 621 |
+
# Prepare head mask if needed
|
| 622 |
+
# 1.0 in head_mask indicate we keep the head
|
| 623 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 624 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 625 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 626 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 627 |
+
|
| 628 |
+
# TODO: maybe have a cleaner way to cast the input (from `ImageProcessor` side?)
|
| 629 |
+
expected_dtype = self.embeddings.patch_embeddings.projection.weight.dtype
|
| 630 |
+
if pixel_values.dtype != expected_dtype:
|
| 631 |
+
pixel_values = pixel_values.to(expected_dtype)
|
| 632 |
+
|
| 633 |
+
embedding_output = self.embeddings(
|
| 634 |
+
pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
encoder_outputs = self.encoder(
|
| 638 |
+
embedding_output,
|
| 639 |
+
head_mask=head_mask,
|
| 640 |
+
output_attentions=output_attentions,
|
| 641 |
+
output_hidden_states=output_hidden_states,
|
| 642 |
+
return_dict=return_dict,
|
| 643 |
+
)
|
| 644 |
+
sequence_output = encoder_outputs[0]
|
| 645 |
+
sequence_output = self.layernorm(sequence_output)
|
| 646 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 647 |
+
|
| 648 |
+
if not return_dict:
|
| 649 |
+
head_outputs = (sequence_output, pooled_output) if pooled_output is not None else (sequence_output,)
|
| 650 |
+
return head_outputs + encoder_outputs[1:]
|
| 651 |
+
|
| 652 |
+
return BaseModelOutputWithPooling(
|
| 653 |
+
last_hidden_state=sequence_output,
|
| 654 |
+
pooler_output=pooled_output,
|
| 655 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 656 |
+
attentions=encoder_outputs.attentions,
|
| 657 |
+
)
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
class ViTHybridPooler(nn.Module):
|
| 661 |
+
def __init__(self, config: ViTHybridConfig):
|
| 662 |
+
super().__init__()
|
| 663 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 664 |
+
self.activation = nn.Tanh()
|
| 665 |
+
|
| 666 |
+
def forward(self, hidden_states):
|
| 667 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 668 |
+
# to the first token.
|
| 669 |
+
first_token_tensor = hidden_states[:, 0]
|
| 670 |
+
pooled_output = self.dense(first_token_tensor)
|
| 671 |
+
pooled_output = self.activation(pooled_output)
|
| 672 |
+
return pooled_output
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
@add_start_docstrings(
|
| 676 |
+
"""
|
| 677 |
+
ViT Hybrid Model transformer with an image classification head on top (a linear layer on top of the final hidden
|
| 678 |
+
state of the [CLS] token) e.g. for ImageNet.
|
| 679 |
+
""",
|
| 680 |
+
VIT_START_DOCSTRING,
|
| 681 |
+
)
|
| 682 |
+
class ViTHybridForImageClassification(ViTHybridPreTrainedModel):
|
| 683 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 684 |
+
super().__init__(config)
|
| 685 |
+
|
| 686 |
+
self.num_labels = config.num_labels
|
| 687 |
+
self.vit = ViTHybridModel(config, add_pooling_layer=False)
|
| 688 |
+
|
| 689 |
+
# Classifier head
|
| 690 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 691 |
+
|
| 692 |
+
# Initialize weights and apply final processing
|
| 693 |
+
self.post_init()
|
| 694 |
+
|
| 695 |
+
@add_start_docstrings_to_model_forward(VIT_INPUTS_DOCSTRING)
|
| 696 |
+
@add_code_sample_docstrings(
|
| 697 |
+
checkpoint=_IMAGE_CLASS_CHECKPOINT,
|
| 698 |
+
output_type=ImageClassifierOutput,
|
| 699 |
+
config_class=_CONFIG_FOR_DOC,
|
| 700 |
+
expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
|
| 701 |
+
)
|
| 702 |
+
def forward(
|
| 703 |
+
self,
|
| 704 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 705 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 706 |
+
labels: Optional[torch.Tensor] = None,
|
| 707 |
+
output_attentions: Optional[bool] = None,
|
| 708 |
+
output_hidden_states: Optional[bool] = None,
|
| 709 |
+
interpolate_pos_encoding: Optional[bool] = None,
|
| 710 |
+
return_dict: Optional[bool] = None,
|
| 711 |
+
) -> Union[tuple, ImageClassifierOutput]:
|
| 712 |
+
r"""
|
| 713 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 714 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 715 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 716 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 717 |
+
"""
|
| 718 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 719 |
+
|
| 720 |
+
outputs = self.vit(
|
| 721 |
+
pixel_values,
|
| 722 |
+
head_mask=head_mask,
|
| 723 |
+
output_attentions=output_attentions,
|
| 724 |
+
output_hidden_states=output_hidden_states,
|
| 725 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 726 |
+
return_dict=return_dict,
|
| 727 |
+
)
|
| 728 |
+
|
| 729 |
+
sequence_output = outputs[0]
|
| 730 |
+
|
| 731 |
+
logits = self.classifier(sequence_output[:, 0, :])
|
| 732 |
+
|
| 733 |
+
loss = None
|
| 734 |
+
if labels is not None:
|
| 735 |
+
# move labels to correct device to enable model parallelism
|
| 736 |
+
labels = labels.to(logits.device)
|
| 737 |
+
if self.config.problem_type is None:
|
| 738 |
+
if self.num_labels == 1:
|
| 739 |
+
self.config.problem_type = "regression"
|
| 740 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 741 |
+
self.config.problem_type = "single_label_classification"
|
| 742 |
+
else:
|
| 743 |
+
self.config.problem_type = "multi_label_classification"
|
| 744 |
+
|
| 745 |
+
if self.config.problem_type == "regression":
|
| 746 |
+
loss_fct = MSELoss()
|
| 747 |
+
if self.num_labels == 1:
|
| 748 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 749 |
+
else:
|
| 750 |
+
loss = loss_fct(logits, labels)
|
| 751 |
+
elif self.config.problem_type == "single_label_classification":
|
| 752 |
+
loss_fct = CrossEntropyLoss()
|
| 753 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 754 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 755 |
+
loss_fct = BCEWithLogitsLoss()
|
| 756 |
+
loss = loss_fct(logits, labels)
|
| 757 |
+
|
| 758 |
+
if not return_dict:
|
| 759 |
+
output = (logits,) + outputs[1:]
|
| 760 |
+
return ((loss,) + output) if loss is not None else output
|
| 761 |
+
|
| 762 |
+
return ImageClassifierOutput(
|
| 763 |
+
loss=loss,
|
| 764 |
+
logits=logits,
|
| 765 |
+
hidden_states=outputs.hidden_states,
|
| 766 |
+
attentions=outputs.attentions,
|
| 767 |
+
)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/xlm_prophetnet/__init__.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_import_structure = {
|
| 20 |
+
"configuration_xlm_prophetnet": ["XLMProphetNetConfig"],
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
if not is_sentencepiece_available():
|
| 25 |
+
raise OptionalDependencyNotAvailable()
|
| 26 |
+
except OptionalDependencyNotAvailable:
|
| 27 |
+
pass
|
| 28 |
+
else:
|
| 29 |
+
_import_structure["tokenization_xlm_prophetnet"] = ["XLMProphetNetTokenizer"]
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
if not is_torch_available():
|
| 33 |
+
raise OptionalDependencyNotAvailable()
|
| 34 |
+
except OptionalDependencyNotAvailable:
|
| 35 |
+
pass
|
| 36 |
+
else:
|
| 37 |
+
_import_structure["modeling_xlm_prophetnet"] = [
|
| 38 |
+
"XLMProphetNetDecoder",
|
| 39 |
+
"XLMProphetNetEncoder",
|
| 40 |
+
"XLMProphetNetForCausalLM",
|
| 41 |
+
"XLMProphetNetForConditionalGeneration",
|
| 42 |
+
"XLMProphetNetModel",
|
| 43 |
+
"XLMProphetNetPreTrainedModel",
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if TYPE_CHECKING:
|
| 48 |
+
from .configuration_xlm_prophetnet import XLMProphetNetConfig
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
if not is_sentencepiece_available():
|
| 52 |
+
raise OptionalDependencyNotAvailable()
|
| 53 |
+
except OptionalDependencyNotAvailable:
|
| 54 |
+
pass
|
| 55 |
+
else:
|
| 56 |
+
from .tokenization_xlm_prophetnet import XLMProphetNetTokenizer
|
| 57 |
+
|
| 58 |
+
try:
|
| 59 |
+
if not is_torch_available():
|
| 60 |
+
raise OptionalDependencyNotAvailable()
|
| 61 |
+
except OptionalDependencyNotAvailable:
|
| 62 |
+
pass
|
| 63 |
+
else:
|
| 64 |
+
from .modeling_xlm_prophetnet import (
|
| 65 |
+
XLMProphetNetDecoder,
|
| 66 |
+
XLMProphetNetEncoder,
|
| 67 |
+
XLMProphetNetForCausalLM,
|
| 68 |
+
XLMProphetNetForConditionalGeneration,
|
| 69 |
+
XLMProphetNetModel,
|
| 70 |
+
XLMProphetNetPreTrainedModel,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
else:
|
| 74 |
+
import sys
|
| 75 |
+
|
| 76 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/xlm_prophetnet/configuration_xlm_prophetnet.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The Microsoft 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 |
+
"""XLM-ProphetNet model configuration"""
|
| 16 |
+
|
| 17 |
+
from typing import Callable, Optional, Union
|
| 18 |
+
|
| 19 |
+
from ....configuration_utils import PretrainedConfig
|
| 20 |
+
from ....utils import logging
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class XLMProphetNetConfig(PretrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
This is the configuration class to store the configuration of a [`XLMProphetNetModel`]. It is used to instantiate a
|
| 29 |
+
XLMProphetNet model according to the specified arguments, defining the model architecture. Instantiating a
|
| 30 |
+
configuration with the defaults will yield a similar configuration to that of the XLMProphetNet
|
| 31 |
+
[microsoft/xprophetnet-large-wiki100-cased](https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased)
|
| 32 |
+
architecture.
|
| 33 |
+
|
| 34 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 35 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
activation_dropout (`float`, *optional*, defaults to 0.1):
|
| 39 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 40 |
+
activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 41 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 42 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 43 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
| 44 |
+
Vocabulary size of the ProphetNET model. Defines the number of different tokens that can be represented by
|
| 45 |
+
the `inputs_ids` passed when calling [`XLMProphetNetModel`].
|
| 46 |
+
hidden_size (`int`, *optional*, defaults to 1024):
|
| 47 |
+
Dimensionality of the layers and the pooler layer.
|
| 48 |
+
encoder_ffn_dim (`int`, *optional*, defaults to 4096):
|
| 49 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
|
| 50 |
+
num_encoder_layers (`int`, *optional*, defaults to 12):
|
| 51 |
+
Number of encoder layers.
|
| 52 |
+
num_encoder_attention_heads (`int`, *optional*, defaults to 16):
|
| 53 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 54 |
+
decoder_ffn_dim (`int`, *optional*, defaults to 4096):
|
| 55 |
+
Dimensionality of the `intermediate` (often named feed-forward) layer in decoder.
|
| 56 |
+
num_decoder_layers (`int`, *optional*, defaults to 12):
|
| 57 |
+
Number of decoder layers.
|
| 58 |
+
num_decoder_attention_heads (`int`, *optional*, defaults to 16):
|
| 59 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 60 |
+
attention_dropout (`float`, *optional*, defaults to 0.1):
|
| 61 |
+
The dropout ratio for the attention probabilities.
|
| 62 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 63 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 64 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 65 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 66 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 67 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 68 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 69 |
+
add_cross_attention (`bool`, *optional*, defaults to `True`):
|
| 70 |
+
Whether cross-attention layers should be added to the model.
|
| 71 |
+
is_encoder_decoder (`bool`, *optional*, defaults to `True`):
|
| 72 |
+
Whether this is an encoder/decoder model.
|
| 73 |
+
pad_token_id (`int`, *optional*, defaults to 1)
|
| 74 |
+
Padding token id.
|
| 75 |
+
bos_token_id (`int`, *optional*, defaults to 0)
|
| 76 |
+
Beginning of stream token id.
|
| 77 |
+
eos_token_id (`int`, *optional*, defaults to 2)
|
| 78 |
+
End of stream token id.
|
| 79 |
+
ngram (`int`, *optional*, defaults to 2)
|
| 80 |
+
Number of future tokens to predict. Set to 1 to be same as traditional Language model to predict next first
|
| 81 |
+
token.
|
| 82 |
+
num_buckets (`int`, *optional*, defaults to 32)
|
| 83 |
+
The number of buckets to use for each attention layer. This is for relative position calculation. See the
|
| 84 |
+
[T5 paper](see https://arxiv.org/abs/1910.10683) for more details.
|
| 85 |
+
relative_max_distance (`int`, *optional*, defaults to 128)
|
| 86 |
+
Relative distances greater than this number will be put into the last same bucket. This is for relative
|
| 87 |
+
position calculation. See the [T5 paper](see https://arxiv.org/abs/1910.10683) for more details.
|
| 88 |
+
disable_ngram_loss (`bool`, *optional*, defaults to `False`):
|
| 89 |
+
Whether be trained predicting only the next first token.
|
| 90 |
+
eps (`float`, *optional*, defaults to 0.0):
|
| 91 |
+
Controls the `epsilon` parameter value for label smoothing in the loss calculation. If set to 0, no label
|
| 92 |
+
smoothing is performed.
|
| 93 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 94 |
+
Whether or not the model should return the last key/values attentions (not used by all models).
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
model_type = "xlm-prophetnet"
|
| 98 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 99 |
+
attribute_map = {
|
| 100 |
+
"num_attention_heads": "num_encoder_attention_heads",
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
def __init__(
|
| 104 |
+
self,
|
| 105 |
+
activation_dropout: Optional[float] = 0.1,
|
| 106 |
+
activation_function: Optional[Union[str, Callable]] = "gelu",
|
| 107 |
+
vocab_size: Optional[int] = 30522,
|
| 108 |
+
hidden_size: Optional[int] = 1024,
|
| 109 |
+
encoder_ffn_dim: Optional[int] = 4096,
|
| 110 |
+
num_encoder_layers: Optional[int] = 12,
|
| 111 |
+
num_encoder_attention_heads: Optional[int] = 16,
|
| 112 |
+
decoder_ffn_dim: Optional[int] = 4096,
|
| 113 |
+
num_decoder_layers: Optional[int] = 12,
|
| 114 |
+
num_decoder_attention_heads: Optional[int] = 16,
|
| 115 |
+
attention_dropout: Optional[float] = 0.1,
|
| 116 |
+
dropout: Optional[float] = 0.1,
|
| 117 |
+
max_position_embeddings: Optional[int] = 512,
|
| 118 |
+
init_std: Optional[float] = 0.02,
|
| 119 |
+
is_encoder_decoder: Optional[bool] = True,
|
| 120 |
+
add_cross_attention: Optional[bool] = True,
|
| 121 |
+
decoder_start_token_id: Optional[int] = 0,
|
| 122 |
+
ngram: Optional[int] = 2,
|
| 123 |
+
num_buckets: Optional[int] = 32,
|
| 124 |
+
relative_max_distance: Optional[int] = 128,
|
| 125 |
+
disable_ngram_loss: Optional[bool] = False,
|
| 126 |
+
eps: Optional[float] = 0.0,
|
| 127 |
+
use_cache: Optional[bool] = True,
|
| 128 |
+
pad_token_id: Optional[int] = 0,
|
| 129 |
+
bos_token_id: Optional[int] = 1,
|
| 130 |
+
eos_token_id: Optional[int] = 2,
|
| 131 |
+
**kwargs,
|
| 132 |
+
):
|
| 133 |
+
self.vocab_size = vocab_size
|
| 134 |
+
self.hidden_size = hidden_size
|
| 135 |
+
self.encoder_ffn_dim = encoder_ffn_dim
|
| 136 |
+
self.num_encoder_layers = num_encoder_layers
|
| 137 |
+
self.num_encoder_attention_heads = num_encoder_attention_heads
|
| 138 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 139 |
+
self.num_decoder_layers = num_decoder_layers
|
| 140 |
+
self.num_decoder_attention_heads = num_decoder_attention_heads
|
| 141 |
+
self.max_position_embeddings = max_position_embeddings
|
| 142 |
+
self.init_std = init_std # Normal(0, this parameter)
|
| 143 |
+
self.activation_function = activation_function
|
| 144 |
+
|
| 145 |
+
# parameters for xlmprophetnet
|
| 146 |
+
self.ngram = ngram
|
| 147 |
+
self.num_buckets = num_buckets
|
| 148 |
+
self.relative_max_distance = relative_max_distance
|
| 149 |
+
self.disable_ngram_loss = disable_ngram_loss
|
| 150 |
+
self.eps = eps
|
| 151 |
+
|
| 152 |
+
# 3 Types of Dropout
|
| 153 |
+
self.attention_dropout = attention_dropout
|
| 154 |
+
self.activation_dropout = activation_dropout
|
| 155 |
+
self.dropout = dropout
|
| 156 |
+
|
| 157 |
+
self.use_cache = use_cache
|
| 158 |
+
|
| 159 |
+
super().__init__(
|
| 160 |
+
pad_token_id=pad_token_id,
|
| 161 |
+
bos_token_id=bos_token_id,
|
| 162 |
+
eos_token_id=eos_token_id,
|
| 163 |
+
is_encoder_decoder=is_encoder_decoder,
|
| 164 |
+
add_cross_attention=add_cross_attention,
|
| 165 |
+
decoder_start_token_id=decoder_start_token_id,
|
| 166 |
+
**kwargs,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
@property
|
| 170 |
+
def num_hidden_layers(self) -> int:
|
| 171 |
+
return self.num_encoder_layers + self.num_decoder_layers
|
| 172 |
+
|
| 173 |
+
@num_hidden_layers.setter
|
| 174 |
+
def num_hidden_layers(self, value):
|
| 175 |
+
raise NotImplementedError(
|
| 176 |
+
"This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and"
|
| 177 |
+
" `num_decoder_layers`."
|
| 178 |
+
)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/xlm_prophetnet/modeling_xlm_prophetnet.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/deprecated/xlm_prophetnet/tokenization_xlm_prophetnet.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The Microsoft Authors and The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import collections
|
| 17 |
+
import os
|
| 18 |
+
from shutil import copyfile
|
| 19 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 20 |
+
|
| 21 |
+
from ....tokenization_utils import PreTrainedTokenizer
|
| 22 |
+
from ....utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
SPIECE_UNDERLINE = "▁"
|
| 28 |
+
|
| 29 |
+
VOCAB_FILES_NAMES = {"vocab_file": "prophetnet.tokenizer"}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def load_vocab(vocab_file):
|
| 33 |
+
"""Loads a vocabulary file into a dictionary."""
|
| 34 |
+
vocab = collections.OrderedDict()
|
| 35 |
+
with open(vocab_file, "r", encoding="utf-8") as reader:
|
| 36 |
+
tokens = reader.readlines()
|
| 37 |
+
for index, token in enumerate(tokens):
|
| 38 |
+
token = token.rstrip("\n")
|
| 39 |
+
vocab[token] = index
|
| 40 |
+
return vocab
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class XLMProphetNetTokenizer(PreTrainedTokenizer):
|
| 44 |
+
"""
|
| 45 |
+
Adapted from [`RobertaTokenizer`] and [`XLNetTokenizer`]. Based on
|
| 46 |
+
[SentencePiece](https://github.com/google/sentencepiece).
|
| 47 |
+
|
| 48 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 49 |
+
this superclass for more information regarding those methods.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
vocab_file (`str`):
|
| 53 |
+
Path to the vocabulary file.
|
| 54 |
+
bos_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 55 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 56 |
+
|
| 57 |
+
<Tip>
|
| 58 |
+
|
| 59 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 60 |
+
sequence. The token used is the `cls_token`.
|
| 61 |
+
|
| 62 |
+
</Tip>
|
| 63 |
+
|
| 64 |
+
eos_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 65 |
+
The end of sequence token.
|
| 66 |
+
|
| 67 |
+
<Tip>
|
| 68 |
+
|
| 69 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 70 |
+
The token used is the `sep_token`.
|
| 71 |
+
|
| 72 |
+
</Tip>
|
| 73 |
+
|
| 74 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 75 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 76 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 77 |
+
token of a sequence built with special tokens.
|
| 78 |
+
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
|
| 79 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 80 |
+
token instead.
|
| 81 |
+
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
|
| 82 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 83 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 84 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 85 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 86 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 87 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 88 |
+
modeling. This is the token which the model will try to predict.
|
| 89 |
+
sp_model_kwargs (`dict`, *optional*):
|
| 90 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
| 91 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
| 92 |
+
to set:
|
| 93 |
+
|
| 94 |
+
- `enable_sampling`: Enable subword regularization.
|
| 95 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
| 96 |
+
|
| 97 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
| 98 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
| 99 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
| 100 |
+
using forward-filtering-and-backward-sampling algorithm.
|
| 101 |
+
|
| 102 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
| 103 |
+
BPE-dropout.
|
| 104 |
+
|
| 105 |
+
Attributes:
|
| 106 |
+
sp_model (`SentencePieceProcessor`):
|
| 107 |
+
The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 111 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 112 |
+
|
| 113 |
+
def __init__(
|
| 114 |
+
self,
|
| 115 |
+
vocab_file,
|
| 116 |
+
bos_token="[SEP]",
|
| 117 |
+
eos_token="[SEP]",
|
| 118 |
+
sep_token="[SEP]",
|
| 119 |
+
unk_token="[UNK]",
|
| 120 |
+
pad_token="[PAD]",
|
| 121 |
+
cls_token="[CLS]",
|
| 122 |
+
mask_token="[MASK]",
|
| 123 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
| 124 |
+
**kwargs,
|
| 125 |
+
) -> None:
|
| 126 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 127 |
+
|
| 128 |
+
try:
|
| 129 |
+
import sentencepiece as spm
|
| 130 |
+
except ImportError:
|
| 131 |
+
logger.warning(
|
| 132 |
+
"You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece"
|
| 133 |
+
" pip install sentencepiece"
|
| 134 |
+
)
|
| 135 |
+
raise
|
| 136 |
+
|
| 137 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 138 |
+
self.sp_model.Load(str(vocab_file))
|
| 139 |
+
self.vocab_file = vocab_file
|
| 140 |
+
|
| 141 |
+
# Original fairseq vocab and spm vocab must be "aligned":
|
| 142 |
+
# Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
|
| 143 |
+
# -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
|
| 144 |
+
# fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-'
|
| 145 |
+
# spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a'
|
| 146 |
+
|
| 147 |
+
# put special tokens and [unused] tokens into the vocab
|
| 148 |
+
self.fairseq_tokens_to_ids = {"[PAD]": 0, "[CLS]": 1, "[SEP]": 2, "[UNK]": 3, "[MASK]": 4}
|
| 149 |
+
|
| 150 |
+
for i in range(10):
|
| 151 |
+
tok = f"[unused{i}]"
|
| 152 |
+
self.fairseq_tokens_to_ids[tok] = 5 + i
|
| 153 |
+
|
| 154 |
+
# The first "real" token "," has position 15 in the embedding vocab and position 3 in the spm vocab
|
| 155 |
+
self.fairseq_offset = 12
|
| 156 |
+
self.fairseq_ids_to_tokens = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
|
| 157 |
+
|
| 158 |
+
# TODO ArthurZ fairseq_ids_to_tokens should be removed
|
| 159 |
+
|
| 160 |
+
super().__init__(
|
| 161 |
+
bos_token=bos_token,
|
| 162 |
+
eos_token=eos_token,
|
| 163 |
+
sep_token=sep_token,
|
| 164 |
+
unk_token=unk_token,
|
| 165 |
+
pad_token=pad_token,
|
| 166 |
+
cls_token=cls_token,
|
| 167 |
+
mask_token=mask_token,
|
| 168 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 169 |
+
**kwargs,
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
@property
|
| 173 |
+
def can_save_slow_tokenizer(self) -> bool:
|
| 174 |
+
return os.path.isfile(self.vocab_file) if self.vocab_file else False
|
| 175 |
+
|
| 176 |
+
def __getstate__(self):
|
| 177 |
+
state = self.__dict__.copy()
|
| 178 |
+
state["sp_model"] = None
|
| 179 |
+
return state
|
| 180 |
+
|
| 181 |
+
def __setstate__(self, d):
|
| 182 |
+
self.__dict__ = d
|
| 183 |
+
try:
|
| 184 |
+
import sentencepiece as spm
|
| 185 |
+
except ImportError:
|
| 186 |
+
logger.warning(
|
| 187 |
+
"You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece"
|
| 188 |
+
" pip install sentencepiece"
|
| 189 |
+
)
|
| 190 |
+
raise
|
| 191 |
+
|
| 192 |
+
# for backward compatibility
|
| 193 |
+
if not hasattr(self, "sp_model_kwargs"):
|
| 194 |
+
self.sp_model_kwargs = {}
|
| 195 |
+
|
| 196 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 197 |
+
self.sp_model.Load(self.vocab_file)
|
| 198 |
+
|
| 199 |
+
def get_special_tokens_mask(
|
| 200 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 201 |
+
) -> List[int]:
|
| 202 |
+
"""
|
| 203 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 204 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 205 |
+
|
| 206 |
+
Args:
|
| 207 |
+
token_ids_0 (`List[int]`):
|
| 208 |
+
List of IDs.
|
| 209 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 210 |
+
Optional second list of IDs for sequence pairs.
|
| 211 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 212 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 213 |
+
|
| 214 |
+
Returns:
|
| 215 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
if already_has_special_tokens:
|
| 219 |
+
return super().get_special_tokens_mask(
|
| 220 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
if token_ids_1 is None:
|
| 224 |
+
return ([0] * len(token_ids_0)) + [1]
|
| 225 |
+
return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
|
| 226 |
+
|
| 227 |
+
def create_token_type_ids_from_sequences(
|
| 228 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 229 |
+
) -> List[int]:
|
| 230 |
+
"""
|
| 231 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLMProphetNet
|
| 232 |
+
does not make use of token type ids, therefore a list of zeros is returned.
|
| 233 |
+
|
| 234 |
+
Args:
|
| 235 |
+
token_ids_0 (`List[int]`):
|
| 236 |
+
List of IDs.
|
| 237 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 238 |
+
Optional second list of IDs for sequence pairs.
|
| 239 |
+
|
| 240 |
+
Returns:
|
| 241 |
+
`List[int]`: List of zeros.
|
| 242 |
+
|
| 243 |
+
"""
|
| 244 |
+
|
| 245 |
+
sep = [self.sep_token_id]
|
| 246 |
+
|
| 247 |
+
if token_ids_1 is None:
|
| 248 |
+
return len(token_ids_0 + sep) * [0]
|
| 249 |
+
return len(token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
|
| 250 |
+
|
| 251 |
+
@property
|
| 252 |
+
def vocab_size(self):
|
| 253 |
+
return len(self.sp_model) + self.fairseq_offset
|
| 254 |
+
|
| 255 |
+
def get_vocab(self):
|
| 256 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
| 257 |
+
vocab.update(self.added_tokens_encoder)
|
| 258 |
+
return vocab
|
| 259 |
+
|
| 260 |
+
def _tokenize(self, text: str) -> str:
|
| 261 |
+
return self.sp_model.encode(text, out_type=str)
|
| 262 |
+
|
| 263 |
+
def _convert_token_to_id(self, token):
|
| 264 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 265 |
+
if token in self.fairseq_tokens_to_ids:
|
| 266 |
+
return self.fairseq_tokens_to_ids[token]
|
| 267 |
+
spm_id = self.sp_model.PieceToId(token)
|
| 268 |
+
|
| 269 |
+
# Need to return unknown token if the SP model returned 0
|
| 270 |
+
return spm_id + self.fairseq_offset if spm_id else self.unk_token_id
|
| 271 |
+
|
| 272 |
+
def _convert_id_to_token(self, index):
|
| 273 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 274 |
+
if index in self.fairseq_ids_to_tokens:
|
| 275 |
+
return self.fairseq_ids_to_tokens[index]
|
| 276 |
+
return self.sp_model.IdToPiece(index - self.fairseq_offset)
|
| 277 |
+
|
| 278 |
+
def convert_tokens_to_string(self, tokens):
|
| 279 |
+
"""Converts a sequence of tokens (strings for sub-words) in a single string."""
|
| 280 |
+
out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
|
| 281 |
+
return out_string
|
| 282 |
+
|
| 283 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 284 |
+
if not os.path.isdir(save_directory):
|
| 285 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 286 |
+
return
|
| 287 |
+
out_vocab_file = os.path.join(
|
| 288 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
| 292 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 293 |
+
elif not os.path.isfile(self.vocab_file):
|
| 294 |
+
with open(out_vocab_file, "wb") as fi:
|
| 295 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 296 |
+
fi.write(content_spiece_model)
|
| 297 |
+
|
| 298 |
+
return (out_vocab_file,)
|
| 299 |
+
|
| 300 |
+
def build_inputs_with_special_tokens(
|
| 301 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 302 |
+
) -> List[int]:
|
| 303 |
+
"""
|
| 304 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 305 |
+
adding special tokens. A XLMProphetNet sequence has the following format:
|
| 306 |
+
|
| 307 |
+
- single sequence: `X [SEP]`
|
| 308 |
+
- pair of sequences: `A [SEP] B [SEP]`
|
| 309 |
+
|
| 310 |
+
Args:
|
| 311 |
+
token_ids_0 (`List[int]`):
|
| 312 |
+
List of IDs to which the special tokens will be added
|
| 313 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 314 |
+
Optional second list of IDs for sequence pairs.
|
| 315 |
+
|
| 316 |
+
Returns:
|
| 317 |
+
`List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 318 |
+
"""
|
| 319 |
+
|
| 320 |
+
if token_ids_1 is None:
|
| 321 |
+
return token_ids_0 + [self.sep_token_id]
|
| 322 |
+
sep = [self.sep_token_id]
|
| 323 |
+
return token_ids_0 + sep + token_ids_1 + sep
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_anything/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_depth_anything import *
|
| 22 |
+
from .modeling_depth_anything import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_anything/configuration_depth_anything.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""DepthAnything model configuration"""
|
| 16 |
+
|
| 17 |
+
import copy
|
| 18 |
+
|
| 19 |
+
from ...configuration_utils import PretrainedConfig
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
from ...utils.backbone_utils import verify_backbone_config_arguments
|
| 22 |
+
from ..auto.configuration_auto import CONFIG_MAPPING
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class DepthAnythingConfig(PretrainedConfig):
|
| 29 |
+
r"""
|
| 30 |
+
This is the configuration class to store the configuration of a [`DepthAnythingModel`]. It is used to instantiate a DepthAnything
|
| 31 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 32 |
+
defaults will yield a similar configuration to that of the DepthAnything
|
| 33 |
+
[LiheYoung/depth-anything-small-hf](https://huggingface.co/LiheYoung/depth-anything-small-hf) architecture.
|
| 34 |
+
|
| 35 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 36 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
backbone_config (`Union[Dict[str, Any], PretrainedConfig]`, *optional*):
|
| 40 |
+
The configuration of the backbone model. Only used in case `is_hybrid` is `True` or in case you want to
|
| 41 |
+
leverage the [`AutoBackbone`] API.
|
| 42 |
+
backbone (`str`, *optional*):
|
| 43 |
+
Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
|
| 44 |
+
will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
|
| 45 |
+
is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
|
| 46 |
+
use_pretrained_backbone (`bool`, *optional*, defaults to `False`):
|
| 47 |
+
Whether to use pretrained weights for the backbone.
|
| 48 |
+
use_timm_backbone (`bool`, *optional*, defaults to `False`):
|
| 49 |
+
Whether or not to use the `timm` library for the backbone. If set to `False`, will use the [`AutoBackbone`]
|
| 50 |
+
API.
|
| 51 |
+
backbone_kwargs (`dict`, *optional*):
|
| 52 |
+
Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
|
| 53 |
+
e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
|
| 54 |
+
patch_size (`int`, *optional*, defaults to 14):
|
| 55 |
+
The size of the patches to extract from the backbone features.
|
| 56 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 57 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 58 |
+
reassemble_hidden_size (`int`, *optional*, defaults to 384):
|
| 59 |
+
The number of input channels of the reassemble layers.
|
| 60 |
+
reassemble_factors (`List[int]`, *optional*, defaults to `[4, 2, 1, 0.5]`):
|
| 61 |
+
The up/downsampling factors of the reassemble layers.
|
| 62 |
+
neck_hidden_sizes (`List[str]`, *optional*, defaults to `[48, 96, 192, 384]`):
|
| 63 |
+
The hidden sizes to project to for the feature maps of the backbone.
|
| 64 |
+
fusion_hidden_size (`int`, *optional*, defaults to 64):
|
| 65 |
+
The number of channels before fusion.
|
| 66 |
+
head_in_index (`int`, *optional*, defaults to -1):
|
| 67 |
+
The index of the features to use in the depth estimation head.
|
| 68 |
+
head_hidden_size (`int`, *optional*, defaults to 32):
|
| 69 |
+
The number of output channels in the second convolution of the depth estimation head.
|
| 70 |
+
depth_estimation_type (`str`, *optional*, defaults to `"relative"`):
|
| 71 |
+
The type of depth estimation to use. Can be one of `["relative", "metric"]`.
|
| 72 |
+
max_depth (`float`, *optional*):
|
| 73 |
+
The maximum depth to use for the "metric" depth estimation head. 20 should be used for indoor models
|
| 74 |
+
and 80 for outdoor models. For "relative" depth estimation, this value is ignored.
|
| 75 |
+
|
| 76 |
+
Example:
|
| 77 |
+
|
| 78 |
+
```python
|
| 79 |
+
>>> from transformers import DepthAnythingConfig, DepthAnythingForDepthEstimation
|
| 80 |
+
|
| 81 |
+
>>> # Initializing a DepthAnything small style configuration
|
| 82 |
+
>>> configuration = DepthAnythingConfig()
|
| 83 |
+
|
| 84 |
+
>>> # Initializing a model from the DepthAnything small style configuration
|
| 85 |
+
>>> model = DepthAnythingForDepthEstimation(configuration)
|
| 86 |
+
|
| 87 |
+
>>> # Accessing the model configuration
|
| 88 |
+
>>> configuration = model.config
|
| 89 |
+
```"""
|
| 90 |
+
|
| 91 |
+
model_type = "depth_anything"
|
| 92 |
+
|
| 93 |
+
def __init__(
|
| 94 |
+
self,
|
| 95 |
+
backbone_config=None,
|
| 96 |
+
backbone=None,
|
| 97 |
+
use_pretrained_backbone=False,
|
| 98 |
+
use_timm_backbone=False,
|
| 99 |
+
backbone_kwargs=None,
|
| 100 |
+
patch_size=14,
|
| 101 |
+
initializer_range=0.02,
|
| 102 |
+
reassemble_hidden_size=384,
|
| 103 |
+
reassemble_factors=[4, 2, 1, 0.5],
|
| 104 |
+
neck_hidden_sizes=[48, 96, 192, 384],
|
| 105 |
+
fusion_hidden_size=64,
|
| 106 |
+
head_in_index=-1,
|
| 107 |
+
head_hidden_size=32,
|
| 108 |
+
depth_estimation_type="relative",
|
| 109 |
+
max_depth=None,
|
| 110 |
+
**kwargs,
|
| 111 |
+
):
|
| 112 |
+
super().__init__(**kwargs)
|
| 113 |
+
if backbone_config is None and backbone is None:
|
| 114 |
+
logger.info("`backbone_config` is `None`. Initializing the config with the default `Dinov2` backbone.")
|
| 115 |
+
backbone_config = CONFIG_MAPPING["dinov2"](
|
| 116 |
+
image_size=518,
|
| 117 |
+
hidden_size=384,
|
| 118 |
+
num_attention_heads=6,
|
| 119 |
+
out_indices=[9, 10, 11, 12],
|
| 120 |
+
apply_layernorm=True,
|
| 121 |
+
reshape_hidden_states=False,
|
| 122 |
+
)
|
| 123 |
+
elif isinstance(backbone_config, dict):
|
| 124 |
+
backbone_model_type = backbone_config.get("model_type")
|
| 125 |
+
config_class = CONFIG_MAPPING[backbone_model_type]
|
| 126 |
+
backbone_config = config_class.from_dict(backbone_config)
|
| 127 |
+
|
| 128 |
+
verify_backbone_config_arguments(
|
| 129 |
+
use_timm_backbone=use_timm_backbone,
|
| 130 |
+
use_pretrained_backbone=use_pretrained_backbone,
|
| 131 |
+
backbone=backbone,
|
| 132 |
+
backbone_config=backbone_config,
|
| 133 |
+
backbone_kwargs=backbone_kwargs,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
self.backbone_config = backbone_config
|
| 137 |
+
self.backbone = backbone
|
| 138 |
+
self.use_pretrained_backbone = use_pretrained_backbone
|
| 139 |
+
self.use_timm_backbone = use_timm_backbone
|
| 140 |
+
self.backbone_kwargs = backbone_kwargs
|
| 141 |
+
self.reassemble_hidden_size = reassemble_hidden_size
|
| 142 |
+
self.patch_size = patch_size
|
| 143 |
+
self.initializer_range = initializer_range
|
| 144 |
+
self.reassemble_factors = reassemble_factors
|
| 145 |
+
self.neck_hidden_sizes = neck_hidden_sizes
|
| 146 |
+
self.fusion_hidden_size = fusion_hidden_size
|
| 147 |
+
self.head_in_index = head_in_index
|
| 148 |
+
self.head_hidden_size = head_hidden_size
|
| 149 |
+
if depth_estimation_type not in ["relative", "metric"]:
|
| 150 |
+
raise ValueError("depth_estimation_type must be one of ['relative', 'metric']")
|
| 151 |
+
self.depth_estimation_type = depth_estimation_type
|
| 152 |
+
self.max_depth = max_depth if max_depth else 1
|
| 153 |
+
|
| 154 |
+
def to_dict(self):
|
| 155 |
+
"""
|
| 156 |
+
Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`]. Returns:
|
| 157 |
+
`Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
|
| 158 |
+
"""
|
| 159 |
+
output = copy.deepcopy(self.__dict__)
|
| 160 |
+
|
| 161 |
+
if output["backbone_config"] is not None:
|
| 162 |
+
output["backbone_config"] = self.backbone_config.to_dict()
|
| 163 |
+
|
| 164 |
+
output["model_type"] = self.__class__.model_type
|
| 165 |
+
return output
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
__all__ = ["DepthAnythingConfig"]
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_anything/convert_depth_anything_to_hf.py
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 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 Depth Anything checkpoints from the original repository. URL:
|
| 16 |
+
https://github.com/LiheYoung/Depth-Anything"""
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
import requests
|
| 22 |
+
import torch
|
| 23 |
+
from huggingface_hub import hf_hub_download
|
| 24 |
+
from PIL import Image
|
| 25 |
+
|
| 26 |
+
from transformers import DepthAnythingConfig, DepthAnythingForDepthEstimation, Dinov2Config, DPTImageProcessor
|
| 27 |
+
from transformers.utils import logging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logging.set_verbosity_info()
|
| 31 |
+
logger = logging.get_logger(__name__)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def get_dpt_config(model_name):
|
| 35 |
+
if "small" in model_name:
|
| 36 |
+
out_indices = [3, 6, 9, 12] if "v2" in model_name else [9, 10, 11, 12]
|
| 37 |
+
backbone_config = Dinov2Config.from_pretrained(
|
| 38 |
+
"facebook/dinov2-small", out_indices=out_indices, apply_layernorm=True, reshape_hidden_states=False
|
| 39 |
+
)
|
| 40 |
+
fusion_hidden_size = 64
|
| 41 |
+
neck_hidden_sizes = [48, 96, 192, 384]
|
| 42 |
+
elif "base" in model_name:
|
| 43 |
+
out_indices = [3, 6, 9, 12] if "v2" in model_name else [9, 10, 11, 12]
|
| 44 |
+
backbone_config = Dinov2Config.from_pretrained(
|
| 45 |
+
"facebook/dinov2-base", out_indices=out_indices, apply_layernorm=True, reshape_hidden_states=False
|
| 46 |
+
)
|
| 47 |
+
fusion_hidden_size = 128
|
| 48 |
+
neck_hidden_sizes = [96, 192, 384, 768]
|
| 49 |
+
elif "large" in model_name:
|
| 50 |
+
out_indices = [5, 12, 18, 24] if "v2" in model_name else [21, 22, 23, 24]
|
| 51 |
+
backbone_config = Dinov2Config.from_pretrained(
|
| 52 |
+
"facebook/dinov2-large", out_indices=out_indices, apply_layernorm=True, reshape_hidden_states=False
|
| 53 |
+
)
|
| 54 |
+
fusion_hidden_size = 256
|
| 55 |
+
neck_hidden_sizes = [256, 512, 1024, 1024]
|
| 56 |
+
else:
|
| 57 |
+
raise NotImplementedError(f"Model not supported: {model_name}")
|
| 58 |
+
|
| 59 |
+
if "metric" in model_name:
|
| 60 |
+
depth_estimation_type = "metric"
|
| 61 |
+
max_depth = 20 if "indoor" in model_name else 80
|
| 62 |
+
else:
|
| 63 |
+
depth_estimation_type = "relative"
|
| 64 |
+
max_depth = None
|
| 65 |
+
|
| 66 |
+
config = DepthAnythingConfig(
|
| 67 |
+
reassemble_hidden_size=backbone_config.hidden_size,
|
| 68 |
+
patch_size=backbone_config.patch_size,
|
| 69 |
+
backbone_config=backbone_config,
|
| 70 |
+
fusion_hidden_size=fusion_hidden_size,
|
| 71 |
+
neck_hidden_sizes=neck_hidden_sizes,
|
| 72 |
+
depth_estimation_type=depth_estimation_type,
|
| 73 |
+
max_depth=max_depth,
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
return config
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def create_rename_keys(config):
|
| 80 |
+
rename_keys = []
|
| 81 |
+
|
| 82 |
+
# fmt: off
|
| 83 |
+
# stem
|
| 84 |
+
rename_keys.append(("pretrained.cls_token", "backbone.embeddings.cls_token"))
|
| 85 |
+
rename_keys.append(("pretrained.mask_token", "backbone.embeddings.mask_token"))
|
| 86 |
+
rename_keys.append(("pretrained.pos_embed", "backbone.embeddings.position_embeddings"))
|
| 87 |
+
rename_keys.append(("pretrained.patch_embed.proj.weight", "backbone.embeddings.patch_embeddings.projection.weight"))
|
| 88 |
+
rename_keys.append(("pretrained.patch_embed.proj.bias", "backbone.embeddings.patch_embeddings.projection.bias"))
|
| 89 |
+
|
| 90 |
+
# Transfomer encoder
|
| 91 |
+
for i in range(config.backbone_config.num_hidden_layers):
|
| 92 |
+
rename_keys.append((f"pretrained.blocks.{i}.ls1.gamma", f"backbone.encoder.layer.{i}.layer_scale1.lambda1"))
|
| 93 |
+
rename_keys.append((f"pretrained.blocks.{i}.ls2.gamma", f"backbone.encoder.layer.{i}.layer_scale2.lambda1"))
|
| 94 |
+
rename_keys.append((f"pretrained.blocks.{i}.norm1.weight", f"backbone.encoder.layer.{i}.norm1.weight"))
|
| 95 |
+
rename_keys.append((f"pretrained.blocks.{i}.norm1.bias", f"backbone.encoder.layer.{i}.norm1.bias"))
|
| 96 |
+
rename_keys.append((f"pretrained.blocks.{i}.norm2.weight", f"backbone.encoder.layer.{i}.norm2.weight"))
|
| 97 |
+
rename_keys.append((f"pretrained.blocks.{i}.norm2.bias", f"backbone.encoder.layer.{i}.norm2.bias"))
|
| 98 |
+
rename_keys.append((f"pretrained.blocks.{i}.mlp.fc1.weight", f"backbone.encoder.layer.{i}.mlp.fc1.weight"))
|
| 99 |
+
rename_keys.append((f"pretrained.blocks.{i}.mlp.fc1.bias", f"backbone.encoder.layer.{i}.mlp.fc1.bias"))
|
| 100 |
+
rename_keys.append((f"pretrained.blocks.{i}.mlp.fc2.weight", f"backbone.encoder.layer.{i}.mlp.fc2.weight"))
|
| 101 |
+
rename_keys.append((f"pretrained.blocks.{i}.mlp.fc2.bias", f"backbone.encoder.layer.{i}.mlp.fc2.bias"))
|
| 102 |
+
rename_keys.append((f"pretrained.blocks.{i}.attn.proj.weight", f"backbone.encoder.layer.{i}.attention.output.dense.weight"))
|
| 103 |
+
rename_keys.append((f"pretrained.blocks.{i}.attn.proj.bias", f"backbone.encoder.layer.{i}.attention.output.dense.bias"))
|
| 104 |
+
|
| 105 |
+
# Head
|
| 106 |
+
rename_keys.append(("pretrained.norm.weight", "backbone.layernorm.weight"))
|
| 107 |
+
rename_keys.append(("pretrained.norm.bias", "backbone.layernorm.bias"))
|
| 108 |
+
|
| 109 |
+
# activation postprocessing (readout projections + resize blocks)
|
| 110 |
+
# Depth Anything does not use CLS token => readout_projects not required
|
| 111 |
+
|
| 112 |
+
for i in range(4):
|
| 113 |
+
rename_keys.append((f"depth_head.projects.{i}.weight", f"neck.reassemble_stage.layers.{i}.projection.weight"))
|
| 114 |
+
rename_keys.append((f"depth_head.projects.{i}.bias", f"neck.reassemble_stage.layers.{i}.projection.bias"))
|
| 115 |
+
|
| 116 |
+
if i != 2:
|
| 117 |
+
rename_keys.append((f"depth_head.resize_layers.{i}.weight", f"neck.reassemble_stage.layers.{i}.resize.weight"))
|
| 118 |
+
rename_keys.append((f"depth_head.resize_layers.{i}.bias", f"neck.reassemble_stage.layers.{i}.resize.bias"))
|
| 119 |
+
|
| 120 |
+
# refinenet (tricky here)
|
| 121 |
+
mapping = {1:3, 2:2, 3:1, 4:0}
|
| 122 |
+
|
| 123 |
+
for i in range(1, 5):
|
| 124 |
+
j = mapping[i]
|
| 125 |
+
rename_keys.append((f"depth_head.scratch.refinenet{i}.out_conv.weight", f"neck.fusion_stage.layers.{j}.projection.weight"))
|
| 126 |
+
rename_keys.append((f"depth_head.scratch.refinenet{i}.out_conv.bias", f"neck.fusion_stage.layers.{j}.projection.bias"))
|
| 127 |
+
rename_keys.append((f"depth_head.scratch.refinenet{i}.resConfUnit1.conv1.weight", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution1.weight"))
|
| 128 |
+
rename_keys.append((f"depth_head.scratch.refinenet{i}.resConfUnit1.conv1.bias", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution1.bias"))
|
| 129 |
+
rename_keys.append((f"depth_head.scratch.refinenet{i}.resConfUnit1.conv2.weight", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution2.weight"))
|
| 130 |
+
rename_keys.append((f"depth_head.scratch.refinenet{i}.resConfUnit1.conv2.bias", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution2.bias"))
|
| 131 |
+
rename_keys.append((f"depth_head.scratch.refinenet{i}.resConfUnit2.conv1.weight", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution1.weight"))
|
| 132 |
+
rename_keys.append((f"depth_head.scratch.refinenet{i}.resConfUnit2.conv1.bias", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution1.bias"))
|
| 133 |
+
rename_keys.append((f"depth_head.scratch.refinenet{i}.resConfUnit2.conv2.weight", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution2.weight"))
|
| 134 |
+
rename_keys.append((f"depth_head.scratch.refinenet{i}.resConfUnit2.conv2.bias", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution2.bias"))
|
| 135 |
+
|
| 136 |
+
# scratch convolutions
|
| 137 |
+
for i in range(4):
|
| 138 |
+
rename_keys.append((f"depth_head.scratch.layer{i+1}_rn.weight", f"neck.convs.{i}.weight"))
|
| 139 |
+
|
| 140 |
+
# head
|
| 141 |
+
rename_keys.append(("depth_head.scratch.output_conv1.weight", "head.conv1.weight"))
|
| 142 |
+
rename_keys.append(("depth_head.scratch.output_conv1.bias", "head.conv1.bias"))
|
| 143 |
+
rename_keys.append(("depth_head.scratch.output_conv2.0.weight", "head.conv2.weight"))
|
| 144 |
+
rename_keys.append(("depth_head.scratch.output_conv2.0.bias", "head.conv2.bias"))
|
| 145 |
+
rename_keys.append(("depth_head.scratch.output_conv2.2.weight", "head.conv3.weight"))
|
| 146 |
+
rename_keys.append(("depth_head.scratch.output_conv2.2.bias", "head.conv3.bias"))
|
| 147 |
+
|
| 148 |
+
return rename_keys
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# we split up the matrix of each encoder layer into queries, keys and values
|
| 152 |
+
def read_in_q_k_v(state_dict, config):
|
| 153 |
+
hidden_size = config.backbone_config.hidden_size
|
| 154 |
+
for i in range(config.backbone_config.num_hidden_layers):
|
| 155 |
+
# read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias)
|
| 156 |
+
in_proj_weight = state_dict.pop(f"pretrained.blocks.{i}.attn.qkv.weight")
|
| 157 |
+
in_proj_bias = state_dict.pop(f"pretrained.blocks.{i}.attn.qkv.bias")
|
| 158 |
+
# next, add query, keys and values (in that order) to the state dict
|
| 159 |
+
state_dict[f"backbone.encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[:hidden_size, :]
|
| 160 |
+
state_dict[f"backbone.encoder.layer.{i}.attention.attention.query.bias"] = in_proj_bias[:hidden_size]
|
| 161 |
+
state_dict[f"backbone.encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[
|
| 162 |
+
hidden_size : hidden_size * 2, :
|
| 163 |
+
]
|
| 164 |
+
state_dict[f"backbone.encoder.layer.{i}.attention.attention.key.bias"] = in_proj_bias[
|
| 165 |
+
hidden_size : hidden_size * 2
|
| 166 |
+
]
|
| 167 |
+
state_dict[f"backbone.encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[-hidden_size:, :]
|
| 168 |
+
state_dict[f"backbone.encoder.layer.{i}.attention.attention.value.bias"] = in_proj_bias[-hidden_size:]
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def rename_key(dct, old, new):
|
| 172 |
+
val = dct.pop(old)
|
| 173 |
+
dct[new] = val
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
# We will verify our results on an image of cute cats
|
| 177 |
+
def prepare_img():
|
| 178 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 179 |
+
im = Image.open(requests.get(url, stream=True).raw)
|
| 180 |
+
return im
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
name_to_checkpoint = {
|
| 184 |
+
"depth-anything-small": "pytorch_model.bin",
|
| 185 |
+
"depth-anything-base": "pytorch_model.bin",
|
| 186 |
+
"depth-anything-large": "pytorch_model.bin",
|
| 187 |
+
"depth-anything-v2-small": "depth_anything_v2_vits.pth",
|
| 188 |
+
"depth-anything-v2-base": "depth_anything_v2_vitb.pth",
|
| 189 |
+
"depth-anything-v2-large": "depth_anything_v2_vitl.pth",
|
| 190 |
+
"depth-anything-v2-metric-indoor-small": "depth_anything_v2_metric_hypersim_vits.pth",
|
| 191 |
+
"depth-anything-v2-metric-indoor-base": "depth_anything_v2_metric_hypersim_vitb.pth",
|
| 192 |
+
"depth-anything-v2-metric-indoor-large": "depth_anything_v2_metric_hypersim_vitl.pth",
|
| 193 |
+
"depth-anything-v2-metric-outdoor-small": "depth_anything_v2_metric_vkitti_vits.pth",
|
| 194 |
+
"depth-anything-v2-metric-outdoor-base": "depth_anything_v2_metric_vkitti_vitb.pth",
|
| 195 |
+
"depth-anything-v2-metric-outdoor-large": "depth_anything_v2_metric_vkitti_vitl.pth",
|
| 196 |
+
# v2-giant pending
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
@torch.no_grad()
|
| 201 |
+
def convert_dpt_checkpoint(model_name, pytorch_dump_folder_path, push_to_hub, verify_logits):
|
| 202 |
+
"""
|
| 203 |
+
Copy/paste/tweak model's weights to our DPT structure.
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
# define DPT configuration
|
| 207 |
+
config = get_dpt_config(model_name)
|
| 208 |
+
|
| 209 |
+
model_name_to_repo = {
|
| 210 |
+
"depth-anything-small": "LiheYoung/depth_anything_vits14",
|
| 211 |
+
"depth-anything-base": "LiheYoung/depth_anything_vitb14",
|
| 212 |
+
"depth-anything-large": "LiheYoung/depth_anything_vitl14",
|
| 213 |
+
"depth-anything-v2-small": "depth-anything/Depth-Anything-V2-Small",
|
| 214 |
+
"depth-anything-v2-base": "depth-anything/Depth-Anything-V2-Base",
|
| 215 |
+
"depth-anything-v2-large": "depth-anything/Depth-Anything-V2-Large",
|
| 216 |
+
"depth-anything-v2-metric-indoor-small": "depth-anything/Depth-Anything-V2-Metric-Hypersim-Small",
|
| 217 |
+
"depth-anything-v2-metric-indoor-base": "depth-anything/Depth-Anything-V2-Metric-Hypersim-Base",
|
| 218 |
+
"depth-anything-v2-metric-indoor-large": "depth-anything/Depth-Anything-V2-Metric-Hypersim-Large",
|
| 219 |
+
"depth-anything-v2-metric-outdoor-small": "depth-anything/Depth-Anything-V2-Metric-VKITTI-Small",
|
| 220 |
+
"depth-anything-v2-metric-outdoor-base": "depth-anything/Depth-Anything-V2-Metric-VKITTI-Base",
|
| 221 |
+
"depth-anything-v2-metric-outdoor-large": "depth-anything/Depth-Anything-V2-Metric-VKITTI-Large",
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
# load original state_dict
|
| 225 |
+
repo_id = model_name_to_repo[model_name]
|
| 226 |
+
filename = name_to_checkpoint[model_name]
|
| 227 |
+
filepath = hf_hub_download(
|
| 228 |
+
repo_id=repo_id,
|
| 229 |
+
filename=f"{filename}",
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
state_dict = torch.load(filepath, map_location="cpu")
|
| 233 |
+
# rename keys
|
| 234 |
+
rename_keys = create_rename_keys(config)
|
| 235 |
+
for src, dest in rename_keys:
|
| 236 |
+
rename_key(state_dict, src, dest)
|
| 237 |
+
# read in qkv matrices
|
| 238 |
+
read_in_q_k_v(state_dict, config)
|
| 239 |
+
|
| 240 |
+
# load HuggingFace model
|
| 241 |
+
model = DepthAnythingForDepthEstimation(config)
|
| 242 |
+
model.load_state_dict(state_dict)
|
| 243 |
+
model.eval()
|
| 244 |
+
|
| 245 |
+
processor = DPTImageProcessor(
|
| 246 |
+
do_resize=True,
|
| 247 |
+
size={"height": 518, "width": 518},
|
| 248 |
+
ensure_multiple_of=14,
|
| 249 |
+
keep_aspect_ratio=True,
|
| 250 |
+
do_rescale=True,
|
| 251 |
+
do_normalize=True,
|
| 252 |
+
image_mean=[0.485, 0.456, 0.406],
|
| 253 |
+
image_std=[0.229, 0.224, 0.225],
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 257 |
+
image = Image.open(requests.get(url, stream=True).raw)
|
| 258 |
+
|
| 259 |
+
pixel_values = processor(image, return_tensors="pt").pixel_values
|
| 260 |
+
|
| 261 |
+
# Verify forward pass
|
| 262 |
+
with torch.no_grad():
|
| 263 |
+
outputs = model(pixel_values)
|
| 264 |
+
predicted_depth = outputs.predicted_depth
|
| 265 |
+
|
| 266 |
+
print("Shape of predicted depth:", predicted_depth.shape)
|
| 267 |
+
print("First values:", predicted_depth[0, :3, :3])
|
| 268 |
+
|
| 269 |
+
# assert logits
|
| 270 |
+
if verify_logits:
|
| 271 |
+
expected_shape = torch.Size([1, 518, 686])
|
| 272 |
+
if model_name == "depth-anything-small":
|
| 273 |
+
expected_slice = torch.tensor(
|
| 274 |
+
[[8.8204, 8.6468, 8.6195], [8.3313, 8.6027, 8.7526], [8.6526, 8.6866, 8.7453]],
|
| 275 |
+
)
|
| 276 |
+
elif model_name == "depth-anything-base":
|
| 277 |
+
expected_slice = torch.tensor(
|
| 278 |
+
[[26.3997, 26.3004, 26.3928], [26.2260, 26.2092, 26.3427], [26.0719, 26.0483, 26.1254]],
|
| 279 |
+
)
|
| 280 |
+
elif model_name == "depth-anything-large":
|
| 281 |
+
expected_slice = torch.tensor(
|
| 282 |
+
[[87.9968, 87.7493, 88.2704], [87.1927, 87.6611, 87.3640], [86.7789, 86.9469, 86.7991]]
|
| 283 |
+
)
|
| 284 |
+
elif model_name == "depth-anything-v2-small":
|
| 285 |
+
expected_slice = torch.tensor(
|
| 286 |
+
[[2.6751, 2.6211, 2.6571], [2.5820, 2.6138, 2.6271], [2.6160, 2.6141, 2.6306]]
|
| 287 |
+
)
|
| 288 |
+
elif model_name == "depth-anything-v2-base":
|
| 289 |
+
expected_slice = torch.tensor(
|
| 290 |
+
[[4.3576, 4.3723, 4.3908], [4.3231, 4.3146, 4.3611], [4.3016, 4.3170, 4.3121]]
|
| 291 |
+
)
|
| 292 |
+
elif model_name == "depth-anything-v2-large":
|
| 293 |
+
expected_slice = torch.tensor(
|
| 294 |
+
[[162.2751, 161.8504, 162.8788], [160.3138, 160.8050, 161.9835], [159.3812, 159.9884, 160.0768]]
|
| 295 |
+
)
|
| 296 |
+
elif model_name == "depth-anything-v2-metric-indoor-small":
|
| 297 |
+
expected_slice = torch.tensor(
|
| 298 |
+
[[1.3349, 1.2946, 1.2801], [1.2793, 1.2337, 1.2899], [1.2629, 1.2218, 1.2476]]
|
| 299 |
+
)
|
| 300 |
+
elif model_name == "depth-anything-v2-metric-indoor-base":
|
| 301 |
+
expected_slice = torch.tensor(
|
| 302 |
+
[[1.4601, 1.3824, 1.4904], [1.5031, 1.4349, 1.4274], [1.4570, 1.4578, 1.4200]]
|
| 303 |
+
)
|
| 304 |
+
elif model_name == "depth-anything-v2-metric-indoor-large":
|
| 305 |
+
expected_slice = torch.tensor(
|
| 306 |
+
[[1.5040, 1.5019, 1.5218], [1.5087, 1.5195, 1.5149], [1.5437, 1.5128, 1.5252]]
|
| 307 |
+
)
|
| 308 |
+
elif model_name == "depth-anything-v2-metric-outdoor-small":
|
| 309 |
+
expected_slice = torch.tensor(
|
| 310 |
+
[[9.5804, 8.0339, 7.7386], [7.9890, 7.2464, 7.7149], [7.7021, 7.2330, 7.3304]]
|
| 311 |
+
)
|
| 312 |
+
elif model_name == "depth-anything-v2-metric-outdoor-base":
|
| 313 |
+
expected_slice = torch.tensor(
|
| 314 |
+
[[10.2916, 9.0933, 8.8622], [9.1964, 9.3393, 9.0644], [8.9618, 9.4201, 9.2262]]
|
| 315 |
+
)
|
| 316 |
+
elif model_name == "depth-anything-v2-metric-outdoor-large":
|
| 317 |
+
expected_slice = torch.tensor(
|
| 318 |
+
[[14.0137, 13.3627, 13.1080], [13.2522, 13.3943, 13.3705], [13.0581, 13.4505, 13.3925]]
|
| 319 |
+
)
|
| 320 |
+
else:
|
| 321 |
+
raise ValueError("Not supported")
|
| 322 |
+
|
| 323 |
+
assert predicted_depth.shape == torch.Size(expected_shape)
|
| 324 |
+
assert torch.allclose(predicted_depth[0, :3, :3], expected_slice, atol=1e-4)
|
| 325 |
+
print("Looks ok!")
|
| 326 |
+
|
| 327 |
+
if pytorch_dump_folder_path is not None:
|
| 328 |
+
Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
|
| 329 |
+
print(f"Saving model and processor to {pytorch_dump_folder_path}")
|
| 330 |
+
model.save_pretrained(pytorch_dump_folder_path)
|
| 331 |
+
processor.save_pretrained(pytorch_dump_folder_path)
|
| 332 |
+
|
| 333 |
+
if push_to_hub:
|
| 334 |
+
print("Pushing model and processor to hub...")
|
| 335 |
+
model.push_to_hub(repo_id=f"{model_name.title()}-hf")
|
| 336 |
+
processor.push_to_hub(repo_id=f"{model_name.title()}-hf")
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
if __name__ == "__main__":
|
| 340 |
+
parser = argparse.ArgumentParser()
|
| 341 |
+
# Required parameters
|
| 342 |
+
parser.add_argument(
|
| 343 |
+
"--model_name",
|
| 344 |
+
default="depth-anything-small",
|
| 345 |
+
type=str,
|
| 346 |
+
choices=name_to_checkpoint.keys(),
|
| 347 |
+
help="Name of the model you'd like to convert.",
|
| 348 |
+
)
|
| 349 |
+
parser.add_argument(
|
| 350 |
+
"--pytorch_dump_folder_path",
|
| 351 |
+
default=None,
|
| 352 |
+
type=str,
|
| 353 |
+
help="Path to the output PyTorch model directory.",
|
| 354 |
+
)
|
| 355 |
+
parser.add_argument(
|
| 356 |
+
"--push_to_hub",
|
| 357 |
+
action="store_true",
|
| 358 |
+
help="Whether to push the model to the hub after conversion.",
|
| 359 |
+
)
|
| 360 |
+
parser.add_argument(
|
| 361 |
+
"--verify_logits",
|
| 362 |
+
action="store_false",
|
| 363 |
+
required=False,
|
| 364 |
+
help="Whether to verify the logits after conversion.",
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
args = parser.parse_args()
|
| 368 |
+
convert_dpt_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.verify_logits)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_anything/modeling_depth_anything.py
ADDED
|
@@ -0,0 +1,468 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch Depth Anything model."""
|
| 16 |
+
|
| 17 |
+
from typing import List, Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.utils.checkpoint
|
| 21 |
+
from torch import nn
|
| 22 |
+
|
| 23 |
+
from ...file_utils import (
|
| 24 |
+
add_start_docstrings,
|
| 25 |
+
add_start_docstrings_to_model_forward,
|
| 26 |
+
replace_return_docstrings,
|
| 27 |
+
)
|
| 28 |
+
from ...modeling_outputs import DepthEstimatorOutput
|
| 29 |
+
from ...modeling_utils import PreTrainedModel
|
| 30 |
+
from ...utils import logging
|
| 31 |
+
from ...utils.backbone_utils import load_backbone
|
| 32 |
+
from .configuration_depth_anything import DepthAnythingConfig
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
logger = logging.get_logger(__name__)
|
| 36 |
+
|
| 37 |
+
# General docstring
|
| 38 |
+
_CONFIG_FOR_DOC = "DepthAnythingConfig"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
DEPTH_ANYTHING_START_DOCSTRING = r"""
|
| 42 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 43 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 44 |
+
behavior.
|
| 45 |
+
|
| 46 |
+
Parameters:
|
| 47 |
+
config ([`DepthAnythingConfig`]): Model configuration class with all the parameters of the model.
|
| 48 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 49 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
DEPTH_ANYTHING_INPUTS_DOCSTRING = r"""
|
| 53 |
+
Args:
|
| 54 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 55 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`DPTImageProcessor.__call__`]
|
| 56 |
+
for details.
|
| 57 |
+
output_attentions (`bool`, *optional*):
|
| 58 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 59 |
+
tensors for more detail.
|
| 60 |
+
output_hidden_states (`bool`, *optional*):
|
| 61 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 62 |
+
more detail.
|
| 63 |
+
return_dict (`bool`, *optional*):
|
| 64 |
+
Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class DepthAnythingReassembleLayer(nn.Module):
|
| 69 |
+
def __init__(self, config, channels, factor):
|
| 70 |
+
super().__init__()
|
| 71 |
+
self.projection = nn.Conv2d(in_channels=config.reassemble_hidden_size, out_channels=channels, kernel_size=1)
|
| 72 |
+
|
| 73 |
+
# up/down sampling depending on factor
|
| 74 |
+
if factor > 1:
|
| 75 |
+
self.resize = nn.ConvTranspose2d(channels, channels, kernel_size=factor, stride=factor, padding=0)
|
| 76 |
+
elif factor == 1:
|
| 77 |
+
self.resize = nn.Identity()
|
| 78 |
+
elif factor < 1:
|
| 79 |
+
# so should downsample
|
| 80 |
+
self.resize = nn.Conv2d(channels, channels, kernel_size=3, stride=int(1 / factor), padding=1)
|
| 81 |
+
|
| 82 |
+
# Copied from transformers.models.dpt.modeling_dpt.DPTReassembleLayer.forward
|
| 83 |
+
def forward(self, hidden_state):
|
| 84 |
+
hidden_state = self.projection(hidden_state)
|
| 85 |
+
hidden_state = self.resize(hidden_state)
|
| 86 |
+
|
| 87 |
+
return hidden_state
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class DepthAnythingReassembleStage(nn.Module):
|
| 91 |
+
"""
|
| 92 |
+
This class reassembles the hidden states of the backbone into image-like feature representations at various
|
| 93 |
+
resolutions.
|
| 94 |
+
|
| 95 |
+
This happens in 3 stages:
|
| 96 |
+
1. Take the patch embeddings and reshape them to image-like feature representations.
|
| 97 |
+
2. Project the channel dimension of the hidden states according to `config.neck_hidden_sizes`.
|
| 98 |
+
3. Resizing the spatial dimensions (height, width).
|
| 99 |
+
|
| 100 |
+
Args:
|
| 101 |
+
config (`[DepthAnythingConfig]`):
|
| 102 |
+
Model configuration class defining the model architecture.
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
def __init__(self, config):
|
| 106 |
+
super().__init__()
|
| 107 |
+
|
| 108 |
+
self.config = config
|
| 109 |
+
self.layers = nn.ModuleList()
|
| 110 |
+
for channels, factor in zip(config.neck_hidden_sizes, config.reassemble_factors):
|
| 111 |
+
self.layers.append(DepthAnythingReassembleLayer(config, channels=channels, factor=factor))
|
| 112 |
+
|
| 113 |
+
def forward(self, hidden_states: List[torch.Tensor], patch_height=None, patch_width=None) -> List[torch.Tensor]:
|
| 114 |
+
"""
|
| 115 |
+
Args:
|
| 116 |
+
hidden_states (`List[torch.FloatTensor]`, each of shape `(batch_size, sequence_length + 1, hidden_size)`):
|
| 117 |
+
List of hidden states from the backbone.
|
| 118 |
+
"""
|
| 119 |
+
out = []
|
| 120 |
+
|
| 121 |
+
for i, hidden_state in enumerate(hidden_states):
|
| 122 |
+
# reshape to (batch_size, num_channels, height, width)
|
| 123 |
+
hidden_state = hidden_state[:, 1:]
|
| 124 |
+
batch_size, _, num_channels = hidden_state.shape
|
| 125 |
+
hidden_state = hidden_state.reshape(batch_size, patch_height, patch_width, num_channels)
|
| 126 |
+
hidden_state = hidden_state.permute(0, 3, 1, 2).contiguous()
|
| 127 |
+
hidden_state = self.layers[i](hidden_state)
|
| 128 |
+
out.append(hidden_state)
|
| 129 |
+
|
| 130 |
+
return out
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class DepthAnythingPreActResidualLayer(nn.Module):
|
| 134 |
+
"""
|
| 135 |
+
ResidualConvUnit, pre-activate residual unit.
|
| 136 |
+
|
| 137 |
+
Args:
|
| 138 |
+
config (`[DepthAnythingConfig]`):
|
| 139 |
+
Model configuration class defining the model architecture.
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
def __init__(self, config):
|
| 143 |
+
super().__init__()
|
| 144 |
+
|
| 145 |
+
self.activation1 = nn.ReLU()
|
| 146 |
+
self.convolution1 = nn.Conv2d(
|
| 147 |
+
config.fusion_hidden_size,
|
| 148 |
+
config.fusion_hidden_size,
|
| 149 |
+
kernel_size=3,
|
| 150 |
+
stride=1,
|
| 151 |
+
padding=1,
|
| 152 |
+
bias=True,
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
self.activation2 = nn.ReLU()
|
| 156 |
+
self.convolution2 = nn.Conv2d(
|
| 157 |
+
config.fusion_hidden_size,
|
| 158 |
+
config.fusion_hidden_size,
|
| 159 |
+
kernel_size=3,
|
| 160 |
+
stride=1,
|
| 161 |
+
padding=1,
|
| 162 |
+
bias=True,
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 166 |
+
residual = hidden_state
|
| 167 |
+
hidden_state = self.activation1(hidden_state)
|
| 168 |
+
hidden_state = self.convolution1(hidden_state)
|
| 169 |
+
hidden_state = self.activation2(hidden_state)
|
| 170 |
+
hidden_state = self.convolution2(hidden_state)
|
| 171 |
+
|
| 172 |
+
return hidden_state + residual
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
class DepthAnythingFeatureFusionLayer(nn.Module):
|
| 176 |
+
"""Feature fusion layer, merges feature maps from different stages.
|
| 177 |
+
|
| 178 |
+
Args:
|
| 179 |
+
config (`[DepthAnythingConfig]`):
|
| 180 |
+
Model configuration class defining the model architecture.
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
def __init__(self, config):
|
| 184 |
+
super().__init__()
|
| 185 |
+
|
| 186 |
+
self.projection = nn.Conv2d(config.fusion_hidden_size, config.fusion_hidden_size, kernel_size=1, bias=True)
|
| 187 |
+
|
| 188 |
+
self.residual_layer1 = DepthAnythingPreActResidualLayer(config)
|
| 189 |
+
self.residual_layer2 = DepthAnythingPreActResidualLayer(config)
|
| 190 |
+
|
| 191 |
+
def forward(self, hidden_state, residual=None, size=None):
|
| 192 |
+
if residual is not None:
|
| 193 |
+
if hidden_state.shape != residual.shape:
|
| 194 |
+
residual = nn.functional.interpolate(
|
| 195 |
+
residual, size=(hidden_state.shape[2], hidden_state.shape[3]), mode="bilinear", align_corners=False
|
| 196 |
+
)
|
| 197 |
+
hidden_state = hidden_state + self.residual_layer1(residual)
|
| 198 |
+
|
| 199 |
+
hidden_state = self.residual_layer2(hidden_state)
|
| 200 |
+
|
| 201 |
+
modifier = {"scale_factor": 2} if size is None else {"size": size}
|
| 202 |
+
|
| 203 |
+
hidden_state = nn.functional.interpolate(
|
| 204 |
+
hidden_state,
|
| 205 |
+
**modifier,
|
| 206 |
+
mode="bilinear",
|
| 207 |
+
align_corners=True,
|
| 208 |
+
)
|
| 209 |
+
hidden_state = self.projection(hidden_state)
|
| 210 |
+
|
| 211 |
+
return hidden_state
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
class DepthAnythingFeatureFusionStage(nn.Module):
|
| 215 |
+
# Copied from transformers.models.dpt.modeling_dpt.DPTFeatureFusionStage.__init__ with DPT->DepthAnything
|
| 216 |
+
def __init__(self, config):
|
| 217 |
+
super().__init__()
|
| 218 |
+
self.layers = nn.ModuleList()
|
| 219 |
+
for _ in range(len(config.neck_hidden_sizes)):
|
| 220 |
+
self.layers.append(DepthAnythingFeatureFusionLayer(config))
|
| 221 |
+
|
| 222 |
+
def forward(self, hidden_states, size=None):
|
| 223 |
+
# reversing the hidden_states, we start from the last
|
| 224 |
+
hidden_states = hidden_states[::-1]
|
| 225 |
+
|
| 226 |
+
fused_hidden_states = []
|
| 227 |
+
fused_hidden_state = None
|
| 228 |
+
|
| 229 |
+
for idx, (hidden_state, layer) in enumerate(zip(hidden_states, self.layers)):
|
| 230 |
+
size = hidden_states[idx + 1].shape[2:] if idx != (len(hidden_states) - 1) else None
|
| 231 |
+
|
| 232 |
+
if fused_hidden_state is None:
|
| 233 |
+
# first layer only uses the last hidden_state
|
| 234 |
+
fused_hidden_state = layer(hidden_state, size=size)
|
| 235 |
+
else:
|
| 236 |
+
fused_hidden_state = layer(fused_hidden_state, hidden_state, size=size)
|
| 237 |
+
|
| 238 |
+
fused_hidden_states.append(fused_hidden_state)
|
| 239 |
+
|
| 240 |
+
return fused_hidden_states
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
# Copied from transformers.models.dpt.modeling_dpt.DPTPreTrainedModel with DPT->DepthAnything,dpt->depth_anything
|
| 244 |
+
class DepthAnythingPreTrainedModel(PreTrainedModel):
|
| 245 |
+
"""
|
| 246 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 247 |
+
models.
|
| 248 |
+
"""
|
| 249 |
+
|
| 250 |
+
config_class = DepthAnythingConfig
|
| 251 |
+
base_model_prefix = "depth_anything"
|
| 252 |
+
main_input_name = "pixel_values"
|
| 253 |
+
supports_gradient_checkpointing = True
|
| 254 |
+
|
| 255 |
+
def _init_weights(self, module):
|
| 256 |
+
"""Initialize the weights"""
|
| 257 |
+
if isinstance(module, (nn.Linear, nn.Conv2d, nn.ConvTranspose2d)):
|
| 258 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 259 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 260 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 261 |
+
if module.bias is not None:
|
| 262 |
+
module.bias.data.zero_()
|
| 263 |
+
elif isinstance(module, nn.LayerNorm):
|
| 264 |
+
module.bias.data.zero_()
|
| 265 |
+
module.weight.data.fill_(1.0)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
class DepthAnythingNeck(nn.Module):
|
| 269 |
+
"""
|
| 270 |
+
DepthAnythingNeck. A neck is a module that is normally used between the backbone and the head. It takes a list of tensors as
|
| 271 |
+
input and produces another list of tensors as output. For DepthAnything, it includes 2 stages:
|
| 272 |
+
|
| 273 |
+
* DepthAnythingReassembleStage
|
| 274 |
+
* DepthAnythingFeatureFusionStage.
|
| 275 |
+
|
| 276 |
+
Args:
|
| 277 |
+
config (dict): config dict.
|
| 278 |
+
"""
|
| 279 |
+
|
| 280 |
+
def __init__(self, config):
|
| 281 |
+
super().__init__()
|
| 282 |
+
self.config = config
|
| 283 |
+
|
| 284 |
+
self.reassemble_stage = DepthAnythingReassembleStage(config)
|
| 285 |
+
|
| 286 |
+
self.convs = nn.ModuleList()
|
| 287 |
+
for channel in config.neck_hidden_sizes:
|
| 288 |
+
self.convs.append(nn.Conv2d(channel, config.fusion_hidden_size, kernel_size=3, padding=1, bias=False))
|
| 289 |
+
|
| 290 |
+
# fusion
|
| 291 |
+
self.fusion_stage = DepthAnythingFeatureFusionStage(config)
|
| 292 |
+
|
| 293 |
+
def forward(self, hidden_states: List[torch.Tensor], patch_height=None, patch_width=None) -> List[torch.Tensor]:
|
| 294 |
+
"""
|
| 295 |
+
Args:
|
| 296 |
+
hidden_states (`List[torch.FloatTensor]`, each of shape `(batch_size, sequence_length, hidden_size)` or `(batch_size, hidden_size, height, width)`):
|
| 297 |
+
List of hidden states from the backbone.
|
| 298 |
+
"""
|
| 299 |
+
if not isinstance(hidden_states, (tuple, list)):
|
| 300 |
+
raise TypeError("hidden_states should be a tuple or list of tensors")
|
| 301 |
+
|
| 302 |
+
if len(hidden_states) != len(self.config.neck_hidden_sizes):
|
| 303 |
+
raise ValueError("The number of hidden states should be equal to the number of neck hidden sizes.")
|
| 304 |
+
|
| 305 |
+
# postprocess hidden states
|
| 306 |
+
hidden_states = self.reassemble_stage(hidden_states, patch_height, patch_width)
|
| 307 |
+
|
| 308 |
+
features = [self.convs[i](feature) for i, feature in enumerate(hidden_states)]
|
| 309 |
+
|
| 310 |
+
# fusion blocks
|
| 311 |
+
output = self.fusion_stage(features)
|
| 312 |
+
|
| 313 |
+
return output
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class DepthAnythingDepthEstimationHead(nn.Module):
|
| 317 |
+
"""
|
| 318 |
+
Output head consisting of 3 convolutional layers. It progressively halves the feature dimension and upsamples
|
| 319 |
+
the predictions to the input resolution after the first convolutional layer (details can be found in the DPT paper's
|
| 320 |
+
supplementary material). The final activation function is either ReLU or Sigmoid, depending on the depth estimation
|
| 321 |
+
type (relative or metric). For metric depth estimation, the output is scaled by the maximum depth used during pretraining.
|
| 322 |
+
"""
|
| 323 |
+
|
| 324 |
+
def __init__(self, config):
|
| 325 |
+
super().__init__()
|
| 326 |
+
|
| 327 |
+
self.head_in_index = config.head_in_index
|
| 328 |
+
self.patch_size = config.patch_size
|
| 329 |
+
|
| 330 |
+
features = config.fusion_hidden_size
|
| 331 |
+
self.conv1 = nn.Conv2d(features, features // 2, kernel_size=3, stride=1, padding=1)
|
| 332 |
+
self.conv2 = nn.Conv2d(features // 2, config.head_hidden_size, kernel_size=3, stride=1, padding=1)
|
| 333 |
+
self.activation1 = nn.ReLU()
|
| 334 |
+
self.conv3 = nn.Conv2d(config.head_hidden_size, 1, kernel_size=1, stride=1, padding=0)
|
| 335 |
+
if config.depth_estimation_type == "relative":
|
| 336 |
+
self.activation2 = nn.ReLU()
|
| 337 |
+
elif config.depth_estimation_type == "metric":
|
| 338 |
+
self.activation2 = nn.Sigmoid()
|
| 339 |
+
else:
|
| 340 |
+
raise ValueError(f"Unknown depth estimation type: {config.depth_estimation_type}")
|
| 341 |
+
self.max_depth = config.max_depth
|
| 342 |
+
|
| 343 |
+
def forward(self, hidden_states: List[torch.Tensor], patch_height, patch_width) -> torch.Tensor:
|
| 344 |
+
hidden_states = hidden_states[self.head_in_index]
|
| 345 |
+
|
| 346 |
+
predicted_depth = self.conv1(hidden_states)
|
| 347 |
+
predicted_depth = nn.functional.interpolate(
|
| 348 |
+
predicted_depth,
|
| 349 |
+
(int(patch_height * self.patch_size), int(patch_width * self.patch_size)),
|
| 350 |
+
mode="bilinear",
|
| 351 |
+
align_corners=True,
|
| 352 |
+
)
|
| 353 |
+
predicted_depth = self.conv2(predicted_depth)
|
| 354 |
+
predicted_depth = self.activation1(predicted_depth)
|
| 355 |
+
predicted_depth = self.conv3(predicted_depth)
|
| 356 |
+
predicted_depth = self.activation2(predicted_depth) * self.max_depth
|
| 357 |
+
predicted_depth = predicted_depth.squeeze(dim=1) # shape (batch_size, height, width)
|
| 358 |
+
|
| 359 |
+
return predicted_depth
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
@add_start_docstrings(
|
| 363 |
+
"""
|
| 364 |
+
Depth Anything Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2.
|
| 365 |
+
""",
|
| 366 |
+
DEPTH_ANYTHING_START_DOCSTRING,
|
| 367 |
+
)
|
| 368 |
+
class DepthAnythingForDepthEstimation(DepthAnythingPreTrainedModel):
|
| 369 |
+
_no_split_modules = ["DPTViTEmbeddings"]
|
| 370 |
+
|
| 371 |
+
def __init__(self, config):
|
| 372 |
+
super().__init__(config)
|
| 373 |
+
|
| 374 |
+
self.backbone = load_backbone(config)
|
| 375 |
+
self.neck = DepthAnythingNeck(config)
|
| 376 |
+
self.head = DepthAnythingDepthEstimationHead(config)
|
| 377 |
+
|
| 378 |
+
# Initialize weights and apply final processing
|
| 379 |
+
self.post_init()
|
| 380 |
+
|
| 381 |
+
@add_start_docstrings_to_model_forward(DEPTH_ANYTHING_INPUTS_DOCSTRING)
|
| 382 |
+
@replace_return_docstrings(output_type=DepthEstimatorOutput, config_class=_CONFIG_FOR_DOC)
|
| 383 |
+
def forward(
|
| 384 |
+
self,
|
| 385 |
+
pixel_values: torch.FloatTensor,
|
| 386 |
+
labels: Optional[torch.LongTensor] = None,
|
| 387 |
+
output_attentions: Optional[bool] = None,
|
| 388 |
+
output_hidden_states: Optional[bool] = None,
|
| 389 |
+
return_dict: Optional[bool] = None,
|
| 390 |
+
) -> Union[Tuple[torch.Tensor], DepthEstimatorOutput]:
|
| 391 |
+
r"""
|
| 392 |
+
labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
|
| 393 |
+
Ground truth depth estimation maps for computing the loss.
|
| 394 |
+
|
| 395 |
+
Returns:
|
| 396 |
+
|
| 397 |
+
Examples:
|
| 398 |
+
```python
|
| 399 |
+
>>> from transformers import AutoImageProcessor, AutoModelForDepthEstimation
|
| 400 |
+
>>> import torch
|
| 401 |
+
>>> import numpy as np
|
| 402 |
+
>>> from PIL import Image
|
| 403 |
+
>>> import requests
|
| 404 |
+
|
| 405 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 406 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 407 |
+
|
| 408 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("LiheYoung/depth-anything-small-hf")
|
| 409 |
+
>>> model = AutoModelForDepthEstimation.from_pretrained("LiheYoung/depth-anything-small-hf")
|
| 410 |
+
|
| 411 |
+
>>> # prepare image for the model
|
| 412 |
+
>>> inputs = image_processor(images=image, return_tensors="pt")
|
| 413 |
+
|
| 414 |
+
>>> with torch.no_grad():
|
| 415 |
+
... outputs = model(**inputs)
|
| 416 |
+
|
| 417 |
+
>>> # interpolate to original size
|
| 418 |
+
>>> post_processed_output = image_processor.post_process_depth_estimation(
|
| 419 |
+
... outputs,
|
| 420 |
+
... target_sizes=[(image.height, image.width)],
|
| 421 |
+
... )
|
| 422 |
+
|
| 423 |
+
>>> # visualize the prediction
|
| 424 |
+
>>> predicted_depth = post_processed_output[0]["predicted_depth"]
|
| 425 |
+
>>> depth = predicted_depth * 255 / predicted_depth.max()
|
| 426 |
+
>>> depth = depth.detach().cpu().numpy()
|
| 427 |
+
>>> depth = Image.fromarray(depth.astype("uint8"))
|
| 428 |
+
```"""
|
| 429 |
+
loss = None
|
| 430 |
+
if labels is not None:
|
| 431 |
+
raise NotImplementedError("Training is not implemented yet")
|
| 432 |
+
|
| 433 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 434 |
+
output_hidden_states = (
|
| 435 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 436 |
+
)
|
| 437 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 438 |
+
|
| 439 |
+
outputs = self.backbone.forward_with_filtered_kwargs(
|
| 440 |
+
pixel_values, output_hidden_states=output_hidden_states, output_attentions=output_attentions
|
| 441 |
+
)
|
| 442 |
+
hidden_states = outputs.feature_maps
|
| 443 |
+
|
| 444 |
+
_, _, height, width = pixel_values.shape
|
| 445 |
+
patch_size = self.config.patch_size
|
| 446 |
+
patch_height = height // patch_size
|
| 447 |
+
patch_width = width // patch_size
|
| 448 |
+
|
| 449 |
+
hidden_states = self.neck(hidden_states, patch_height, patch_width)
|
| 450 |
+
|
| 451 |
+
predicted_depth = self.head(hidden_states, patch_height, patch_width)
|
| 452 |
+
|
| 453 |
+
if not return_dict:
|
| 454 |
+
if output_hidden_states:
|
| 455 |
+
output = (predicted_depth,) + outputs[1:]
|
| 456 |
+
else:
|
| 457 |
+
output = (predicted_depth,) + outputs[2:]
|
| 458 |
+
return ((loss,) + output) if loss is not None else output
|
| 459 |
+
|
| 460 |
+
return DepthEstimatorOutput(
|
| 461 |
+
loss=loss,
|
| 462 |
+
predicted_depth=predicted_depth,
|
| 463 |
+
hidden_states=outputs.hidden_states if output_hidden_states else None,
|
| 464 |
+
attentions=outputs.attentions,
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
__all__ = ["DepthAnythingForDepthEstimation", "DepthAnythingPreTrainedModel"]
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_pro/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_depth_pro import *
|
| 22 |
+
from .image_processing_depth_pro import *
|
| 23 |
+
from .image_processing_depth_pro_fast import *
|
| 24 |
+
from .modeling_depth_pro import *
|
| 25 |
+
else:
|
| 26 |
+
import sys
|
| 27 |
+
|
| 28 |
+
_file = globals()["__file__"]
|
| 29 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_pro/configuration_depth_pro.py
ADDED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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""DepthPro model configuration"""
|
| 16 |
+
|
| 17 |
+
from copy import deepcopy
|
| 18 |
+
|
| 19 |
+
from ...configuration_utils import PretrainedConfig
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
from ..auto.configuration_auto import CONFIG_MAPPING, AutoConfig
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class DepthProConfig(PretrainedConfig):
|
| 28 |
+
r"""
|
| 29 |
+
This is the configuration class to store the configuration of a [`DepthProModel`]. It is used to instantiate a
|
| 30 |
+
DepthPro model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 31 |
+
with the defaults will yield a similar configuration to that of the DepthPro
|
| 32 |
+
[apple/DepthPro](https://huggingface.co/apple/DepthPro) architecture.
|
| 33 |
+
|
| 34 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 35 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
fusion_hidden_size (`int`, *optional*, defaults to 256):
|
| 39 |
+
The number of channels before fusion.
|
| 40 |
+
patch_size (`int`, *optional*, defaults to 384):
|
| 41 |
+
The size (resolution) of each patch. This is also the image_size for backbone model.
|
| 42 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 43 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 44 |
+
intermediate_hook_ids (`List[int]`, *optional*, defaults to `[11, 5]`):
|
| 45 |
+
Indices of the intermediate hidden states from the patch encoder to use for fusion.
|
| 46 |
+
intermediate_feature_dims (`List[int]`, *optional*, defaults to `[256, 256]`):
|
| 47 |
+
Hidden state dimensions during upsampling for each intermediate hidden state in `intermediate_hook_ids`.
|
| 48 |
+
scaled_images_ratios (`List[float]`, *optional*, defaults to `[0.25, 0.5, 1]`):
|
| 49 |
+
Ratios of scaled images to be used by the patch encoder.
|
| 50 |
+
scaled_images_overlap_ratios (`List[float]`, *optional*, defaults to `[0.0, 0.5, 0.25]`):
|
| 51 |
+
Overlap ratios between patches for each scaled image in `scaled_images_ratios`.
|
| 52 |
+
scaled_images_feature_dims (`List[int]`, *optional*, defaults to `[1024, 1024, 512]`):
|
| 53 |
+
Hidden state dimensions during upsampling for each scaled image in `scaled_images_ratios`.
|
| 54 |
+
merge_padding_value (`int`, *optional*, defaults to 3):
|
| 55 |
+
When merging smaller patches back to the image size, overlapping sections of this size are removed.
|
| 56 |
+
use_batch_norm_in_fusion_residual (`bool`, *optional*, defaults to `False`):
|
| 57 |
+
Whether to use batch normalization in the pre-activate residual units of the fusion blocks.
|
| 58 |
+
use_bias_in_fusion_residual (`bool`, *optional*, defaults to `True`):
|
| 59 |
+
Whether to use bias in the pre-activate residual units of the fusion blocks.
|
| 60 |
+
use_fov_model (`bool`, *optional*, defaults to `False`):
|
| 61 |
+
Whether to use `DepthProFovModel` to generate the field of view.
|
| 62 |
+
num_fov_head_layers (`int`, *optional*, defaults to 2):
|
| 63 |
+
Number of convolution layers in the head of `DepthProFovModel`.
|
| 64 |
+
image_model_config (`Union[Dict[str, Any], PretrainedConfig]`, *optional*):
|
| 65 |
+
The configuration of the image encoder model, which is loaded using the [`AutoModel`] API.
|
| 66 |
+
By default, Dinov2 model is used as backbone.
|
| 67 |
+
patch_model_config (`Union[Dict[str, Any], PretrainedConfig]`, *optional*):
|
| 68 |
+
The configuration of the patch encoder model, which is loaded using the [`AutoModel`] API.
|
| 69 |
+
By default, Dinov2 model is used as backbone.
|
| 70 |
+
fov_model_config (`Union[Dict[str, Any], PretrainedConfig]`, *optional*):
|
| 71 |
+
The configuration of the fov encoder model, which is loaded using the [`AutoModel`] API.
|
| 72 |
+
By default, Dinov2 model is used as backbone.
|
| 73 |
+
|
| 74 |
+
Example:
|
| 75 |
+
|
| 76 |
+
```python
|
| 77 |
+
>>> from transformers import DepthProConfig, DepthProModel
|
| 78 |
+
|
| 79 |
+
>>> # Initializing a DepthPro apple/DepthPro style configuration
|
| 80 |
+
>>> configuration = DepthProConfig()
|
| 81 |
+
|
| 82 |
+
>>> # Initializing a model (with random weights) from the apple/DepthPro style configuration
|
| 83 |
+
>>> model = DepthProModel(configuration)
|
| 84 |
+
|
| 85 |
+
>>> # Accessing the model configuration
|
| 86 |
+
>>> configuration = model.config
|
| 87 |
+
```"""
|
| 88 |
+
|
| 89 |
+
model_type = "depth_pro"
|
| 90 |
+
sub_configs = {"image_model_config": AutoConfig, "patch_model_config": AutoConfig, "fov_model_config": AutoConfig}
|
| 91 |
+
|
| 92 |
+
def __init__(
|
| 93 |
+
self,
|
| 94 |
+
fusion_hidden_size=256,
|
| 95 |
+
patch_size=384,
|
| 96 |
+
initializer_range=0.02,
|
| 97 |
+
intermediate_hook_ids=[11, 5],
|
| 98 |
+
intermediate_feature_dims=[256, 256],
|
| 99 |
+
scaled_images_ratios=[0.25, 0.5, 1],
|
| 100 |
+
scaled_images_overlap_ratios=[0.0, 0.5, 0.25],
|
| 101 |
+
scaled_images_feature_dims=[1024, 1024, 512],
|
| 102 |
+
merge_padding_value=3,
|
| 103 |
+
use_batch_norm_in_fusion_residual=False,
|
| 104 |
+
use_bias_in_fusion_residual=True,
|
| 105 |
+
use_fov_model=False,
|
| 106 |
+
num_fov_head_layers=2,
|
| 107 |
+
image_model_config=None,
|
| 108 |
+
patch_model_config=None,
|
| 109 |
+
fov_model_config=None,
|
| 110 |
+
**kwargs,
|
| 111 |
+
):
|
| 112 |
+
super().__init__(**kwargs)
|
| 113 |
+
|
| 114 |
+
# scaled_images_ratios is sorted
|
| 115 |
+
if scaled_images_ratios != sorted(scaled_images_ratios):
|
| 116 |
+
raise ValueError(
|
| 117 |
+
f"Values in scaled_images_ratios={scaled_images_ratios} " "should be sorted from low to high"
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
# scaled_images_ratios, scaled_images_overlap_ratios, scaled_images_feature_dims should be consistent
|
| 121 |
+
if not (len(scaled_images_ratios) == len(scaled_images_overlap_ratios) == len(scaled_images_feature_dims)):
|
| 122 |
+
raise ValueError(
|
| 123 |
+
f"len(scaled_images_ratios)={len(scaled_images_ratios)} and "
|
| 124 |
+
f"len(scaled_images_overlap_ratios)={len(scaled_images_overlap_ratios)} and "
|
| 125 |
+
f"len(scaled_images_feature_dims)={len(scaled_images_feature_dims)}, "
|
| 126 |
+
f"should match in config."
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
# intermediate_hook_ids, intermediate_feature_dims should be consistent
|
| 130 |
+
if not (len(intermediate_hook_ids) == len(intermediate_feature_dims)):
|
| 131 |
+
raise ValueError(
|
| 132 |
+
f"len(intermediate_hook_ids)={len(intermediate_hook_ids)} and "
|
| 133 |
+
f"len(intermediate_feature_dims)={len(intermediate_feature_dims)}, "
|
| 134 |
+
f"should match in config."
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
# fusion_hidden_size should be consistent with num_fov_head_layers
|
| 138 |
+
if fusion_hidden_size // 2**num_fov_head_layers == 0:
|
| 139 |
+
raise ValueError(
|
| 140 |
+
f"fusion_hidden_size={fusion_hidden_size} should be consistent with num_fov_head_layers={num_fov_head_layers} "
|
| 141 |
+
"i.e fusion_hidden_size // 2**num_fov_head_layers > 0"
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
self.fusion_hidden_size = fusion_hidden_size
|
| 145 |
+
self.patch_size = patch_size
|
| 146 |
+
self.initializer_range = initializer_range
|
| 147 |
+
self.use_batch_norm_in_fusion_residual = use_batch_norm_in_fusion_residual
|
| 148 |
+
self.use_bias_in_fusion_residual = use_bias_in_fusion_residual
|
| 149 |
+
self.use_fov_model = use_fov_model
|
| 150 |
+
self.num_fov_head_layers = num_fov_head_layers
|
| 151 |
+
self.intermediate_hook_ids = intermediate_hook_ids
|
| 152 |
+
self.intermediate_feature_dims = intermediate_feature_dims
|
| 153 |
+
self.scaled_images_ratios = scaled_images_ratios
|
| 154 |
+
self.scaled_images_overlap_ratios = scaled_images_overlap_ratios
|
| 155 |
+
self.scaled_images_feature_dims = scaled_images_feature_dims
|
| 156 |
+
self.merge_padding_value = merge_padding_value
|
| 157 |
+
self.image_model_config = image_model_config
|
| 158 |
+
self.patch_model_config = patch_model_config
|
| 159 |
+
self.fov_model_config = fov_model_config
|
| 160 |
+
|
| 161 |
+
for sub_config_key in self.sub_configs.keys():
|
| 162 |
+
sub_config = getattr(self, sub_config_key)
|
| 163 |
+
|
| 164 |
+
if sub_config is None:
|
| 165 |
+
sub_config = CONFIG_MAPPING["dinov2"](image_size=patch_size)
|
| 166 |
+
logger.info(
|
| 167 |
+
f"`{sub_config_key}` is `None`. Initializing `{sub_config_key}` with the `Dinov2Config` "
|
| 168 |
+
f"with default values except `{sub_config_key}.image_size` is set to `config.patch_size`."
|
| 169 |
+
)
|
| 170 |
+
elif isinstance(sub_config, dict):
|
| 171 |
+
sub_config = deepcopy(sub_config)
|
| 172 |
+
if "model_type" not in sub_config:
|
| 173 |
+
raise KeyError(
|
| 174 |
+
f"The `model_type` key is missing in the `{sub_config_key}` dictionary. Please provide the model type."
|
| 175 |
+
)
|
| 176 |
+
elif sub_config["model_type"] not in CONFIG_MAPPING:
|
| 177 |
+
raise ValueError(
|
| 178 |
+
f"The model type `{sub_config['model_type']}` in `{sub_config_key}` is not supported. Please provide a valid model type."
|
| 179 |
+
)
|
| 180 |
+
image_size = sub_config.get("image_size")
|
| 181 |
+
if image_size != patch_size:
|
| 182 |
+
logger.info(
|
| 183 |
+
f"The `image_size` in `{sub_config_key}` is set to `{image_size}`, "
|
| 184 |
+
f"but it does not match the required `patch_size` of `{patch_size}`. "
|
| 185 |
+
f"Updating `image_size` to `{patch_size}` for consistency. "
|
| 186 |
+
f"Ensure that `image_size` aligns with `patch_size` in the configuration."
|
| 187 |
+
)
|
| 188 |
+
sub_config.update({"image_size": patch_size})
|
| 189 |
+
sub_config = CONFIG_MAPPING[sub_config["model_type"]](**sub_config)
|
| 190 |
+
elif isinstance(sub_config, PretrainedConfig):
|
| 191 |
+
sub_config = sub_config
|
| 192 |
+
image_size = getattr(sub_config, "image_size", None)
|
| 193 |
+
if image_size != patch_size:
|
| 194 |
+
raise ValueError(
|
| 195 |
+
f"`config.{sub_config_key}.image_size={image_size}` should match `config.patch_size={patch_size}`."
|
| 196 |
+
)
|
| 197 |
+
else:
|
| 198 |
+
raise TypeError(
|
| 199 |
+
f"Invalid type for `sub_config`. Expected `PretrainedConfig`, `dict`, or `None`, but got {type(sub_config)}."
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
setattr(self, sub_config_key, sub_config)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
__all__ = ["DepthProConfig"]
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_pro/convert_depth_pro_weights_to_hf.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import gc
|
| 17 |
+
import os
|
| 18 |
+
|
| 19 |
+
import regex as re
|
| 20 |
+
import torch
|
| 21 |
+
from huggingface_hub import hf_hub_download
|
| 22 |
+
|
| 23 |
+
from transformers import (
|
| 24 |
+
DepthProConfig,
|
| 25 |
+
DepthProForDepthEstimation,
|
| 26 |
+
DepthProImageProcessorFast,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# fmt: off
|
| 31 |
+
ORIGINAL_TO_CONVERTED_KEY_MAPPING = {
|
| 32 |
+
|
| 33 |
+
# encoder
|
| 34 |
+
r"encoder.(patch|image)_encoder.cls_token": r"depth_pro.encoder.\1_encoder.model.embeddings.cls_token",
|
| 35 |
+
r"encoder.(patch|image)_encoder.pos_embed": r"depth_pro.encoder.\1_encoder.model.embeddings.position_embeddings",
|
| 36 |
+
r"encoder.(patch|image)_encoder.patch_embed.proj.(weight|bias)": r"depth_pro.encoder.\1_encoder.model.embeddings.patch_embeddings.projection.\2",
|
| 37 |
+
r"encoder.(patch|image)_encoder.blocks.(\d+).norm(\d+).(weight|bias)": r"depth_pro.encoder.\1_encoder.model.encoder.layer.\2.norm\3.\4",
|
| 38 |
+
r"encoder.(patch|image)_encoder.blocks.(\d+).attn.qkv.(weight|bias)": r"depth_pro.encoder.\1_encoder.model.encoder.layer.\2.attention.attention.(query|key|value).\3",
|
| 39 |
+
r"encoder.(patch|image)_encoder.blocks.(\d+).attn.proj.(weight|bias)": r"depth_pro.encoder.\1_encoder.model.encoder.layer.\2.attention.output.dense.\3",
|
| 40 |
+
r"encoder.(patch|image)_encoder.blocks.(\d+).ls(\d+).gamma": r"depth_pro.encoder.\1_encoder.model.encoder.layer.\2.layer_scale\3.lambda1",
|
| 41 |
+
r"encoder.(patch|image)_encoder.blocks.(\d+).mlp.fc(\d+).(weight|bias)": r"depth_pro.encoder.\1_encoder.model.encoder.layer.\2.mlp.fc\3.\4",
|
| 42 |
+
r"encoder.(patch|image)_encoder.norm.(weight|bias)": r"depth_pro.encoder.\1_encoder.model.layernorm.\2",
|
| 43 |
+
r"encoder.fuse_lowres.(weight|bias)": r"depth_pro.neck.fuse_image_with_low_res.\1",
|
| 44 |
+
|
| 45 |
+
# fov
|
| 46 |
+
r"fov.encoder.0.cls_token": r"fov_model.fov_encoder.model.embeddings.cls_token",
|
| 47 |
+
r"fov.encoder.0.pos_embed": r"fov_model.fov_encoder.model.embeddings.position_embeddings",
|
| 48 |
+
r"fov.encoder.0.patch_embed.proj.(weight|bias)": r"fov_model.fov_encoder.model.embeddings.patch_embeddings.projection.\1",
|
| 49 |
+
r"fov.encoder.0.blocks.(\d+).norm(\d+).(weight|bias)": r"fov_model.fov_encoder.model.encoder.layer.\1.norm\2.\3",
|
| 50 |
+
r"fov.encoder.0.blocks.(\d+).attn.qkv.(weight|bias)": r"fov_model.fov_encoder.model.encoder.layer.\1.attention.attention.(query|key|value).\2",
|
| 51 |
+
r"fov.encoder.0.blocks.(\d+).attn.proj.(weight|bias)": r"fov_model.fov_encoder.model.encoder.layer.\1.attention.output.dense.\2",
|
| 52 |
+
r"fov.encoder.0.blocks.(\d+).ls(\d+).gamma": r"fov_model.fov_encoder.model.encoder.layer.\1.layer_scale\2.lambda1",
|
| 53 |
+
r"fov.encoder.0.blocks.(\d+).mlp.fc(\d+).(weight|bias)": r"fov_model.fov_encoder.model.encoder.layer.\1.mlp.fc\2.\3",
|
| 54 |
+
r"fov.encoder.0.norm.(weight|bias)": r"fov_model.fov_encoder.model.layernorm.\1",
|
| 55 |
+
r"fov.downsample.0.(weight|bias)": r"fov_model.conv.\1",
|
| 56 |
+
r"fov.encoder.1.(weight|bias)": r"fov_model.fov_encoder.neck.\1",
|
| 57 |
+
r"fov.head.(\d+).(weight|bias)": r"fov_model.head.layers.\1.\2",
|
| 58 |
+
|
| 59 |
+
# head
|
| 60 |
+
r"head.(\d+).(weight|bias)": r"head.layers.\1.\2",
|
| 61 |
+
|
| 62 |
+
# upsamples
|
| 63 |
+
r"encoder.upsample_lowres.(weight|bias)": r"depth_pro.neck.feature_upsample.image_block.layers.0.\1",
|
| 64 |
+
r"encoder.upsample_latent(\d+).(\d+).(weight|bias)": lambda match: (
|
| 65 |
+
f"depth_pro.neck.feature_upsample.intermediate.{1-int(match.group(1))}.layers.{match.group(2)}.{match.group(3)}"
|
| 66 |
+
),
|
| 67 |
+
r"encoder.upsample(\d+).(\d+).(weight|bias)": lambda match: (
|
| 68 |
+
f"depth_pro.neck.feature_upsample.scaled_images.{2-int(match.group(1))}.layers.{match.group(2)}.{match.group(3)}"
|
| 69 |
+
),
|
| 70 |
+
|
| 71 |
+
# projections between encoder and fusion
|
| 72 |
+
r"decoder.convs.(\d+).weight": lambda match: (
|
| 73 |
+
f"depth_pro.neck.feature_projection.projections.{4-int(match.group(1))}.weight"
|
| 74 |
+
),
|
| 75 |
+
|
| 76 |
+
# fusion stage
|
| 77 |
+
r"decoder.fusions.([1234]).resnet(\d+).residual.(\d+).(weight|bias)": lambda match: (
|
| 78 |
+
f"fusion_stage.intermediate.{4-int(match.group(1))}.residual_layer{match.group(2)}.convolution{(int(match.group(3))+1)//2}.{match.group(4)}"
|
| 79 |
+
),
|
| 80 |
+
r"decoder.fusions.0.resnet(\d+).residual.(\d+).(weight|bias)": lambda match: (
|
| 81 |
+
f"fusion_stage.final.residual_layer{match.group(1)}.convolution{(int(match.group(2))+1)//2}.{match.group(3)}"
|
| 82 |
+
),
|
| 83 |
+
r"decoder.fusions.([1234]).out_conv.(weight|bias)": lambda match: (
|
| 84 |
+
f"fusion_stage.intermediate.{4-int(match.group(1))}.projection.{match.group(2)}"
|
| 85 |
+
),
|
| 86 |
+
r"decoder.fusions.0.out_conv.(weight|bias)": lambda match: (
|
| 87 |
+
f"fusion_stage.final.projection.{match.group(1)}"
|
| 88 |
+
),
|
| 89 |
+
r"decoder.fusions.(\d+).deconv.(weight|bias)": lambda match: (
|
| 90 |
+
f"fusion_stage.intermediate.{4-int(match.group(1))}.deconv.{match.group(2)}"
|
| 91 |
+
),
|
| 92 |
+
}
|
| 93 |
+
# fmt: on
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def convert_old_keys_to_new_keys(state_dict_keys: dict = None):
|
| 97 |
+
output_dict = {}
|
| 98 |
+
if state_dict_keys is not None:
|
| 99 |
+
old_text = "\n".join(state_dict_keys)
|
| 100 |
+
new_text = old_text
|
| 101 |
+
for pattern, replacement in ORIGINAL_TO_CONVERTED_KEY_MAPPING.items():
|
| 102 |
+
if replacement is None:
|
| 103 |
+
new_text = re.sub(pattern, "", new_text) # an empty line
|
| 104 |
+
continue
|
| 105 |
+
new_text = re.sub(pattern, replacement, new_text)
|
| 106 |
+
output_dict = dict(zip(old_text.split("\n"), new_text.split("\n")))
|
| 107 |
+
return output_dict
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def get_qkv_state_dict(key, parameter):
|
| 111 |
+
"""
|
| 112 |
+
new key which looks like this
|
| 113 |
+
xxxx.(q|k|v).xxx (m, n)
|
| 114 |
+
|
| 115 |
+
is converted to
|
| 116 |
+
xxxx.q.xxxx (m//3, n)
|
| 117 |
+
xxxx.k.xxxx (m//3, n)
|
| 118 |
+
xxxx.v.xxxx (m//3, n)
|
| 119 |
+
"""
|
| 120 |
+
qkv_state_dict = {}
|
| 121 |
+
placeholder = re.search(r"(\(.*?\))", key).group(1) # finds "(query|key|value)"
|
| 122 |
+
replacements_keys = placeholder[1:-1].split("|") # creates ['query', 'key', 'value']
|
| 123 |
+
replacements_vals = torch.split(
|
| 124 |
+
parameter, split_size_or_sections=parameter.size(0) // len(replacements_keys), dim=0
|
| 125 |
+
)
|
| 126 |
+
for replacement_key, replacement_val in zip(replacements_keys, replacements_vals):
|
| 127 |
+
qkv_state_dict[key.replace(placeholder, replacement_key)] = replacement_val
|
| 128 |
+
return qkv_state_dict
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def write_model(
|
| 132 |
+
hf_repo_id: str,
|
| 133 |
+
output_dir: str,
|
| 134 |
+
safe_serialization: bool = True,
|
| 135 |
+
):
|
| 136 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 137 |
+
|
| 138 |
+
# ------------------------------------------------------------
|
| 139 |
+
# Create and save config
|
| 140 |
+
# ------------------------------------------------------------
|
| 141 |
+
|
| 142 |
+
# create config
|
| 143 |
+
backbone_config = {
|
| 144 |
+
"model_type": "dinov2",
|
| 145 |
+
"num_hidden_layers": 24,
|
| 146 |
+
"patch_size": 16,
|
| 147 |
+
"hidden_size": 1024,
|
| 148 |
+
"num_attention_heads": 16,
|
| 149 |
+
"image_size": 384,
|
| 150 |
+
"use_mask_token": False,
|
| 151 |
+
}
|
| 152 |
+
config = DepthProConfig(
|
| 153 |
+
# original implementation uses same config for all 3 models
|
| 154 |
+
image_model_config=backbone_config,
|
| 155 |
+
patch_model_config=backbone_config,
|
| 156 |
+
fov_model_config=backbone_config,
|
| 157 |
+
use_fov_model=True,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# save config
|
| 161 |
+
config.save_pretrained(output_dir)
|
| 162 |
+
print("Model config saved successfully...")
|
| 163 |
+
|
| 164 |
+
# ------------------------------------------------------------
|
| 165 |
+
# Convert weights
|
| 166 |
+
# ------------------------------------------------------------
|
| 167 |
+
|
| 168 |
+
# download and load state_dict from hf repo
|
| 169 |
+
file_path = hf_hub_download(hf_repo_id, "depth_pro.pt")
|
| 170 |
+
loaded = torch.load(file_path, weights_only=True)
|
| 171 |
+
|
| 172 |
+
print("Converting model...")
|
| 173 |
+
all_keys = list(loaded.keys())
|
| 174 |
+
new_keys = convert_old_keys_to_new_keys(all_keys)
|
| 175 |
+
|
| 176 |
+
state_dict = {}
|
| 177 |
+
for key in all_keys:
|
| 178 |
+
new_key = new_keys[key]
|
| 179 |
+
current_parameter = loaded.pop(key)
|
| 180 |
+
|
| 181 |
+
if "qkv" in key:
|
| 182 |
+
qkv_state_dict = get_qkv_state_dict(new_key, current_parameter)
|
| 183 |
+
state_dict.update(qkv_state_dict)
|
| 184 |
+
else:
|
| 185 |
+
state_dict[new_key] = current_parameter
|
| 186 |
+
|
| 187 |
+
print("Loading the checkpoint in a DepthPro model.")
|
| 188 |
+
model = DepthProForDepthEstimation(config)
|
| 189 |
+
model.load_state_dict(state_dict, strict=True, assign=True)
|
| 190 |
+
print("Checkpoint loaded successfully.")
|
| 191 |
+
|
| 192 |
+
print("Saving the model.")
|
| 193 |
+
model.save_pretrained(output_dir, safe_serialization=safe_serialization)
|
| 194 |
+
del state_dict, model
|
| 195 |
+
|
| 196 |
+
# Safety check: reload the converted model
|
| 197 |
+
gc.collect()
|
| 198 |
+
print("Reloading the model to check if it's saved correctly.")
|
| 199 |
+
model = DepthProForDepthEstimation.from_pretrained(output_dir, device_map="auto")
|
| 200 |
+
print("Model reloaded successfully.")
|
| 201 |
+
return model
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def write_image_processor(output_dir: str):
|
| 205 |
+
image_processor = DepthProImageProcessorFast()
|
| 206 |
+
image_processor.save_pretrained(output_dir)
|
| 207 |
+
return image_processor
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def main():
|
| 211 |
+
parser = argparse.ArgumentParser()
|
| 212 |
+
parser.add_argument(
|
| 213 |
+
"--hf_repo_id",
|
| 214 |
+
default="apple/DepthPro",
|
| 215 |
+
help="Location of official weights from apple on HF",
|
| 216 |
+
)
|
| 217 |
+
parser.add_argument(
|
| 218 |
+
"--output_dir",
|
| 219 |
+
default="apple_DepthPro",
|
| 220 |
+
help="Location to write the converted model and processor",
|
| 221 |
+
)
|
| 222 |
+
parser.add_argument(
|
| 223 |
+
"--safe_serialization", default=True, type=bool, help="Whether or not to save using `safetensors`."
|
| 224 |
+
)
|
| 225 |
+
parser.add_argument(
|
| 226 |
+
"--push_to_hub",
|
| 227 |
+
action=argparse.BooleanOptionalAction,
|
| 228 |
+
help="Whether or not to push the converted model to the huggingface hub.",
|
| 229 |
+
)
|
| 230 |
+
parser.add_argument(
|
| 231 |
+
"--hub_repo_id",
|
| 232 |
+
default="apple/DepthPro-hf",
|
| 233 |
+
help="Huggingface hub repo to write the converted model and processor",
|
| 234 |
+
)
|
| 235 |
+
args = parser.parse_args()
|
| 236 |
+
|
| 237 |
+
model = write_model(
|
| 238 |
+
hf_repo_id=args.hf_repo_id,
|
| 239 |
+
output_dir=args.output_dir,
|
| 240 |
+
safe_serialization=args.safe_serialization,
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
image_processor = write_image_processor(
|
| 244 |
+
output_dir=args.output_dir,
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
if args.push_to_hub:
|
| 248 |
+
print("Pushing to hub...")
|
| 249 |
+
model.push_to_hub(args.hub_repo_id)
|
| 250 |
+
image_processor.push_to_hub(args.hub_repo_id)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
if __name__ == "__main__":
|
| 254 |
+
main()
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_pro/image_processing_depth_pro.py
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Image processor class for DepthPro."""
|
| 16 |
+
|
| 17 |
+
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from .modeling_depth_pro import DepthProDepthEstimatorOutput
|
| 24 |
+
|
| 25 |
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
| 26 |
+
from ...image_transforms import to_channel_dimension_format
|
| 27 |
+
from ...image_utils import (
|
| 28 |
+
IMAGENET_STANDARD_MEAN,
|
| 29 |
+
IMAGENET_STANDARD_STD,
|
| 30 |
+
ChannelDimension,
|
| 31 |
+
ImageInput,
|
| 32 |
+
PILImageResampling,
|
| 33 |
+
infer_channel_dimension_format,
|
| 34 |
+
is_scaled_image,
|
| 35 |
+
is_torch_available,
|
| 36 |
+
make_list_of_images,
|
| 37 |
+
pil_torch_interpolation_mapping,
|
| 38 |
+
to_numpy_array,
|
| 39 |
+
valid_images,
|
| 40 |
+
)
|
| 41 |
+
from ...utils import (
|
| 42 |
+
TensorType,
|
| 43 |
+
filter_out_non_signature_kwargs,
|
| 44 |
+
logging,
|
| 45 |
+
requires_backends,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
if is_torch_available():
|
| 50 |
+
import torch
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
logger = logging.get_logger(__name__)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class DepthProImageProcessor(BaseImageProcessor):
|
| 57 |
+
r"""
|
| 58 |
+
Constructs a DepthPro image processor.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 62 |
+
Whether to resize the image's (height, width) dimensions to the specified `(size["height"],
|
| 63 |
+
size["width"])`. Can be overridden by the `do_resize` parameter in the `preprocess` method.
|
| 64 |
+
size (`dict`, *optional*, defaults to `{"height": 1536, "width": 1536}`):
|
| 65 |
+
Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
|
| 66 |
+
method.
|
| 67 |
+
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
|
| 68 |
+
Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
|
| 69 |
+
`preprocess` method.
|
| 70 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 71 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
|
| 72 |
+
parameter in the `preprocess` method.
|
| 73 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
| 74 |
+
Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
|
| 75 |
+
`preprocess` method.
|
| 76 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 77 |
+
Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
|
| 78 |
+
method.
|
| 79 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
|
| 80 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
| 81 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
| 82 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
|
| 83 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
| 84 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
model_input_names = ["pixel_values"]
|
| 88 |
+
|
| 89 |
+
def __init__(
|
| 90 |
+
self,
|
| 91 |
+
do_resize: bool = True,
|
| 92 |
+
size: Optional[Dict[str, int]] = None,
|
| 93 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 94 |
+
do_rescale: bool = True,
|
| 95 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 96 |
+
do_normalize: bool = True,
|
| 97 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 98 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 99 |
+
**kwargs,
|
| 100 |
+
):
|
| 101 |
+
super().__init__(**kwargs)
|
| 102 |
+
size = size if size is not None else {"height": 1536, "width": 1536}
|
| 103 |
+
size = get_size_dict(size)
|
| 104 |
+
self.do_resize = do_resize
|
| 105 |
+
self.do_rescale = do_rescale
|
| 106 |
+
self.do_normalize = do_normalize
|
| 107 |
+
self.size = size
|
| 108 |
+
self.resample = resample
|
| 109 |
+
self.rescale_factor = rescale_factor
|
| 110 |
+
self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
|
| 111 |
+
self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
|
| 112 |
+
|
| 113 |
+
def resize(
|
| 114 |
+
self,
|
| 115 |
+
image: np.ndarray,
|
| 116 |
+
size: Dict[str, int],
|
| 117 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 118 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 119 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 120 |
+
**kwargs,
|
| 121 |
+
) -> np.ndarray:
|
| 122 |
+
"""
|
| 123 |
+
Resize an image to `(size["height"], size["width"])`.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
image (`np.ndarray`):
|
| 127 |
+
Image to resize.
|
| 128 |
+
size (`Dict[str, int]`):
|
| 129 |
+
Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
|
| 130 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
|
| 131 |
+
`PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
|
| 132 |
+
data_format (`ChannelDimension` or `str`, *optional*):
|
| 133 |
+
The channel dimension format for the output image. If unset, the channel dimension format of the input
|
| 134 |
+
image is used. Can be one of:
|
| 135 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 136 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 137 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 138 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 139 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 140 |
+
from the input image. Can be one of:
|
| 141 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 142 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 143 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 144 |
+
|
| 145 |
+
Returns:
|
| 146 |
+
`np.ndarray`: The resized images.
|
| 147 |
+
"""
|
| 148 |
+
requires_backends(self, "torch")
|
| 149 |
+
|
| 150 |
+
size = get_size_dict(size)
|
| 151 |
+
if "height" not in size or "width" not in size:
|
| 152 |
+
raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
|
| 153 |
+
output_size = (size["height"], size["width"])
|
| 154 |
+
|
| 155 |
+
# we use torch interpolation instead of image.resize because DepthProImageProcessor
|
| 156 |
+
# rescales, then normalizes, which may cause some values to become negative, before resizing the image.
|
| 157 |
+
# image.resize expects all values to be in range [0, 1] or [0, 255] and throws an exception otherwise,
|
| 158 |
+
# however pytorch interpolation works with negative values.
|
| 159 |
+
# relevant issue here: https://github.com/huggingface/transformers/issues/34920
|
| 160 |
+
# input should be (B, C, H, W)
|
| 161 |
+
image_tensor = torch.from_numpy(image).unsqueeze(0)
|
| 162 |
+
resized_image = torch.nn.functional.interpolate(
|
| 163 |
+
input=image_tensor,
|
| 164 |
+
size=output_size,
|
| 165 |
+
mode=pil_torch_interpolation_mapping[resample].value,
|
| 166 |
+
)
|
| 167 |
+
resized_image = resized_image.squeeze(0).numpy()
|
| 168 |
+
return resized_image
|
| 169 |
+
|
| 170 |
+
def _validate_input_arguments(
|
| 171 |
+
self,
|
| 172 |
+
do_resize: bool,
|
| 173 |
+
size: Dict[str, int],
|
| 174 |
+
resample: PILImageResampling,
|
| 175 |
+
do_rescale: bool,
|
| 176 |
+
rescale_factor: float,
|
| 177 |
+
do_normalize: bool,
|
| 178 |
+
image_mean: Union[float, List[float]],
|
| 179 |
+
image_std: Union[float, List[float]],
|
| 180 |
+
data_format: Union[str, ChannelDimension],
|
| 181 |
+
):
|
| 182 |
+
if do_resize and None in (size, resample):
|
| 183 |
+
raise ValueError("Size and resample must be specified if do_resize is True.")
|
| 184 |
+
|
| 185 |
+
if do_rescale and rescale_factor is None:
|
| 186 |
+
raise ValueError("Rescale factor must be specified if do_rescale is True.")
|
| 187 |
+
|
| 188 |
+
if do_normalize and None in (image_mean, image_std):
|
| 189 |
+
raise ValueError("Image mean and standard deviation must be specified if do_normalize is True.")
|
| 190 |
+
|
| 191 |
+
@filter_out_non_signature_kwargs()
|
| 192 |
+
def preprocess(
|
| 193 |
+
self,
|
| 194 |
+
images: ImageInput,
|
| 195 |
+
do_resize: Optional[bool] = None,
|
| 196 |
+
size: Optional[Dict[str, int]] = None,
|
| 197 |
+
resample: Optional[PILImageResampling] = None,
|
| 198 |
+
do_rescale: Optional[bool] = None,
|
| 199 |
+
rescale_factor: Optional[float] = None,
|
| 200 |
+
do_normalize: Optional[bool] = None,
|
| 201 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 202 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 203 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 204 |
+
data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
|
| 205 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 206 |
+
):
|
| 207 |
+
"""
|
| 208 |
+
Preprocess an image or batch of images.
|
| 209 |
+
|
| 210 |
+
Args:
|
| 211 |
+
images (`ImageInput`):
|
| 212 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 213 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 214 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 215 |
+
Whether to resize the image.
|
| 216 |
+
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
|
| 217 |
+
Dictionary in the format `{"height": h, "width": w}` specifying the size of the output image after
|
| 218 |
+
resizing.
|
| 219 |
+
resample (`PILImageResampling` filter, *optional*, defaults to `self.resample`):
|
| 220 |
+
`PILImageResampling` filter to use if resizing the image e.g. `PILImageResampling.BILINEAR`. Only has
|
| 221 |
+
an effect if `do_resize` is set to `True`.
|
| 222 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 223 |
+
Whether to rescale the image values between [0 - 1].
|
| 224 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 225 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 226 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 227 |
+
Whether to normalize the image.
|
| 228 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
| 229 |
+
Image mean to use if `do_normalize` is set to `True`.
|
| 230 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
| 231 |
+
Image standard deviation to use if `do_normalize` is set to `True`.
|
| 232 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 233 |
+
The type of tensors to return. Can be one of:
|
| 234 |
+
- Unset: Return a list of `np.ndarray`.
|
| 235 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 236 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 237 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 238 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 239 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 240 |
+
The channel dimension format for the output image. Can be one of:
|
| 241 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 242 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 243 |
+
- Unset: Use the channel dimension format of the input image.
|
| 244 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 245 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 246 |
+
from the input image. Can be one of:
|
| 247 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 248 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 249 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 250 |
+
"""
|
| 251 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 252 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 253 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 254 |
+
resample = resample if resample is not None else self.resample
|
| 255 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 256 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 257 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 258 |
+
|
| 259 |
+
size = size if size is not None else self.size
|
| 260 |
+
|
| 261 |
+
images = make_list_of_images(images)
|
| 262 |
+
|
| 263 |
+
if not valid_images(images):
|
| 264 |
+
raise ValueError(
|
| 265 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 266 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 267 |
+
)
|
| 268 |
+
self._validate_input_arguments(
|
| 269 |
+
do_resize=do_resize,
|
| 270 |
+
size=size,
|
| 271 |
+
resample=resample,
|
| 272 |
+
do_rescale=do_rescale,
|
| 273 |
+
rescale_factor=rescale_factor,
|
| 274 |
+
do_normalize=do_normalize,
|
| 275 |
+
image_mean=image_mean,
|
| 276 |
+
image_std=image_std,
|
| 277 |
+
data_format=data_format,
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
# All transformations expect numpy arrays.
|
| 281 |
+
images = [to_numpy_array(image) for image in images]
|
| 282 |
+
|
| 283 |
+
if is_scaled_image(images[0]) and do_rescale:
|
| 284 |
+
logger.warning_once(
|
| 285 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 286 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
if input_data_format is None:
|
| 290 |
+
# We assume that all images have the same channel dimension format.
|
| 291 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 292 |
+
|
| 293 |
+
all_images = []
|
| 294 |
+
for image in images:
|
| 295 |
+
if do_rescale:
|
| 296 |
+
image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
| 297 |
+
|
| 298 |
+
if do_normalize:
|
| 299 |
+
image = self.normalize(
|
| 300 |
+
image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
# depth-pro rescales and normalizes the image before resizing it
|
| 304 |
+
# uses torch interpolation which requires ChannelDimension.FIRST
|
| 305 |
+
if do_resize:
|
| 306 |
+
image = to_channel_dimension_format(image, ChannelDimension.FIRST, input_channel_dim=input_data_format)
|
| 307 |
+
image = self.resize(image=image, size=size, resample=resample)
|
| 308 |
+
image = to_channel_dimension_format(image, data_format, input_channel_dim=ChannelDimension.FIRST)
|
| 309 |
+
else:
|
| 310 |
+
image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
| 311 |
+
|
| 312 |
+
all_images.append(image)
|
| 313 |
+
|
| 314 |
+
data = {"pixel_values": all_images}
|
| 315 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 316 |
+
|
| 317 |
+
def post_process_depth_estimation(
|
| 318 |
+
self,
|
| 319 |
+
outputs: "DepthProDepthEstimatorOutput",
|
| 320 |
+
target_sizes: Optional[Union[TensorType, List[Tuple[int, int]], None]] = None,
|
| 321 |
+
) -> Dict[str, List[TensorType]]:
|
| 322 |
+
"""
|
| 323 |
+
Post-processes the raw depth predictions from the model to generate
|
| 324 |
+
final depth predictions which is caliberated using the field of view if provided
|
| 325 |
+
and resized to specified target sizes if provided.
|
| 326 |
+
|
| 327 |
+
Args:
|
| 328 |
+
outputs ([`DepthProDepthEstimatorOutput`]):
|
| 329 |
+
Raw outputs of the model.
|
| 330 |
+
target_sizes (`Optional[Union[TensorType, List[Tuple[int, int]], None]]`, *optional*, defaults to `None`):
|
| 331 |
+
Target sizes to resize the depth predictions. Can be a tensor of shape `(batch_size, 2)`
|
| 332 |
+
or a list of tuples `(height, width)` for each image in the batch. If `None`, no resizing
|
| 333 |
+
is performed.
|
| 334 |
+
|
| 335 |
+
Returns:
|
| 336 |
+
`List[Dict[str, TensorType]]`: A list of dictionaries of tensors representing the processed depth
|
| 337 |
+
predictions, and field of view (degrees) and focal length (pixels) if `field_of_view` is given in `outputs`.
|
| 338 |
+
|
| 339 |
+
Raises:
|
| 340 |
+
`ValueError`:
|
| 341 |
+
If the lengths of `predicted_depths`, `fovs`, or `target_sizes` are mismatched.
|
| 342 |
+
"""
|
| 343 |
+
requires_backends(self, "torch")
|
| 344 |
+
|
| 345 |
+
predicted_depth = outputs.predicted_depth
|
| 346 |
+
fov = outputs.field_of_view
|
| 347 |
+
|
| 348 |
+
batch_size = len(predicted_depth)
|
| 349 |
+
|
| 350 |
+
if target_sizes is not None and batch_size != len(target_sizes):
|
| 351 |
+
raise ValueError(
|
| 352 |
+
"Make sure that you pass in as many fov values as the batch dimension of the predicted depth"
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
results = []
|
| 356 |
+
fov = [None] * batch_size if fov is None else fov
|
| 357 |
+
target_sizes = [None] * batch_size if target_sizes is None else target_sizes
|
| 358 |
+
for depth, fov_value, target_size in zip(predicted_depth, fov, target_sizes):
|
| 359 |
+
focal_length = None
|
| 360 |
+
if target_size is not None:
|
| 361 |
+
# scale image w.r.t fov
|
| 362 |
+
if fov_value is not None:
|
| 363 |
+
width = target_size[1]
|
| 364 |
+
focal_length = 0.5 * width / torch.tan(0.5 * torch.deg2rad(fov_value))
|
| 365 |
+
depth = depth * width / focal_length
|
| 366 |
+
|
| 367 |
+
# interpolate
|
| 368 |
+
depth = torch.nn.functional.interpolate(
|
| 369 |
+
# input should be (B, C, H, W)
|
| 370 |
+
input=depth.unsqueeze(0).unsqueeze(1),
|
| 371 |
+
size=target_size,
|
| 372 |
+
mode=pil_torch_interpolation_mapping[self.resample].value,
|
| 373 |
+
).squeeze()
|
| 374 |
+
|
| 375 |
+
# inverse the depth
|
| 376 |
+
depth = 1.0 / torch.clamp(depth, min=1e-4, max=1e4)
|
| 377 |
+
|
| 378 |
+
results.append(
|
| 379 |
+
{
|
| 380 |
+
"predicted_depth": depth,
|
| 381 |
+
"field_of_view": fov_value,
|
| 382 |
+
"focal_length": focal_length,
|
| 383 |
+
}
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
return results
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
__all__ = ["DepthProImageProcessor"]
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/depth_pro/image_processing_depth_pro_fast.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Fast Image processor class for DepthPro."""
|
| 16 |
+
|
| 17 |
+
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
from ...image_processing_base import BatchFeature
|
| 20 |
+
from ...image_processing_utils_fast import (
|
| 21 |
+
BASE_IMAGE_PROCESSOR_FAST_DOCSTRING,
|
| 22 |
+
BaseImageProcessorFast,
|
| 23 |
+
group_images_by_shape,
|
| 24 |
+
reorder_images,
|
| 25 |
+
)
|
| 26 |
+
from ...image_utils import (
|
| 27 |
+
IMAGENET_STANDARD_MEAN,
|
| 28 |
+
IMAGENET_STANDARD_STD,
|
| 29 |
+
PILImageResampling,
|
| 30 |
+
SizeDict,
|
| 31 |
+
)
|
| 32 |
+
from ...utils import (
|
| 33 |
+
TensorType,
|
| 34 |
+
add_start_docstrings,
|
| 35 |
+
is_torch_available,
|
| 36 |
+
is_torchvision_available,
|
| 37 |
+
is_torchvision_v2_available,
|
| 38 |
+
logging,
|
| 39 |
+
requires_backends,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if TYPE_CHECKING:
|
| 44 |
+
from .modeling_depth_pro import DepthProDepthEstimatorOutput
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
if is_torch_available():
|
| 50 |
+
import torch
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if is_torchvision_available():
|
| 54 |
+
from ...image_utils import pil_torch_interpolation_mapping
|
| 55 |
+
|
| 56 |
+
if is_torchvision_v2_available():
|
| 57 |
+
from torchvision.transforms.v2 import functional as F
|
| 58 |
+
else:
|
| 59 |
+
from torchvision.transforms import functional as F
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@add_start_docstrings(
|
| 63 |
+
"Constructs a fast DepthPro image processor.",
|
| 64 |
+
BASE_IMAGE_PROCESSOR_FAST_DOCSTRING,
|
| 65 |
+
)
|
| 66 |
+
class DepthProImageProcessorFast(BaseImageProcessorFast):
|
| 67 |
+
resample = PILImageResampling.BILINEAR
|
| 68 |
+
image_mean = IMAGENET_STANDARD_MEAN
|
| 69 |
+
image_std = IMAGENET_STANDARD_STD
|
| 70 |
+
size = {"height": 1536, "width": 1536}
|
| 71 |
+
do_resize = True
|
| 72 |
+
do_rescale = True
|
| 73 |
+
do_normalize = True
|
| 74 |
+
|
| 75 |
+
# DepthPro resizes image after rescaling and normalizing,
|
| 76 |
+
# which makes it different from BaseImageProcessorFast._preprocess
|
| 77 |
+
def _preprocess(
|
| 78 |
+
self,
|
| 79 |
+
images: List["torch.Tensor"],
|
| 80 |
+
do_resize: bool,
|
| 81 |
+
size: SizeDict,
|
| 82 |
+
interpolation: Optional["F.InterpolationMode"],
|
| 83 |
+
do_center_crop: bool,
|
| 84 |
+
crop_size: SizeDict,
|
| 85 |
+
do_rescale: bool,
|
| 86 |
+
rescale_factor: float,
|
| 87 |
+
do_normalize: bool,
|
| 88 |
+
image_mean: Optional[Union[float, List[float]]],
|
| 89 |
+
image_std: Optional[Union[float, List[float]]],
|
| 90 |
+
return_tensors: Optional[Union[str, TensorType]],
|
| 91 |
+
) -> BatchFeature:
|
| 92 |
+
# Group images by size for batched scaling
|
| 93 |
+
grouped_images, grouped_images_index = group_images_by_shape(images)
|
| 94 |
+
processed_images_grouped = {}
|
| 95 |
+
for shape, stacked_images in grouped_images.items():
|
| 96 |
+
# Fused rescale and normalize
|
| 97 |
+
stacked_images = self.rescale_and_normalize(
|
| 98 |
+
stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
|
| 99 |
+
)
|
| 100 |
+
if do_resize:
|
| 101 |
+
stacked_images = self.resize(
|
| 102 |
+
image=stacked_images,
|
| 103 |
+
size=size,
|
| 104 |
+
interpolation=interpolation,
|
| 105 |
+
antialias=False,
|
| 106 |
+
)
|
| 107 |
+
processed_images_grouped[shape] = stacked_images
|
| 108 |
+
|
| 109 |
+
processed_images = reorder_images(processed_images_grouped, grouped_images_index)
|
| 110 |
+
processed_images = torch.stack(processed_images, dim=0) if return_tensors else processed_images
|
| 111 |
+
|
| 112 |
+
return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
|
| 113 |
+
|
| 114 |
+
# Copied from transformers.models.depth_pro.image_processing_depth_pro.DepthProImageProcessor.post_process_depth_estimation
|
| 115 |
+
def post_process_depth_estimation(
|
| 116 |
+
self,
|
| 117 |
+
outputs: "DepthProDepthEstimatorOutput",
|
| 118 |
+
target_sizes: Optional[Union[TensorType, List[Tuple[int, int]], None]] = None,
|
| 119 |
+
) -> Dict[str, List[TensorType]]:
|
| 120 |
+
"""
|
| 121 |
+
Post-processes the raw depth predictions from the model to generate
|
| 122 |
+
final depth predictions which is caliberated using the field of view if provided
|
| 123 |
+
and resized to specified target sizes if provided.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
outputs ([`DepthProDepthEstimatorOutput`]):
|
| 127 |
+
Raw outputs of the model.
|
| 128 |
+
target_sizes (`Optional[Union[TensorType, List[Tuple[int, int]], None]]`, *optional*, defaults to `None`):
|
| 129 |
+
Target sizes to resize the depth predictions. Can be a tensor of shape `(batch_size, 2)`
|
| 130 |
+
or a list of tuples `(height, width)` for each image in the batch. If `None`, no resizing
|
| 131 |
+
is performed.
|
| 132 |
+
|
| 133 |
+
Returns:
|
| 134 |
+
`List[Dict[str, TensorType]]`: A list of dictionaries of tensors representing the processed depth
|
| 135 |
+
predictions, and field of view (degrees) and focal length (pixels) if `field_of_view` is given in `outputs`.
|
| 136 |
+
|
| 137 |
+
Raises:
|
| 138 |
+
`ValueError`:
|
| 139 |
+
If the lengths of `predicted_depths`, `fovs`, or `target_sizes` are mismatched.
|
| 140 |
+
"""
|
| 141 |
+
requires_backends(self, "torch")
|
| 142 |
+
|
| 143 |
+
predicted_depth = outputs.predicted_depth
|
| 144 |
+
fov = outputs.field_of_view
|
| 145 |
+
|
| 146 |
+
batch_size = len(predicted_depth)
|
| 147 |
+
|
| 148 |
+
if target_sizes is not None and batch_size != len(target_sizes):
|
| 149 |
+
raise ValueError(
|
| 150 |
+
"Make sure that you pass in as many fov values as the batch dimension of the predicted depth"
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
results = []
|
| 154 |
+
fov = [None] * batch_size if fov is None else fov
|
| 155 |
+
target_sizes = [None] * batch_size if target_sizes is None else target_sizes
|
| 156 |
+
for depth, fov_value, target_size in zip(predicted_depth, fov, target_sizes):
|
| 157 |
+
focal_length = None
|
| 158 |
+
if target_size is not None:
|
| 159 |
+
# scale image w.r.t fov
|
| 160 |
+
if fov_value is not None:
|
| 161 |
+
width = target_size[1]
|
| 162 |
+
focal_length = 0.5 * width / torch.tan(0.5 * torch.deg2rad(fov_value))
|
| 163 |
+
depth = depth * width / focal_length
|
| 164 |
+
|
| 165 |
+
# interpolate
|
| 166 |
+
depth = torch.nn.functional.interpolate(
|
| 167 |
+
# input should be (B, C, H, W)
|
| 168 |
+
input=depth.unsqueeze(0).unsqueeze(1),
|
| 169 |
+
size=target_size,
|
| 170 |
+
mode=pil_torch_interpolation_mapping[self.resample].value,
|
| 171 |
+
).squeeze()
|
| 172 |
+
|
| 173 |
+
# inverse the depth
|
| 174 |
+
depth = 1.0 / torch.clamp(depth, min=1e-4, max=1e4)
|
| 175 |
+
|
| 176 |
+
results.append(
|
| 177 |
+
{
|
| 178 |
+
"predicted_depth": depth,
|
| 179 |
+
"field_of_view": fov_value,
|
| 180 |
+
"focal_length": focal_length,
|
| 181 |
+
}
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
return results
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
__all__ = ["DepthProImageProcessorFast"]
|
tasks/tasksmith-e0f68dd4420c/environment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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The Apple Research Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch DepthPro model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import List, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn.functional as F
|
| 23 |
+
from torch import nn
|
| 24 |
+
|
| 25 |
+
from ...modeling_outputs import BaseModelOutput
|
| 26 |
+
from ...modeling_utils import PreTrainedModel
|
| 27 |
+
from ...utils import (
|
| 28 |
+
ModelOutput,
|
| 29 |
+
add_start_docstrings,
|
| 30 |
+
add_start_docstrings_to_model_forward,
|
| 31 |
+
logging,
|
| 32 |
+
replace_return_docstrings,
|
| 33 |
+
torch_int,
|
| 34 |
+
)
|
| 35 |
+
from ..auto import AutoModel
|
| 36 |
+
from .configuration_depth_pro import DepthProConfig
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
logger = logging.get_logger(__name__)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass
|
| 43 |
+
class DepthProOutput(ModelOutput):
|
| 44 |
+
"""
|
| 45 |
+
Base class for DepthPro's outputs.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, n_patches_per_batch, sequence_length, hidden_size)`):
|
| 49 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 50 |
+
features (`Union[torch.FloatTensor, List[torch.FloatTensor]]`, *optional*):
|
| 51 |
+
Features from encoders. Can be a single feature or a list of features.
|
| 52 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 53 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 54 |
+
one for the output of each layer) of shape `(batch_size, n_patches_per_batch, sequence_length, hidden_size)`.
|
| 55 |
+
|
| 56 |
+
Hidden-states of the model at the output of each layer and the optional initial embedding outputs.
|
| 57 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 58 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, n_patches_per_batch, num_heads, sequence_length,
|
| 59 |
+
sequence_length)`.
|
| 60 |
+
|
| 61 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 62 |
+
heads.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
last_hidden_state: torch.FloatTensor = None
|
| 66 |
+
features: Union[torch.FloatTensor, List[torch.FloatTensor]] = None
|
| 67 |
+
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 68 |
+
attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@dataclass
|
| 72 |
+
class DepthProDepthEstimatorOutput(ModelOutput):
|
| 73 |
+
"""
|
| 74 |
+
Base class for DepthProForDepthEstimation's output.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 78 |
+
Classification (or regression if config.num_labels==1) loss.
|
| 79 |
+
predicted_depth (`torch.FloatTensor` of shape `(batch_size, height, width)`):
|
| 80 |
+
Predicted depth for each pixel.
|
| 81 |
+
field_of_view (`torch.FloatTensor` of shape `(batch_size,)`, *optional*, returned when `use_fov_model` is provided):
|
| 82 |
+
Field of View Scaler.
|
| 83 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 84 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 85 |
+
one for the output of each layer) of shape `(batch_size, n_patches_per_batch, sequence_length, hidden_size)`.
|
| 86 |
+
|
| 87 |
+
Hidden-states of the model at the output of each layer and the optional initial embedding outputs.
|
| 88 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 89 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, n_patches_per_batch, num_heads, sequence_length,
|
| 90 |
+
sequence_length)`.
|
| 91 |
+
|
| 92 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 93 |
+
heads.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
loss: Optional[torch.FloatTensor] = None
|
| 97 |
+
predicted_depth: torch.FloatTensor = None
|
| 98 |
+
field_of_view: Optional[torch.FloatTensor] = None
|
| 99 |
+
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 100 |
+
attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def split_to_patches(pixel_values: torch.Tensor, patch_size: int, overlap_ratio: float) -> torch.Tensor:
|
| 104 |
+
"""Creates Patches from Batch."""
|
| 105 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 106 |
+
|
| 107 |
+
if height == width == patch_size:
|
| 108 |
+
# create patches only if scaled image is not already equal to patch size
|
| 109 |
+
return pixel_values
|
| 110 |
+
|
| 111 |
+
stride = torch_int(patch_size * (1 - overlap_ratio))
|
| 112 |
+
|
| 113 |
+
patches = F.unfold(pixel_values, kernel_size=(patch_size, patch_size), stride=(stride, stride))
|
| 114 |
+
patches = patches.permute(2, 0, 1)
|
| 115 |
+
patches = patches.reshape(-1, num_channels, patch_size, patch_size)
|
| 116 |
+
|
| 117 |
+
return patches
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def reshape_features(hidden_states: torch.Tensor) -> torch.Tensor:
|
| 121 |
+
"""Discard class token and reshape 1D feature map to a 2D grid."""
|
| 122 |
+
n_samples, seq_len, hidden_size = hidden_states.shape
|
| 123 |
+
size = torch_int(seq_len**0.5)
|
| 124 |
+
|
| 125 |
+
hidden_states = hidden_states[:, -(size**2) :, :] # remove special tokens if there are any
|
| 126 |
+
hidden_states = hidden_states.reshape(n_samples, size, size, hidden_size)
|
| 127 |
+
hidden_states = hidden_states.permute(0, 3, 1, 2)
|
| 128 |
+
|
| 129 |
+
return hidden_states
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def merge_patches(patches: torch.Tensor, batch_size: int, padding: int) -> torch.Tensor:
|
| 133 |
+
"""Merges smaller patches into image-like feature map."""
|
| 134 |
+
n_patches, hidden_size, out_size, out_size = patches.shape
|
| 135 |
+
n_patches_per_batch = n_patches // batch_size
|
| 136 |
+
sqrt_n_patches_per_batch = torch_int(n_patches_per_batch**0.5)
|
| 137 |
+
new_out_size = sqrt_n_patches_per_batch * out_size
|
| 138 |
+
|
| 139 |
+
if n_patches == batch_size:
|
| 140 |
+
# merge only if the patches were created from scaled image
|
| 141 |
+
# patches are not created when scaled image size is equal to patch size
|
| 142 |
+
return patches
|
| 143 |
+
|
| 144 |
+
if n_patches_per_batch < 4:
|
| 145 |
+
# for each batch, atleast 4 small patches are required to
|
| 146 |
+
# recreate a large square patch from merging them and later padding is applied
|
| 147 |
+
# 3 x (8x8) patches becomes 1 x ( 8x8 ) patch (extra patch ignored, no padding)
|
| 148 |
+
# 4 x (8x8) patches becomes 1 x (16x16) patch (padding later)
|
| 149 |
+
# 5 x (8x8) patches becomes 1 x (16x16) patch (extra patch ignored, padding later)
|
| 150 |
+
# 9 x (8x8) patches becomes 1 x (24x24) patch (padding later)
|
| 151 |
+
# thus the following code only rearranges the patches and removes extra ones
|
| 152 |
+
padding = 0
|
| 153 |
+
|
| 154 |
+
# make sure padding is not large enough to remove more than half of the patch
|
| 155 |
+
padding = min(out_size // 4, padding)
|
| 156 |
+
|
| 157 |
+
if padding == 0:
|
| 158 |
+
# faster when no padding is required
|
| 159 |
+
merged = patches.reshape(n_patches_per_batch, batch_size, hidden_size, out_size, out_size)
|
| 160 |
+
merged = merged.permute(1, 2, 0, 3, 4)
|
| 161 |
+
merged = merged[:, :, : sqrt_n_patches_per_batch**2, :, :]
|
| 162 |
+
merged = merged.reshape(
|
| 163 |
+
batch_size, hidden_size, sqrt_n_patches_per_batch, sqrt_n_patches_per_batch, out_size, out_size
|
| 164 |
+
)
|
| 165 |
+
merged = merged.permute(0, 1, 2, 4, 3, 5)
|
| 166 |
+
merged = merged.reshape(batch_size, hidden_size, new_out_size, new_out_size)
|
| 167 |
+
else:
|
| 168 |
+
# padding example:
|
| 169 |
+
# let out_size = 8, new_out_size = 32, padding = 2
|
| 170 |
+
# each patch is separated by "|"
|
| 171 |
+
# and padding is applied to the merging edges of each patch
|
| 172 |
+
# 00 01 02 03 04 05 06 07 | 08 09 10 11 12 13 14 15 | 16 17 18 19 20 21 22 23 | 24 25 26 27 28 29 30 31
|
| 173 |
+
# 00 01 02 03 04 05 -- -- | -- -- 10 11 12 13 -- -- | -- -- 18 19 20 21 -- -- | -- -- 26 27 28 29 30 31
|
| 174 |
+
i = 0
|
| 175 |
+
boxes = []
|
| 176 |
+
for h in range(sqrt_n_patches_per_batch):
|
| 177 |
+
boxes_in_row = []
|
| 178 |
+
for w in range(sqrt_n_patches_per_batch):
|
| 179 |
+
box = patches[batch_size * i : batch_size * (i + 1)]
|
| 180 |
+
|
| 181 |
+
# collect paddings
|
| 182 |
+
paddings = [0, 0, 0, 0]
|
| 183 |
+
if h != 0:
|
| 184 |
+
# remove pad from height if box is not at top border
|
| 185 |
+
paddings[0] = padding
|
| 186 |
+
if w != 0:
|
| 187 |
+
# remove pad from width if box is not at left border
|
| 188 |
+
paddings[2] = padding
|
| 189 |
+
if h != sqrt_n_patches_per_batch - 1:
|
| 190 |
+
# remove pad from height if box is not at bottom border
|
| 191 |
+
paddings[1] = padding
|
| 192 |
+
if w != sqrt_n_patches_per_batch - 1:
|
| 193 |
+
# remove pad from width if box is not at right border
|
| 194 |
+
paddings[3] = padding
|
| 195 |
+
|
| 196 |
+
# remove paddings
|
| 197 |
+
_, _, box_h, box_w = box.shape
|
| 198 |
+
pad_top, pad_bottom, pad_left, pad_right = paddings
|
| 199 |
+
box = box[:, :, pad_top : box_h - pad_bottom, pad_left : box_w - pad_right]
|
| 200 |
+
|
| 201 |
+
boxes_in_row.append(box)
|
| 202 |
+
i += 1
|
| 203 |
+
boxes_in_row = torch.cat(boxes_in_row, dim=-1)
|
| 204 |
+
boxes.append(boxes_in_row)
|
| 205 |
+
merged = torch.cat(boxes, dim=-2)
|
| 206 |
+
|
| 207 |
+
return merged
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def reconstruct_feature_maps(
|
| 211 |
+
hidden_state: torch.Tensor, batch_size: int, padding: int, output_size: Tuple[float, float]
|
| 212 |
+
) -> torch.Tensor:
|
| 213 |
+
"""
|
| 214 |
+
Reconstructs feature maps from the hidden state produced by any of the encoder. Converts the hidden state of shape
|
| 215 |
+
`(n_patches_per_batch * batch_size, seq_len, hidden_size)` to feature maps of shape
|
| 216 |
+
`(batch_size, hidden_size, output_size[0], output_size[1])`.
|
| 217 |
+
|
| 218 |
+
Args:
|
| 219 |
+
hidden_state (torch.Tensor): Input tensor of shape `(n_patches_per_batch * batch_size, seq_len, hidden_size)`
|
| 220 |
+
representing the encoded patches.
|
| 221 |
+
batch_size (int): The number of samples in a batch.
|
| 222 |
+
padding (int): The amount of padding to be removed when merging patches.
|
| 223 |
+
output_size (Tuple[float, float]): The desired output size for the feature maps, specified as `(height, width)`.
|
| 224 |
+
|
| 225 |
+
Returns:
|
| 226 |
+
torch.Tensor: Reconstructed feature maps of shape `(batch_size, hidden_size, output_size[0], output_size[1])`.
|
| 227 |
+
"""
|
| 228 |
+
# reshape back to image like
|
| 229 |
+
features = reshape_features(hidden_state)
|
| 230 |
+
|
| 231 |
+
# merge all patches in a batch to create one large patch per batch
|
| 232 |
+
features = merge_patches(
|
| 233 |
+
features,
|
| 234 |
+
batch_size=batch_size,
|
| 235 |
+
padding=padding,
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
# interpolate patches to base size
|
| 239 |
+
features = F.interpolate(
|
| 240 |
+
features,
|
| 241 |
+
size=output_size,
|
| 242 |
+
mode="bilinear",
|
| 243 |
+
align_corners=False,
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
return features
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
class DepthProPatchEncoder(nn.Module):
|
| 250 |
+
def __init__(self, config: DepthProConfig):
|
| 251 |
+
super().__init__()
|
| 252 |
+
self.config = config
|
| 253 |
+
|
| 254 |
+
self.intermediate_hook_ids = config.intermediate_hook_ids
|
| 255 |
+
self.intermediate_feature_dims = config.intermediate_feature_dims
|
| 256 |
+
self.scaled_images_ratios = config.scaled_images_ratios
|
| 257 |
+
self.scaled_images_overlap_ratios = config.scaled_images_overlap_ratios
|
| 258 |
+
self.scaled_images_feature_dims = config.scaled_images_feature_dims
|
| 259 |
+
self.merge_padding_value = config.merge_padding_value
|
| 260 |
+
|
| 261 |
+
self.n_scaled_images = len(config.scaled_images_ratios)
|
| 262 |
+
self.n_intermediate_hooks = len(config.intermediate_hook_ids)
|
| 263 |
+
self.out_size = config.image_model_config.image_size // config.image_model_config.patch_size
|
| 264 |
+
|
| 265 |
+
self.model = AutoModel.from_config(config.patch_model_config)
|
| 266 |
+
|
| 267 |
+
def forward(
|
| 268 |
+
self,
|
| 269 |
+
pixel_values: torch.Tensor,
|
| 270 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 271 |
+
) -> List[torch.Tensor]:
|
| 272 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 273 |
+
|
| 274 |
+
if min(self.scaled_images_ratios) * min(height, width) < self.config.patch_size:
|
| 275 |
+
raise ValueError(
|
| 276 |
+
f"Image size {height}x{width} is too small to be scaled "
|
| 277 |
+
f"with scaled_images_ratios={self.scaled_images_ratios} "
|
| 278 |
+
f"when patch_size={self.config.patch_size}."
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
# STEP 1: create 3-level image
|
| 282 |
+
|
| 283 |
+
scaled_images = []
|
| 284 |
+
for ratio in self.scaled_images_ratios:
|
| 285 |
+
scaled_images.append(
|
| 286 |
+
F.interpolate(
|
| 287 |
+
pixel_values,
|
| 288 |
+
scale_factor=ratio,
|
| 289 |
+
mode="bilinear",
|
| 290 |
+
align_corners=False,
|
| 291 |
+
)
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
# STEP 2: create patches
|
| 295 |
+
|
| 296 |
+
for i in range(self.n_scaled_images):
|
| 297 |
+
scaled_images[i] = split_to_patches(
|
| 298 |
+
scaled_images[i],
|
| 299 |
+
patch_size=self.config.patch_size,
|
| 300 |
+
overlap_ratio=self.scaled_images_overlap_ratios[i],
|
| 301 |
+
)
|
| 302 |
+
n_patches_per_scaled_image = [len(i) for i in scaled_images]
|
| 303 |
+
patches = torch.cat(scaled_images[::-1], dim=0) # -1 as patch encoder expects high res patches first
|
| 304 |
+
|
| 305 |
+
# STEP 3: apply patch encoder
|
| 306 |
+
|
| 307 |
+
encodings = self.model(
|
| 308 |
+
# each patch is processed as a separate batch
|
| 309 |
+
patches,
|
| 310 |
+
head_mask=head_mask,
|
| 311 |
+
# required for intermediate features
|
| 312 |
+
output_hidden_states=self.n_intermediate_hooks > 0,
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
scaled_images_last_hidden_state = torch.split_with_sizes(encodings[0], n_patches_per_scaled_image[::-1])
|
| 316 |
+
# -1 (reverse list) as patch encoder returns high res patches first, we need low res first
|
| 317 |
+
scaled_images_last_hidden_state = scaled_images_last_hidden_state[::-1]
|
| 318 |
+
|
| 319 |
+
# calculate base height and width
|
| 320 |
+
# base height and width are the dimensions of the lowest resolution features
|
| 321 |
+
exponent_value = torch_int(math.log2(width / self.out_size))
|
| 322 |
+
base_height = height // 2**exponent_value
|
| 323 |
+
base_width = width // 2**exponent_value
|
| 324 |
+
|
| 325 |
+
# STEP 4: get patch features (high_res, med_res, low_res) - (3-5) in diagram
|
| 326 |
+
|
| 327 |
+
scaled_images_features = []
|
| 328 |
+
for i in range(self.n_scaled_images):
|
| 329 |
+
hidden_state = scaled_images_last_hidden_state[i]
|
| 330 |
+
batch_size = batch_size
|
| 331 |
+
padding = torch_int(self.merge_padding_value * (1 / self.scaled_images_ratios[i]))
|
| 332 |
+
output_height = base_height * 2**i
|
| 333 |
+
output_width = base_width * 2**i
|
| 334 |
+
features = reconstruct_feature_maps(
|
| 335 |
+
hidden_state,
|
| 336 |
+
batch_size=batch_size,
|
| 337 |
+
padding=padding,
|
| 338 |
+
output_size=(output_height, output_width),
|
| 339 |
+
)
|
| 340 |
+
scaled_images_features.append(features)
|
| 341 |
+
|
| 342 |
+
# STEP 5: get intermediate features - (1-2) in diagram
|
| 343 |
+
|
| 344 |
+
intermediate_features = []
|
| 345 |
+
for i in range(self.n_intermediate_hooks):
|
| 346 |
+
# +1 to correct index position as hidden_states contain embedding output as well
|
| 347 |
+
hidden_state = encodings[2][self.intermediate_hook_ids[i] + 1]
|
| 348 |
+
padding = torch_int(self.merge_padding_value * (1 / self.scaled_images_ratios[-1]))
|
| 349 |
+
output_height = base_height * 2 ** (self.n_scaled_images - 1)
|
| 350 |
+
output_width = base_width * 2 ** (self.n_scaled_images - 1)
|
| 351 |
+
features = reconstruct_feature_maps(
|
| 352 |
+
hidden_state,
|
| 353 |
+
batch_size=batch_size,
|
| 354 |
+
padding=padding,
|
| 355 |
+
output_size=(output_height, output_width),
|
| 356 |
+
)
|
| 357 |
+
intermediate_features.append(features)
|
| 358 |
+
|
| 359 |
+
# STEP 7: combine all features
|
| 360 |
+
features = [*scaled_images_features, *intermediate_features]
|
| 361 |
+
|
| 362 |
+
return features
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
class DepthProImageEncoder(nn.Module):
|
| 366 |
+
def __init__(self, config: DepthProConfig):
|
| 367 |
+
super().__init__()
|
| 368 |
+
self.config = config
|
| 369 |
+
self.out_size = config.image_model_config.image_size // config.image_model_config.patch_size
|
| 370 |
+
|
| 371 |
+
self.model = AutoModel.from_config(config.image_model_config)
|
| 372 |
+
|
| 373 |
+
def forward(
|
| 374 |
+
self,
|
| 375 |
+
pixel_values: torch.Tensor,
|
| 376 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 377 |
+
output_attentions: bool = False,
|
| 378 |
+
output_hidden_states: bool = False,
|
| 379 |
+
return_dict: bool = True,
|
| 380 |
+
) -> Union[tuple, DepthProOutput]:
|
| 381 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 382 |
+
|
| 383 |
+
# scale the image for image_encoder
|
| 384 |
+
size = self.config.image_model_config.image_size
|
| 385 |
+
pixel_values = F.interpolate(
|
| 386 |
+
pixel_values,
|
| 387 |
+
size=(size, size),
|
| 388 |
+
mode="bilinear",
|
| 389 |
+
align_corners=False,
|
| 390 |
+
)
|
| 391 |
+
encodings = self.model(
|
| 392 |
+
pixel_values=pixel_values,
|
| 393 |
+
head_mask=head_mask,
|
| 394 |
+
output_attentions=output_attentions,
|
| 395 |
+
output_hidden_states=output_hidden_states,
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
# calculate base height and width
|
| 399 |
+
# base height and width are the dimensions of the lowest resolution features
|
| 400 |
+
exponent_value = torch_int(math.log2(width / self.out_size))
|
| 401 |
+
base_height = height // 2**exponent_value
|
| 402 |
+
base_width = width // 2**exponent_value
|
| 403 |
+
|
| 404 |
+
features = reconstruct_feature_maps(
|
| 405 |
+
encodings[0],
|
| 406 |
+
batch_size=batch_size,
|
| 407 |
+
padding=0,
|
| 408 |
+
output_size=(base_height, base_width),
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
if not return_dict:
|
| 412 |
+
return (encodings[0], features) + encodings[2:] # ignore last_hidden_state and poooler output
|
| 413 |
+
|
| 414 |
+
return DepthProOutput(
|
| 415 |
+
last_hidden_state=encodings.last_hidden_state,
|
| 416 |
+
features=features,
|
| 417 |
+
hidden_states=encodings.hidden_states,
|
| 418 |
+
attentions=encodings.attentions,
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
class DepthProEncoder(nn.Module):
|
| 423 |
+
def __init__(self, config: DepthProConfig):
|
| 424 |
+
super().__init__()
|
| 425 |
+
self.config = config
|
| 426 |
+
self.intermediate_hook_ids = config.intermediate_hook_ids
|
| 427 |
+
self.intermediate_feature_dims = config.intermediate_feature_dims
|
| 428 |
+
self.scaled_images_ratios = config.scaled_images_ratios
|
| 429 |
+
self.scaled_images_overlap_ratios = config.scaled_images_overlap_ratios
|
| 430 |
+
self.scaled_images_feature_dims = config.scaled_images_feature_dims
|
| 431 |
+
self.merge_padding_value = config.merge_padding_value
|
| 432 |
+
|
| 433 |
+
self.n_scaled_images = len(self.scaled_images_ratios)
|
| 434 |
+
self.n_intermediate_hooks = len(self.intermediate_hook_ids)
|
| 435 |
+
|
| 436 |
+
self.patch_encoder = DepthProPatchEncoder(config)
|
| 437 |
+
self.image_encoder = DepthProImageEncoder(config)
|
| 438 |
+
|
| 439 |
+
def forward(
|
| 440 |
+
self,
|
| 441 |
+
pixel_values: torch.Tensor,
|
| 442 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 443 |
+
output_attentions: bool = False,
|
| 444 |
+
output_hidden_states: bool = False,
|
| 445 |
+
return_dict: bool = True,
|
| 446 |
+
) -> Union[tuple, DepthProOutput]:
|
| 447 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 448 |
+
|
| 449 |
+
patch_features = self.patch_encoder(
|
| 450 |
+
pixel_values,
|
| 451 |
+
head_mask=head_mask,
|
| 452 |
+
)
|
| 453 |
+
image_encodings = self.image_encoder(
|
| 454 |
+
pixel_values,
|
| 455 |
+
head_mask=head_mask,
|
| 456 |
+
output_attentions=output_attentions,
|
| 457 |
+
output_hidden_states=output_hidden_states,
|
| 458 |
+
return_dict=return_dict,
|
| 459 |
+
)
|
| 460 |
+
image_features = image_encodings[1] # index 1 contains features
|
| 461 |
+
|
| 462 |
+
features = [image_features, *patch_features]
|
| 463 |
+
|
| 464 |
+
if not return_dict:
|
| 465 |
+
return (image_encodings[0], features) + image_encodings[2:]
|
| 466 |
+
|
| 467 |
+
return DepthProOutput(
|
| 468 |
+
last_hidden_state=image_encodings.last_hidden_state,
|
| 469 |
+
features=features,
|
| 470 |
+
hidden_states=image_encodings.hidden_states,
|
| 471 |
+
attentions=image_encodings.attentions,
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
class DepthProFeatureUpsampleBlock(nn.Module):
|
| 476 |
+
def __init__(
|
| 477 |
+
self,
|
| 478 |
+
config: DepthProConfig,
|
| 479 |
+
input_dims: int,
|
| 480 |
+
intermediate_dims: int,
|
| 481 |
+
output_dims: int,
|
| 482 |
+
n_upsample_layers: int,
|
| 483 |
+
use_proj: bool = True,
|
| 484 |
+
bias: bool = False,
|
| 485 |
+
):
|
| 486 |
+
super().__init__()
|
| 487 |
+
self.config = config
|
| 488 |
+
self.layers = nn.ModuleList()
|
| 489 |
+
|
| 490 |
+
# create first projection layer
|
| 491 |
+
if use_proj:
|
| 492 |
+
proj = nn.Conv2d(
|
| 493 |
+
in_channels=input_dims,
|
| 494 |
+
out_channels=intermediate_dims,
|
| 495 |
+
kernel_size=1,
|
| 496 |
+
stride=1,
|
| 497 |
+
padding=0,
|
| 498 |
+
bias=bias,
|
| 499 |
+
)
|
| 500 |
+
self.layers.append(proj)
|
| 501 |
+
|
| 502 |
+
# create following upsample layers
|
| 503 |
+
for i in range(n_upsample_layers):
|
| 504 |
+
in_channels = intermediate_dims if i == 0 else output_dims
|
| 505 |
+
layer = nn.ConvTranspose2d(
|
| 506 |
+
in_channels=in_channels,
|
| 507 |
+
out_channels=output_dims,
|
| 508 |
+
kernel_size=2,
|
| 509 |
+
stride=2,
|
| 510 |
+
padding=0,
|
| 511 |
+
bias=bias,
|
| 512 |
+
)
|
| 513 |
+
self.layers.append(layer)
|
| 514 |
+
|
| 515 |
+
def forward(self, features: torch.Tensor) -> torch.Tensor:
|
| 516 |
+
for layer in self.layers:
|
| 517 |
+
features = layer(features)
|
| 518 |
+
return features
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
class DepthProFeatureUpsample(nn.Module):
|
| 522 |
+
def __init__(self, config: DepthProConfig):
|
| 523 |
+
super().__init__()
|
| 524 |
+
self.config = config
|
| 525 |
+
self.n_scaled_images = len(self.config.scaled_images_ratios)
|
| 526 |
+
self.n_intermediate_hooks = len(self.config.intermediate_hook_ids)
|
| 527 |
+
|
| 528 |
+
# for image_features
|
| 529 |
+
self.image_block = DepthProFeatureUpsampleBlock(
|
| 530 |
+
config=config,
|
| 531 |
+
input_dims=config.image_model_config.hidden_size,
|
| 532 |
+
intermediate_dims=config.image_model_config.hidden_size,
|
| 533 |
+
output_dims=config.scaled_images_feature_dims[0],
|
| 534 |
+
n_upsample_layers=1,
|
| 535 |
+
use_proj=False,
|
| 536 |
+
bias=True,
|
| 537 |
+
)
|
| 538 |
+
|
| 539 |
+
# for scaled_images_features
|
| 540 |
+
self.scaled_images = nn.ModuleList()
|
| 541 |
+
for i, feature_dims in enumerate(config.scaled_images_feature_dims):
|
| 542 |
+
block = DepthProFeatureUpsampleBlock(
|
| 543 |
+
config=config,
|
| 544 |
+
input_dims=config.patch_model_config.hidden_size,
|
| 545 |
+
intermediate_dims=feature_dims,
|
| 546 |
+
output_dims=feature_dims,
|
| 547 |
+
n_upsample_layers=1,
|
| 548 |
+
)
|
| 549 |
+
self.scaled_images.append(block)
|
| 550 |
+
|
| 551 |
+
# for intermediate_features
|
| 552 |
+
self.intermediate = nn.ModuleList()
|
| 553 |
+
for i, feature_dims in enumerate(config.intermediate_feature_dims):
|
| 554 |
+
intermediate_dims = config.fusion_hidden_size if i == 0 else feature_dims
|
| 555 |
+
block = DepthProFeatureUpsampleBlock(
|
| 556 |
+
config=config,
|
| 557 |
+
input_dims=config.patch_model_config.hidden_size,
|
| 558 |
+
intermediate_dims=intermediate_dims,
|
| 559 |
+
output_dims=feature_dims,
|
| 560 |
+
n_upsample_layers=2 + i,
|
| 561 |
+
)
|
| 562 |
+
self.intermediate.append(block)
|
| 563 |
+
|
| 564 |
+
def forward(self, features: List[torch.Tensor]) -> List[torch.Tensor]:
|
| 565 |
+
features[0] = self.image_block(features[0])
|
| 566 |
+
|
| 567 |
+
for i in range(self.n_scaled_images):
|
| 568 |
+
features[i + 1] = self.scaled_images[i](features[i + 1])
|
| 569 |
+
|
| 570 |
+
for i in range(self.n_intermediate_hooks):
|
| 571 |
+
features[self.n_scaled_images + i + 1] = self.intermediate[i](features[self.n_scaled_images + i + 1])
|
| 572 |
+
|
| 573 |
+
return features
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
class DepthProFeatureProjection(nn.Module):
|
| 577 |
+
def __init__(self, config: DepthProConfig):
|
| 578 |
+
super().__init__()
|
| 579 |
+
self.config = config
|
| 580 |
+
|
| 581 |
+
combined_feature_dims = config.scaled_images_feature_dims + config.intermediate_feature_dims
|
| 582 |
+
self.projections = nn.ModuleList()
|
| 583 |
+
for i, in_channels in enumerate(combined_feature_dims):
|
| 584 |
+
if i == len(combined_feature_dims) - 1 and in_channels == config.fusion_hidden_size:
|
| 585 |
+
# projection for last layer can be ignored if input and output channels already match
|
| 586 |
+
self.projections.append(nn.Identity())
|
| 587 |
+
else:
|
| 588 |
+
self.projections.append(
|
| 589 |
+
nn.Conv2d(
|
| 590 |
+
in_channels=in_channels,
|
| 591 |
+
out_channels=config.fusion_hidden_size,
|
| 592 |
+
kernel_size=3,
|
| 593 |
+
stride=1,
|
| 594 |
+
padding=1,
|
| 595 |
+
bias=False,
|
| 596 |
+
)
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
def forward(self, features: List[torch.Tensor]) -> List[torch.Tensor]:
|
| 600 |
+
projected_features = []
|
| 601 |
+
for i, projection in enumerate(self.projections):
|
| 602 |
+
upsampled_feature = projection(features[i])
|
| 603 |
+
projected_features.append(upsampled_feature)
|
| 604 |
+
return projected_features
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
class DepthProNeck(nn.Module):
|
| 608 |
+
def __init__(self, config: DepthProConfig):
|
| 609 |
+
super().__init__()
|
| 610 |
+
self.config = config
|
| 611 |
+
|
| 612 |
+
self.feature_upsample = DepthProFeatureUpsample(config)
|
| 613 |
+
self.fuse_image_with_low_res = nn.Conv2d(
|
| 614 |
+
in_channels=config.scaled_images_feature_dims[0] * 2,
|
| 615 |
+
out_channels=config.scaled_images_feature_dims[0],
|
| 616 |
+
kernel_size=1,
|
| 617 |
+
stride=1,
|
| 618 |
+
padding=0,
|
| 619 |
+
bias=True,
|
| 620 |
+
)
|
| 621 |
+
self.feature_projection = DepthProFeatureProjection(config)
|
| 622 |
+
|
| 623 |
+
def forward(self, features: List[torch.Tensor]) -> List[torch.Tensor]:
|
| 624 |
+
features = self.feature_upsample(features)
|
| 625 |
+
# global features = low res features + image features
|
| 626 |
+
global_features = torch.cat((features[1], features[0]), dim=1)
|
| 627 |
+
global_features = self.fuse_image_with_low_res(global_features)
|
| 628 |
+
features = [global_features, *features[2:]]
|
| 629 |
+
features = self.feature_projection(features)
|
| 630 |
+
return features
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
# General docstring
|
| 634 |
+
_CONFIG_FOR_DOC = "DepthProConfig"
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
DEPTH_PRO_START_DOCSTRING = r"""
|
| 638 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 639 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 640 |
+
behavior.
|
| 641 |
+
|
| 642 |
+
Parameters:
|
| 643 |
+
config ([`DepthProConfig`]): Model configuration class with all the parameters of the model.
|
| 644 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 645 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 646 |
+
"""
|
| 647 |
+
|
| 648 |
+
DEPTH_PRO_INPUTS_DOCSTRING = r"""
|
| 649 |
+
Args:
|
| 650 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 651 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`DPTImageProcessor.__call__`]
|
| 652 |
+
for details.
|
| 653 |
+
|
| 654 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 655 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 656 |
+
|
| 657 |
+
- 1 indicates the head is **not masked**,
|
| 658 |
+
- 0 indicates the head is **masked**.
|
| 659 |
+
|
| 660 |
+
output_attentions (`bool`, *optional*):
|
| 661 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 662 |
+
tensors for more detail.
|
| 663 |
+
output_hidden_states (`bool`, *optional*):
|
| 664 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 665 |
+
more detail.
|
| 666 |
+
return_dict (`bool`, *optional*):
|
| 667 |
+
Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
|
| 668 |
+
"""
|
| 669 |
+
|
| 670 |
+
DEPTH_PRO_FOR_DEPTH_ESTIMATION_START_DOCSTRING = r"""
|
| 671 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 672 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 673 |
+
behavior.
|
| 674 |
+
|
| 675 |
+
Parameters:
|
| 676 |
+
config ([`DepthProConfig`]): Model configuration class with all the parameters of the model.
|
| 677 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 678 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 679 |
+
use_fov_model (`bool`, *optional*, defaults to `True`):
|
| 680 |
+
Whether to use `DepthProFovModel` to generate the field of view.
|
| 681 |
+
"""
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
class DepthProPreTrainedModel(PreTrainedModel):
|
| 685 |
+
"""
|
| 686 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 687 |
+
models.
|
| 688 |
+
"""
|
| 689 |
+
|
| 690 |
+
config_class = DepthProConfig
|
| 691 |
+
base_model_prefix = "depth_pro"
|
| 692 |
+
main_input_name = "pixel_values"
|
| 693 |
+
supports_gradient_checkpointing = True
|
| 694 |
+
_supports_sdpa = True
|
| 695 |
+
_no_split_modules = ["DepthProPreActResidualLayer"]
|
| 696 |
+
_keys_to_ignore_on_load_unexpected = ["fov_model.*"]
|
| 697 |
+
|
| 698 |
+
def _init_weights(self, module):
|
| 699 |
+
"""Initialize the weights"""
|
| 700 |
+
if isinstance(module, nn.Linear):
|
| 701 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 702 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 703 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 704 |
+
if module.bias is not None:
|
| 705 |
+
module.bias.data.zero_()
|
| 706 |
+
elif isinstance(module, nn.LayerNorm):
|
| 707 |
+
module.bias.data.zero_()
|
| 708 |
+
module.weight.data.fill_(1.0)
|
| 709 |
+
elif isinstance(module, (nn.Conv2d, nn.ConvTranspose2d)):
|
| 710 |
+
nn.init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu")
|
| 711 |
+
if module.bias is not None:
|
| 712 |
+
module.bias.data.zero_()
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
@add_start_docstrings(
|
| 716 |
+
"The bare DepthPro Model transformer outputting raw hidden-states without any specific head on top.",
|
| 717 |
+
DEPTH_PRO_START_DOCSTRING,
|
| 718 |
+
)
|
| 719 |
+
class DepthProModel(DepthProPreTrainedModel):
|
| 720 |
+
def __init__(self, config):
|
| 721 |
+
super().__init__(config)
|
| 722 |
+
self.config = config
|
| 723 |
+
self.encoder = DepthProEncoder(config)
|
| 724 |
+
self.neck = DepthProNeck(config)
|
| 725 |
+
# Initialize weights and apply final processing
|
| 726 |
+
self.post_init()
|
| 727 |
+
|
| 728 |
+
def get_input_embeddings(self):
|
| 729 |
+
return self.encoder.image_encoder.model.get_input_embeddings()
|
| 730 |
+
|
| 731 |
+
@add_start_docstrings_to_model_forward(DEPTH_PRO_INPUTS_DOCSTRING)
|
| 732 |
+
@replace_return_docstrings(output_type=BaseModelOutput, config_class=_CONFIG_FOR_DOC)
|
| 733 |
+
def forward(
|
| 734 |
+
self,
|
| 735 |
+
pixel_values: torch.FloatTensor,
|
| 736 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 737 |
+
output_attentions: Optional[bool] = None,
|
| 738 |
+
output_hidden_states: Optional[bool] = None,
|
| 739 |
+
return_dict: Optional[bool] = None,
|
| 740 |
+
) -> Union[Tuple, DepthProOutput]:
|
| 741 |
+
r"""
|
| 742 |
+
Returns:
|
| 743 |
+
|
| 744 |
+
Examples:
|
| 745 |
+
|
| 746 |
+
```python
|
| 747 |
+
>>> import torch
|
| 748 |
+
>>> from PIL import Image
|
| 749 |
+
>>> import requests
|
| 750 |
+
>>> from transformers import AutoProcessor, DepthProModel
|
| 751 |
+
|
| 752 |
+
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
| 753 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 754 |
+
|
| 755 |
+
>>> checkpoint = "apple/DepthPro-hf"
|
| 756 |
+
>>> processor = AutoProcessor.from_pretrained(checkpoint)
|
| 757 |
+
>>> model = DepthProModel.from_pretrained(checkpoint)
|
| 758 |
+
|
| 759 |
+
>>> # prepare image for the model
|
| 760 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 761 |
+
|
| 762 |
+
>>> with torch.no_grad():
|
| 763 |
+
... output = model(**inputs)
|
| 764 |
+
|
| 765 |
+
>>> output.last_hidden_state.shape
|
| 766 |
+
torch.Size([1, 35, 577, 1024])
|
| 767 |
+
```"""
|
| 768 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 769 |
+
output_hidden_states = (
|
| 770 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 771 |
+
)
|
| 772 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 773 |
+
|
| 774 |
+
encodings = self.encoder(
|
| 775 |
+
pixel_values,
|
| 776 |
+
head_mask=head_mask,
|
| 777 |
+
output_attentions=output_attentions,
|
| 778 |
+
output_hidden_states=output_hidden_states,
|
| 779 |
+
return_dict=return_dict,
|
| 780 |
+
)
|
| 781 |
+
features = encodings[1] # index 1 contains features
|
| 782 |
+
features = self.neck(features)
|
| 783 |
+
|
| 784 |
+
if not return_dict:
|
| 785 |
+
return (encodings[0], features) + encodings[2:]
|
| 786 |
+
|
| 787 |
+
return DepthProOutput(
|
| 788 |
+
last_hidden_state=encodings.last_hidden_state,
|
| 789 |
+
features=features,
|
| 790 |
+
hidden_states=encodings.hidden_states,
|
| 791 |
+
attentions=encodings.attentions,
|
| 792 |
+
)
|
| 793 |
+
|
| 794 |
+
|
| 795 |
+
# Copied from transformers.models.dpt.modeling_dpt.DPTPreActResidualLayer DPT->DepthPro
|
| 796 |
+
class DepthProPreActResidualLayer(nn.Module):
|
| 797 |
+
"""
|
| 798 |
+
ResidualConvUnit, pre-activate residual unit.
|
| 799 |
+
|
| 800 |
+
Args:
|
| 801 |
+
config (`[DepthProConfig]`):
|
| 802 |
+
Model configuration class defining the model architecture.
|
| 803 |
+
"""
|
| 804 |
+
|
| 805 |
+
def __init__(self, config):
|
| 806 |
+
super().__init__()
|
| 807 |
+
|
| 808 |
+
self.use_batch_norm = config.use_batch_norm_in_fusion_residual
|
| 809 |
+
use_bias_in_fusion_residual = (
|
| 810 |
+
config.use_bias_in_fusion_residual
|
| 811 |
+
if config.use_bias_in_fusion_residual is not None
|
| 812 |
+
else not self.use_batch_norm
|
| 813 |
+
)
|
| 814 |
+
|
| 815 |
+
self.activation1 = nn.ReLU()
|
| 816 |
+
self.convolution1 = nn.Conv2d(
|
| 817 |
+
config.fusion_hidden_size,
|
| 818 |
+
config.fusion_hidden_size,
|
| 819 |
+
kernel_size=3,
|
| 820 |
+
stride=1,
|
| 821 |
+
padding=1,
|
| 822 |
+
bias=use_bias_in_fusion_residual,
|
| 823 |
+
)
|
| 824 |
+
|
| 825 |
+
self.activation2 = nn.ReLU()
|
| 826 |
+
self.convolution2 = nn.Conv2d(
|
| 827 |
+
config.fusion_hidden_size,
|
| 828 |
+
config.fusion_hidden_size,
|
| 829 |
+
kernel_size=3,
|
| 830 |
+
stride=1,
|
| 831 |
+
padding=1,
|
| 832 |
+
bias=use_bias_in_fusion_residual,
|
| 833 |
+
)
|
| 834 |
+
|
| 835 |
+
if self.use_batch_norm:
|
| 836 |
+
self.batch_norm1 = nn.BatchNorm2d(config.fusion_hidden_size)
|
| 837 |
+
self.batch_norm2 = nn.BatchNorm2d(config.fusion_hidden_size)
|
| 838 |
+
|
| 839 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 840 |
+
residual = hidden_state
|
| 841 |
+
hidden_state = self.activation1(hidden_state)
|
| 842 |
+
|
| 843 |
+
hidden_state = self.convolution1(hidden_state)
|
| 844 |
+
|
| 845 |
+
if self.use_batch_norm:
|
| 846 |
+
hidden_state = self.batch_norm1(hidden_state)
|
| 847 |
+
|
| 848 |
+
hidden_state = self.activation2(hidden_state)
|
| 849 |
+
hidden_state = self.convolution2(hidden_state)
|
| 850 |
+
|
| 851 |
+
if self.use_batch_norm:
|
| 852 |
+
hidden_state = self.batch_norm2(hidden_state)
|
| 853 |
+
|
| 854 |
+
return hidden_state + residual
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
# Modified from transformers.models.dpt.modeling_dpt.DPTFeatureFusionLayer
|
| 858 |
+
# except it uses deconv and skip_add and needs no interpolation
|
| 859 |
+
class DepthProFeatureFusionLayer(nn.Module):
|
| 860 |
+
def __init__(self, config: DepthProConfig, use_deconv: bool = True):
|
| 861 |
+
super().__init__()
|
| 862 |
+
self.config = config
|
| 863 |
+
self.use_deconv = use_deconv
|
| 864 |
+
|
| 865 |
+
self.residual_layer1 = DepthProPreActResidualLayer(config)
|
| 866 |
+
self.residual_layer2 = DepthProPreActResidualLayer(config)
|
| 867 |
+
|
| 868 |
+
if self.use_deconv:
|
| 869 |
+
self.deconv = nn.ConvTranspose2d(
|
| 870 |
+
in_channels=config.fusion_hidden_size,
|
| 871 |
+
out_channels=config.fusion_hidden_size,
|
| 872 |
+
kernel_size=2,
|
| 873 |
+
stride=2,
|
| 874 |
+
padding=0,
|
| 875 |
+
bias=False,
|
| 876 |
+
)
|
| 877 |
+
|
| 878 |
+
self.projection = nn.Conv2d(config.fusion_hidden_size, config.fusion_hidden_size, kernel_size=1, bias=True)
|
| 879 |
+
|
| 880 |
+
def forward(self, hidden_state: torch.Tensor, residual: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 881 |
+
if residual is not None:
|
| 882 |
+
residual = self.residual_layer1(residual)
|
| 883 |
+
hidden_state = hidden_state + residual
|
| 884 |
+
|
| 885 |
+
hidden_state = self.residual_layer2(hidden_state)
|
| 886 |
+
if self.use_deconv:
|
| 887 |
+
hidden_state = self.deconv(hidden_state)
|
| 888 |
+
hidden_state = self.projection(hidden_state)
|
| 889 |
+
|
| 890 |
+
return hidden_state
|
| 891 |
+
|
| 892 |
+
|
| 893 |
+
# Modified from transformers.models.dpt.modeling_dpt.DPTFeatureFusionStage with DPT->DepthPro
|
| 894 |
+
# with deconv and reversed layers
|
| 895 |
+
class DepthProFeatureFusionStage(nn.Module):
|
| 896 |
+
def __init__(self, config):
|
| 897 |
+
super().__init__()
|
| 898 |
+
self.config = config
|
| 899 |
+
|
| 900 |
+
self.num_layers = len(config.intermediate_hook_ids) + len(config.scaled_images_ratios)
|
| 901 |
+
self.intermediate = nn.ModuleList()
|
| 902 |
+
for _ in range(self.num_layers - 1):
|
| 903 |
+
self.intermediate.append(DepthProFeatureFusionLayer(config))
|
| 904 |
+
|
| 905 |
+
# final layer doesnot require deconvolution
|
| 906 |
+
self.final = DepthProFeatureFusionLayer(config, use_deconv=False)
|
| 907 |
+
|
| 908 |
+
def forward(self, hidden_states: List[torch.Tensor]) -> List[torch.Tensor]:
|
| 909 |
+
if self.num_layers != len(hidden_states):
|
| 910 |
+
raise ValueError(
|
| 911 |
+
f"num_layers={self.num_layers} in DepthProFeatureFusionStage"
|
| 912 |
+
f"doesnot match len(hidden_states)={len(hidden_states)}"
|
| 913 |
+
)
|
| 914 |
+
|
| 915 |
+
fused_hidden_states = []
|
| 916 |
+
fused_hidden_state = None
|
| 917 |
+
for hidden_state, layer in zip(hidden_states[:-1], self.intermediate):
|
| 918 |
+
if fused_hidden_state is None:
|
| 919 |
+
# first layer only uses the last hidden_state
|
| 920 |
+
fused_hidden_state = layer(hidden_state)
|
| 921 |
+
else:
|
| 922 |
+
fused_hidden_state = layer(fused_hidden_state, hidden_state)
|
| 923 |
+
fused_hidden_states.append(fused_hidden_state)
|
| 924 |
+
|
| 925 |
+
hidden_state = hidden_states[-1]
|
| 926 |
+
fused_hidden_state = self.final(fused_hidden_state, hidden_state)
|
| 927 |
+
fused_hidden_states.append(fused_hidden_state)
|
| 928 |
+
|
| 929 |
+
return fused_hidden_states
|
| 930 |
+
|
| 931 |
+
|
| 932 |
+
class DepthProFovEncoder(nn.Module):
|
| 933 |
+
def __init__(self, config: DepthProConfig):
|
| 934 |
+
super().__init__()
|
| 935 |
+
self.config = config
|
| 936 |
+
self.out_size = config.image_model_config.image_size // config.image_model_config.patch_size
|
| 937 |
+
|
| 938 |
+
self.model = AutoModel.from_config(config.fov_model_config)
|
| 939 |
+
self.neck = nn.Linear(config.fov_model_config.hidden_size, config.fusion_hidden_size // 2)
|
| 940 |
+
|
| 941 |
+
def forward(
|
| 942 |
+
self,
|
| 943 |
+
pixel_values: torch.Tensor,
|
| 944 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 945 |
+
) -> torch.Tensor:
|
| 946 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 947 |
+
|
| 948 |
+
# scale the image for fov_encoder
|
| 949 |
+
size = self.config.fov_model_config.image_size
|
| 950 |
+
pixel_values = F.interpolate(
|
| 951 |
+
pixel_values,
|
| 952 |
+
size=(size, size),
|
| 953 |
+
mode="bilinear",
|
| 954 |
+
align_corners=False,
|
| 955 |
+
)
|
| 956 |
+
encodings = self.model(
|
| 957 |
+
pixel_values=pixel_values,
|
| 958 |
+
head_mask=head_mask,
|
| 959 |
+
)
|
| 960 |
+
hidden_state = encodings[0]
|
| 961 |
+
hidden_state = self.neck(hidden_state)
|
| 962 |
+
|
| 963 |
+
# calculate base height and width
|
| 964 |
+
# base height and width are the dimensions of the lowest resolution features
|
| 965 |
+
exponent_value = torch_int(math.log2(width / self.out_size))
|
| 966 |
+
base_height = height // 2**exponent_value
|
| 967 |
+
base_width = width // 2**exponent_value
|
| 968 |
+
|
| 969 |
+
features = reconstruct_feature_maps(
|
| 970 |
+
hidden_state,
|
| 971 |
+
batch_size=batch_size,
|
| 972 |
+
padding=0,
|
| 973 |
+
output_size=(base_height, base_width),
|
| 974 |
+
)
|
| 975 |
+
|
| 976 |
+
return features
|
| 977 |
+
|
| 978 |
+
|
| 979 |
+
class DepthProFovHead(nn.Module):
|
| 980 |
+
def __init__(self, config: DepthProConfig):
|
| 981 |
+
super().__init__()
|
| 982 |
+
self.config = config
|
| 983 |
+
self.fusion_hidden_size = config.fusion_hidden_size
|
| 984 |
+
self.out_size = config.image_model_config.image_size // config.image_model_config.patch_size
|
| 985 |
+
|
| 986 |
+
# create initial head layers
|
| 987 |
+
self.layers = nn.ModuleList()
|
| 988 |
+
for i in range(config.num_fov_head_layers):
|
| 989 |
+
self.layers.append(
|
| 990 |
+
nn.Conv2d(
|
| 991 |
+
math.ceil(self.fusion_hidden_size / 2 ** (i + 1)),
|
| 992 |
+
math.ceil(self.fusion_hidden_size / 2 ** (i + 2)),
|
| 993 |
+
kernel_size=3,
|
| 994 |
+
stride=2,
|
| 995 |
+
padding=1,
|
| 996 |
+
)
|
| 997 |
+
)
|
| 998 |
+
self.layers.append(nn.ReLU(True))
|
| 999 |
+
# calculate expected shapes to finally generate a scalar output from final head layer
|
| 1000 |
+
final_in_channels = math.ceil(self.fusion_hidden_size / 2 ** (config.num_fov_head_layers + 1))
|
| 1001 |
+
final_kernel_size = torch_int((self.out_size - 1) / 2**config.num_fov_head_layers + 1)
|
| 1002 |
+
self.layers.append(
|
| 1003 |
+
nn.Conv2d(
|
| 1004 |
+
in_channels=final_in_channels, out_channels=1, kernel_size=final_kernel_size, stride=1, padding=0
|
| 1005 |
+
)
|
| 1006 |
+
)
|
| 1007 |
+
|
| 1008 |
+
def forward(self, features: torch.Tensor) -> torch.Tensor:
|
| 1009 |
+
features = F.interpolate(
|
| 1010 |
+
features,
|
| 1011 |
+
size=(self.out_size, self.out_size),
|
| 1012 |
+
mode="bilinear",
|
| 1013 |
+
align_corners=False,
|
| 1014 |
+
)
|
| 1015 |
+
for layer in self.layers:
|
| 1016 |
+
features = layer(features)
|
| 1017 |
+
return features
|
| 1018 |
+
|
| 1019 |
+
|
| 1020 |
+
class DepthProFovModel(nn.Module):
|
| 1021 |
+
def __init__(self, config: DepthProConfig):
|
| 1022 |
+
super().__init__()
|
| 1023 |
+
self.config = config
|
| 1024 |
+
self.fusion_hidden_size = config.fusion_hidden_size
|
| 1025 |
+
|
| 1026 |
+
self.fov_encoder = DepthProFovEncoder(config)
|
| 1027 |
+
self.conv = nn.Conv2d(
|
| 1028 |
+
self.fusion_hidden_size, self.fusion_hidden_size // 2, kernel_size=3, stride=2, padding=1
|
| 1029 |
+
)
|
| 1030 |
+
self.activation = nn.ReLU(inplace=True)
|
| 1031 |
+
self.head = DepthProFovHead(config)
|
| 1032 |
+
|
| 1033 |
+
def forward(
|
| 1034 |
+
self,
|
| 1035 |
+
pixel_values: torch.Tensor,
|
| 1036 |
+
global_features: torch.Tensor,
|
| 1037 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1038 |
+
) -> torch.Tensor:
|
| 1039 |
+
fov_features = self.fov_encoder(pixel_values, head_mask)
|
| 1040 |
+
|
| 1041 |
+
global_features = self.conv(global_features)
|
| 1042 |
+
global_features = self.activation(global_features)
|
| 1043 |
+
|
| 1044 |
+
fov_features = fov_features + global_features
|
| 1045 |
+
fov_output = self.head(fov_features)
|
| 1046 |
+
fov_output = fov_output.flatten()
|
| 1047 |
+
|
| 1048 |
+
return fov_output
|
| 1049 |
+
|
| 1050 |
+
|
| 1051 |
+
class DepthProDepthEstimationHead(nn.Module):
|
| 1052 |
+
"""
|
| 1053 |
+
The DepthProDepthEstimationHead module serves as the output head for depth estimation tasks.
|
| 1054 |
+
This module comprises a sequence of convolutional and transposed convolutional layers
|
| 1055 |
+
that process the feature map from the fusion to produce a single-channel depth map.
|
| 1056 |
+
Key operations include dimensionality reduction and upsampling to match the input resolution.
|
| 1057 |
+
"""
|
| 1058 |
+
|
| 1059 |
+
def __init__(self, config):
|
| 1060 |
+
super().__init__()
|
| 1061 |
+
self.config = config
|
| 1062 |
+
|
| 1063 |
+
features = config.fusion_hidden_size
|
| 1064 |
+
self.layers = nn.ModuleList(
|
| 1065 |
+
[
|
| 1066 |
+
nn.Conv2d(features, features // 2, kernel_size=3, stride=1, padding=1),
|
| 1067 |
+
nn.ConvTranspose2d(
|
| 1068 |
+
in_channels=features // 2,
|
| 1069 |
+
out_channels=features // 2,
|
| 1070 |
+
kernel_size=2,
|
| 1071 |
+
stride=2,
|
| 1072 |
+
padding=0,
|
| 1073 |
+
bias=True,
|
| 1074 |
+
),
|
| 1075 |
+
nn.Conv2d(features // 2, 32, kernel_size=3, stride=1, padding=1),
|
| 1076 |
+
nn.ReLU(True),
|
| 1077 |
+
nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0),
|
| 1078 |
+
nn.ReLU(),
|
| 1079 |
+
]
|
| 1080 |
+
)
|
| 1081 |
+
|
| 1082 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 1083 |
+
for layer in self.layers:
|
| 1084 |
+
hidden_states = layer(hidden_states)
|
| 1085 |
+
|
| 1086 |
+
predicted_depth = hidden_states.squeeze(dim=1)
|
| 1087 |
+
return predicted_depth
|
| 1088 |
+
|
| 1089 |
+
|
| 1090 |
+
@add_start_docstrings(
|
| 1091 |
+
"""
|
| 1092 |
+
DepthPro Model with a depth estimation head on top (consisting of 3 convolutional layers).
|
| 1093 |
+
""",
|
| 1094 |
+
DEPTH_PRO_FOR_DEPTH_ESTIMATION_START_DOCSTRING,
|
| 1095 |
+
)
|
| 1096 |
+
class DepthProForDepthEstimation(DepthProPreTrainedModel):
|
| 1097 |
+
def __init__(self, config, use_fov_model=None):
|
| 1098 |
+
super().__init__(config)
|
| 1099 |
+
self.config = config
|
| 1100 |
+
self.use_fov_model = use_fov_model if use_fov_model is not None else self.config.use_fov_model
|
| 1101 |
+
|
| 1102 |
+
# dinov2 (vit) like encoders
|
| 1103 |
+
self.depth_pro = DepthProModel(config)
|
| 1104 |
+
|
| 1105 |
+
# dpt (vit) like fusion stage
|
| 1106 |
+
self.fusion_stage = DepthProFeatureFusionStage(config)
|
| 1107 |
+
|
| 1108 |
+
# depth estimation head
|
| 1109 |
+
self.head = DepthProDepthEstimationHead(config)
|
| 1110 |
+
|
| 1111 |
+
# dinov2 (vit) like encoder
|
| 1112 |
+
self.fov_model = DepthProFovModel(config) if self.use_fov_model else None
|
| 1113 |
+
|
| 1114 |
+
# Initialize weights and apply final processing
|
| 1115 |
+
self.post_init()
|
| 1116 |
+
|
| 1117 |
+
@add_start_docstrings_to_model_forward(DEPTH_PRO_INPUTS_DOCSTRING)
|
| 1118 |
+
@replace_return_docstrings(output_type=DepthProDepthEstimatorOutput, config_class=_CONFIG_FOR_DOC)
|
| 1119 |
+
def forward(
|
| 1120 |
+
self,
|
| 1121 |
+
pixel_values: torch.FloatTensor,
|
| 1122 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1123 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1124 |
+
output_attentions: Optional[bool] = None,
|
| 1125 |
+
output_hidden_states: Optional[bool] = None,
|
| 1126 |
+
return_dict: Optional[bool] = None,
|
| 1127 |
+
) -> Union[Tuple[torch.Tensor], DepthProDepthEstimatorOutput]:
|
| 1128 |
+
r"""
|
| 1129 |
+
labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
|
| 1130 |
+
Ground truth depth estimation maps for computing the loss.
|
| 1131 |
+
|
| 1132 |
+
Returns:
|
| 1133 |
+
|
| 1134 |
+
Examples:
|
| 1135 |
+
|
| 1136 |
+
```python
|
| 1137 |
+
>>> from transformers import AutoImageProcessor, DepthProForDepthEstimation
|
| 1138 |
+
>>> import torch
|
| 1139 |
+
>>> from PIL import Image
|
| 1140 |
+
>>> import requests
|
| 1141 |
+
|
| 1142 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1143 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1144 |
+
|
| 1145 |
+
>>> checkpoint = "apple/DepthPro-hf"
|
| 1146 |
+
>>> processor = AutoImageProcessor.from_pretrained(checkpoint)
|
| 1147 |
+
>>> model = DepthProForDepthEstimation.from_pretrained(checkpoint)
|
| 1148 |
+
|
| 1149 |
+
>>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 1150 |
+
>>> model.to(device)
|
| 1151 |
+
|
| 1152 |
+
>>> # prepare image for the model
|
| 1153 |
+
>>> inputs = processor(images=image, return_tensors="pt").to(device)
|
| 1154 |
+
|
| 1155 |
+
>>> with torch.no_grad():
|
| 1156 |
+
... outputs = model(**inputs)
|
| 1157 |
+
|
| 1158 |
+
>>> # interpolate to original size
|
| 1159 |
+
>>> post_processed_output = processor.post_process_depth_estimation(
|
| 1160 |
+
... outputs, target_sizes=[(image.height, image.width)],
|
| 1161 |
+
... )
|
| 1162 |
+
|
| 1163 |
+
>>> # get the field of view (fov) predictions
|
| 1164 |
+
>>> field_of_view = post_processed_output[0]["field_of_view"]
|
| 1165 |
+
>>> focal_length = post_processed_output[0]["focal_length"]
|
| 1166 |
+
|
| 1167 |
+
>>> # visualize the prediction
|
| 1168 |
+
>>> predicted_depth = post_processed_output[0]["predicted_depth"]
|
| 1169 |
+
>>> depth = predicted_depth * 255 / predicted_depth.max()
|
| 1170 |
+
>>> depth = depth.detach().cpu().numpy()
|
| 1171 |
+
>>> depth = Image.fromarray(depth.astype("uint8"))
|
| 1172 |
+
```"""
|
| 1173 |
+
loss = None
|
| 1174 |
+
if labels is not None:
|
| 1175 |
+
raise NotImplementedError("Training is not implemented yet")
|
| 1176 |
+
|
| 1177 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1178 |
+
output_hidden_states = (
|
| 1179 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1180 |
+
)
|
| 1181 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1182 |
+
|
| 1183 |
+
depth_pro_outputs = self.depth_pro(
|
| 1184 |
+
pixel_values=pixel_values,
|
| 1185 |
+
head_mask=head_mask,
|
| 1186 |
+
output_attentions=output_attentions,
|
| 1187 |
+
output_hidden_states=output_hidden_states,
|
| 1188 |
+
return_dict=True,
|
| 1189 |
+
)
|
| 1190 |
+
features = depth_pro_outputs.features
|
| 1191 |
+
fused_hidden_states = self.fusion_stage(features)
|
| 1192 |
+
predicted_depth = self.head(fused_hidden_states[-1])
|
| 1193 |
+
|
| 1194 |
+
if self.use_fov_model:
|
| 1195 |
+
# frozen features from encoder are used
|
| 1196 |
+
features_for_fov = features[0].detach()
|
| 1197 |
+
fov = self.fov_model(
|
| 1198 |
+
pixel_values=pixel_values,
|
| 1199 |
+
global_features=features_for_fov,
|
| 1200 |
+
head_mask=head_mask,
|
| 1201 |
+
)
|
| 1202 |
+
else:
|
| 1203 |
+
fov = None
|
| 1204 |
+
|
| 1205 |
+
if not return_dict:
|
| 1206 |
+
outputs = [loss, predicted_depth, fov, depth_pro_outputs.hidden_states, depth_pro_outputs.attentions]
|
| 1207 |
+
return tuple(v for v in outputs if v is not None)
|
| 1208 |
+
|
| 1209 |
+
return DepthProDepthEstimatorOutput(
|
| 1210 |
+
loss=loss,
|
| 1211 |
+
predicted_depth=predicted_depth,
|
| 1212 |
+
field_of_view=fov,
|
| 1213 |
+
hidden_states=depth_pro_outputs.hidden_states,
|
| 1214 |
+
attentions=depth_pro_outputs.attentions,
|
| 1215 |
+
)
|
| 1216 |
+
|
| 1217 |
+
|
| 1218 |
+
__all__ = ["DepthProPreTrainedModel", "DepthProModel", "DepthProForDepthEstimation"]
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/detr/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 15 |
+
from typing import TYPE_CHECKING
|
| 16 |
+
|
| 17 |
+
from ...utils import _LazyModule
|
| 18 |
+
from ...utils.import_utils import define_import_structure
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING:
|
| 22 |
+
from .configuration_detr import *
|
| 23 |
+
from .feature_extraction_detr import *
|
| 24 |
+
from .image_processing_detr import *
|
| 25 |
+
from .image_processing_detr_fast import *
|
| 26 |
+
from .modeling_detr import *
|
| 27 |
+
else:
|
| 28 |
+
import sys
|
| 29 |
+
|
| 30 |
+
_file = globals()["__file__"]
|
| 31 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/detr/configuration_detr.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 Facebook AI Research and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""DETR model configuration"""
|
| 16 |
+
|
| 17 |
+
from collections import OrderedDict
|
| 18 |
+
from typing import Mapping
|
| 19 |
+
|
| 20 |
+
from packaging import version
|
| 21 |
+
|
| 22 |
+
from ...configuration_utils import PretrainedConfig
|
| 23 |
+
from ...onnx import OnnxConfig
|
| 24 |
+
from ...utils import logging
|
| 25 |
+
from ...utils.backbone_utils import verify_backbone_config_arguments
|
| 26 |
+
from ..auto import CONFIG_MAPPING
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
logger = logging.get_logger(__name__)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class DetrConfig(PretrainedConfig):
|
| 33 |
+
r"""
|
| 34 |
+
This is the configuration class to store the configuration of a [`DetrModel`]. It is used to instantiate a DETR
|
| 35 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 36 |
+
defaults will yield a similar configuration to that of the DETR
|
| 37 |
+
[facebook/detr-resnet-50](https://huggingface.co/facebook/detr-resnet-50) architecture.
|
| 38 |
+
|
| 39 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 40 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
use_timm_backbone (`bool`, *optional*, defaults to `True`):
|
| 44 |
+
Whether or not to use the `timm` library for the backbone. If set to `False`, will use the [`AutoBackbone`]
|
| 45 |
+
API.
|
| 46 |
+
backbone_config (`PretrainedConfig` or `dict`, *optional*):
|
| 47 |
+
The configuration of the backbone model. Only used in case `use_timm_backbone` is set to `False` in which
|
| 48 |
+
case it will default to `ResNetConfig()`.
|
| 49 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 50 |
+
The number of input channels.
|
| 51 |
+
num_queries (`int`, *optional*, defaults to 100):
|
| 52 |
+
Number of object queries, i.e. detection slots. This is the maximal number of objects [`DetrModel`] can
|
| 53 |
+
detect in a single image. For COCO, we recommend 100 queries.
|
| 54 |
+
d_model (`int`, *optional*, defaults to 256):
|
| 55 |
+
This parameter is a general dimension parameter, defining dimensions for components such as the encoder layer and projection parameters in the decoder layer, among others.
|
| 56 |
+
encoder_layers (`int`, *optional*, defaults to 6):
|
| 57 |
+
Number of encoder layers.
|
| 58 |
+
decoder_layers (`int`, *optional*, defaults to 6):
|
| 59 |
+
Number of decoder layers.
|
| 60 |
+
encoder_attention_heads (`int`, *optional*, defaults to 8):
|
| 61 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 62 |
+
decoder_attention_heads (`int`, *optional*, defaults to 8):
|
| 63 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 64 |
+
decoder_ffn_dim (`int`, *optional*, defaults to 2048):
|
| 65 |
+
Dimension of the "intermediate" (often named feed-forward) layer in decoder.
|
| 66 |
+
encoder_ffn_dim (`int`, *optional*, defaults to 2048):
|
| 67 |
+
Dimension of the "intermediate" (often named feed-forward) layer in decoder.
|
| 68 |
+
activation_function (`str` or `function`, *optional*, defaults to `"relu"`):
|
| 69 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 70 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 71 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 72 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 73 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 74 |
+
The dropout ratio for the attention probabilities.
|
| 75 |
+
activation_dropout (`float`, *optional*, defaults to 0.0):
|
| 76 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 77 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 78 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 79 |
+
init_xavier_std (`float`, *optional*, defaults to 1):
|
| 80 |
+
The scaling factor used for the Xavier initialization gain in the HM Attention map module.
|
| 81 |
+
encoder_layerdrop (`float`, *optional*, defaults to 0.0):
|
| 82 |
+
The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
|
| 83 |
+
for more details.
|
| 84 |
+
decoder_layerdrop (`float`, *optional*, defaults to 0.0):
|
| 85 |
+
The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
|
| 86 |
+
for more details.
|
| 87 |
+
auxiliary_loss (`bool`, *optional*, defaults to `False`):
|
| 88 |
+
Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
|
| 89 |
+
position_embedding_type (`str`, *optional*, defaults to `"sine"`):
|
| 90 |
+
Type of position embeddings to be used on top of the image features. One of `"sine"` or `"learned"`.
|
| 91 |
+
backbone (`str`, *optional*, defaults to `"resnet50"`):
|
| 92 |
+
Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
|
| 93 |
+
will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
|
| 94 |
+
is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
|
| 95 |
+
use_pretrained_backbone (`bool`, *optional*, `True`):
|
| 96 |
+
Whether to use pretrained weights for the backbone.
|
| 97 |
+
backbone_kwargs (`dict`, *optional*):
|
| 98 |
+
Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
|
| 99 |
+
e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
|
| 100 |
+
dilation (`bool`, *optional*, defaults to `False`):
|
| 101 |
+
Whether to replace stride with dilation in the last convolutional block (DC5). Only supported when
|
| 102 |
+
`use_timm_backbone` = `True`.
|
| 103 |
+
class_cost (`float`, *optional*, defaults to 1):
|
| 104 |
+
Relative weight of the classification error in the Hungarian matching cost.
|
| 105 |
+
bbox_cost (`float`, *optional*, defaults to 5):
|
| 106 |
+
Relative weight of the L1 error of the bounding box coordinates in the Hungarian matching cost.
|
| 107 |
+
giou_cost (`float`, *optional*, defaults to 2):
|
| 108 |
+
Relative weight of the generalized IoU loss of the bounding box in the Hungarian matching cost.
|
| 109 |
+
mask_loss_coefficient (`float`, *optional*, defaults to 1):
|
| 110 |
+
Relative weight of the Focal loss in the panoptic segmentation loss.
|
| 111 |
+
dice_loss_coefficient (`float`, *optional*, defaults to 1):
|
| 112 |
+
Relative weight of the DICE/F-1 loss in the panoptic segmentation loss.
|
| 113 |
+
bbox_loss_coefficient (`float`, *optional*, defaults to 5):
|
| 114 |
+
Relative weight of the L1 bounding box loss in the object detection loss.
|
| 115 |
+
giou_loss_coefficient (`float`, *optional*, defaults to 2):
|
| 116 |
+
Relative weight of the generalized IoU loss in the object detection loss.
|
| 117 |
+
eos_coefficient (`float`, *optional*, defaults to 0.1):
|
| 118 |
+
Relative classification weight of the 'no-object' class in the object detection loss.
|
| 119 |
+
|
| 120 |
+
Examples:
|
| 121 |
+
|
| 122 |
+
```python
|
| 123 |
+
>>> from transformers import DetrConfig, DetrModel
|
| 124 |
+
|
| 125 |
+
>>> # Initializing a DETR facebook/detr-resnet-50 style configuration
|
| 126 |
+
>>> configuration = DetrConfig()
|
| 127 |
+
|
| 128 |
+
>>> # Initializing a model (with random weights) from the facebook/detr-resnet-50 style configuration
|
| 129 |
+
>>> model = DetrModel(configuration)
|
| 130 |
+
|
| 131 |
+
>>> # Accessing the model configuration
|
| 132 |
+
>>> configuration = model.config
|
| 133 |
+
```"""
|
| 134 |
+
|
| 135 |
+
model_type = "detr"
|
| 136 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 137 |
+
attribute_map = {
|
| 138 |
+
"hidden_size": "d_model",
|
| 139 |
+
"num_attention_heads": "encoder_attention_heads",
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
def __init__(
|
| 143 |
+
self,
|
| 144 |
+
use_timm_backbone=True,
|
| 145 |
+
backbone_config=None,
|
| 146 |
+
num_channels=3,
|
| 147 |
+
num_queries=100,
|
| 148 |
+
encoder_layers=6,
|
| 149 |
+
encoder_ffn_dim=2048,
|
| 150 |
+
encoder_attention_heads=8,
|
| 151 |
+
decoder_layers=6,
|
| 152 |
+
decoder_ffn_dim=2048,
|
| 153 |
+
decoder_attention_heads=8,
|
| 154 |
+
encoder_layerdrop=0.0,
|
| 155 |
+
decoder_layerdrop=0.0,
|
| 156 |
+
is_encoder_decoder=True,
|
| 157 |
+
activation_function="relu",
|
| 158 |
+
d_model=256,
|
| 159 |
+
dropout=0.1,
|
| 160 |
+
attention_dropout=0.0,
|
| 161 |
+
activation_dropout=0.0,
|
| 162 |
+
init_std=0.02,
|
| 163 |
+
init_xavier_std=1.0,
|
| 164 |
+
auxiliary_loss=False,
|
| 165 |
+
position_embedding_type="sine",
|
| 166 |
+
backbone="resnet50",
|
| 167 |
+
use_pretrained_backbone=True,
|
| 168 |
+
backbone_kwargs=None,
|
| 169 |
+
dilation=False,
|
| 170 |
+
class_cost=1,
|
| 171 |
+
bbox_cost=5,
|
| 172 |
+
giou_cost=2,
|
| 173 |
+
mask_loss_coefficient=1,
|
| 174 |
+
dice_loss_coefficient=1,
|
| 175 |
+
bbox_loss_coefficient=5,
|
| 176 |
+
giou_loss_coefficient=2,
|
| 177 |
+
eos_coefficient=0.1,
|
| 178 |
+
**kwargs,
|
| 179 |
+
):
|
| 180 |
+
# We default to values which were previously hard-coded in the model. This enables configurability of the config
|
| 181 |
+
# while keeping the default behavior the same.
|
| 182 |
+
if use_timm_backbone and backbone_kwargs is None:
|
| 183 |
+
backbone_kwargs = {}
|
| 184 |
+
if dilation:
|
| 185 |
+
backbone_kwargs["output_stride"] = 16
|
| 186 |
+
backbone_kwargs["out_indices"] = [1, 2, 3, 4]
|
| 187 |
+
backbone_kwargs["in_chans"] = num_channels
|
| 188 |
+
# Backwards compatibility
|
| 189 |
+
elif not use_timm_backbone and backbone in (None, "resnet50"):
|
| 190 |
+
if backbone_config is None:
|
| 191 |
+
logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.")
|
| 192 |
+
backbone_config = CONFIG_MAPPING["resnet"](out_features=["stage4"])
|
| 193 |
+
elif isinstance(backbone_config, dict):
|
| 194 |
+
backbone_model_type = backbone_config.get("model_type")
|
| 195 |
+
config_class = CONFIG_MAPPING[backbone_model_type]
|
| 196 |
+
backbone_config = config_class.from_dict(backbone_config)
|
| 197 |
+
backbone = None
|
| 198 |
+
# set timm attributes to None
|
| 199 |
+
dilation = None
|
| 200 |
+
|
| 201 |
+
verify_backbone_config_arguments(
|
| 202 |
+
use_timm_backbone=use_timm_backbone,
|
| 203 |
+
use_pretrained_backbone=use_pretrained_backbone,
|
| 204 |
+
backbone=backbone,
|
| 205 |
+
backbone_config=backbone_config,
|
| 206 |
+
backbone_kwargs=backbone_kwargs,
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
self.use_timm_backbone = use_timm_backbone
|
| 210 |
+
self.backbone_config = backbone_config
|
| 211 |
+
self.num_channels = num_channels
|
| 212 |
+
self.num_queries = num_queries
|
| 213 |
+
self.d_model = d_model
|
| 214 |
+
self.encoder_ffn_dim = encoder_ffn_dim
|
| 215 |
+
self.encoder_layers = encoder_layers
|
| 216 |
+
self.encoder_attention_heads = encoder_attention_heads
|
| 217 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 218 |
+
self.decoder_layers = decoder_layers
|
| 219 |
+
self.decoder_attention_heads = decoder_attention_heads
|
| 220 |
+
self.dropout = dropout
|
| 221 |
+
self.attention_dropout = attention_dropout
|
| 222 |
+
self.activation_dropout = activation_dropout
|
| 223 |
+
self.activation_function = activation_function
|
| 224 |
+
self.init_std = init_std
|
| 225 |
+
self.init_xavier_std = init_xavier_std
|
| 226 |
+
self.encoder_layerdrop = encoder_layerdrop
|
| 227 |
+
self.decoder_layerdrop = decoder_layerdrop
|
| 228 |
+
self.num_hidden_layers = encoder_layers
|
| 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.backbone_kwargs = backbone_kwargs
|
| 234 |
+
self.dilation = dilation
|
| 235 |
+
# Hungarian matcher
|
| 236 |
+
self.class_cost = class_cost
|
| 237 |
+
self.bbox_cost = bbox_cost
|
| 238 |
+
self.giou_cost = giou_cost
|
| 239 |
+
# Loss coefficients
|
| 240 |
+
self.mask_loss_coefficient = mask_loss_coefficient
|
| 241 |
+
self.dice_loss_coefficient = dice_loss_coefficient
|
| 242 |
+
self.bbox_loss_coefficient = bbox_loss_coefficient
|
| 243 |
+
self.giou_loss_coefficient = giou_loss_coefficient
|
| 244 |
+
self.eos_coefficient = eos_coefficient
|
| 245 |
+
super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)
|
| 246 |
+
|
| 247 |
+
@property
|
| 248 |
+
def num_attention_heads(self) -> int:
|
| 249 |
+
return self.encoder_attention_heads
|
| 250 |
+
|
| 251 |
+
@property
|
| 252 |
+
def hidden_size(self) -> int:
|
| 253 |
+
return self.d_model
|
| 254 |
+
|
| 255 |
+
@classmethod
|
| 256 |
+
def from_backbone_config(cls, backbone_config: PretrainedConfig, **kwargs):
|
| 257 |
+
"""Instantiate a [`DetrConfig`] (or a derived class) from a pre-trained backbone model configuration.
|
| 258 |
+
|
| 259 |
+
Args:
|
| 260 |
+
backbone_config ([`PretrainedConfig`]):
|
| 261 |
+
The backbone configuration.
|
| 262 |
+
Returns:
|
| 263 |
+
[`DetrConfig`]: An instance of a configuration object
|
| 264 |
+
"""
|
| 265 |
+
return cls(backbone_config=backbone_config, **kwargs)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
class DetrOnnxConfig(OnnxConfig):
|
| 269 |
+
torch_onnx_minimum_version = version.parse("1.11")
|
| 270 |
+
|
| 271 |
+
@property
|
| 272 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 273 |
+
return OrderedDict(
|
| 274 |
+
[
|
| 275 |
+
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
|
| 276 |
+
("pixel_mask", {0: "batch"}),
|
| 277 |
+
]
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
@property
|
| 281 |
+
def atol_for_validation(self) -> float:
|
| 282 |
+
return 1e-5
|
| 283 |
+
|
| 284 |
+
@property
|
| 285 |
+
def default_onnx_opset(self) -> int:
|
| 286 |
+
return 12
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
__all__ = ["DetrConfig",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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert DETR checkpoints with timm backbone."""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import json
|
| 19 |
+
from collections import OrderedDict
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import requests
|
| 23 |
+
import torch
|
| 24 |
+
from huggingface_hub import hf_hub_download
|
| 25 |
+
from PIL import Image
|
| 26 |
+
|
| 27 |
+
from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor
|
| 28 |
+
from transformers.utils import logging
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
logging.set_verbosity_info()
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
# here we list all keys to be renamed (original name on the left, our name on the right)
|
| 35 |
+
rename_keys = []
|
| 36 |
+
for i in range(6):
|
| 37 |
+
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
|
| 38 |
+
rename_keys.append(
|
| 39 |
+
(f"transformer.encoder.layers.{i}.self_attn.out_proj.weight", f"encoder.layers.{i}.self_attn.out_proj.weight")
|
| 40 |
+
)
|
| 41 |
+
rename_keys.append(
|
| 42 |
+
(f"transformer.encoder.layers.{i}.self_attn.out_proj.bias", f"encoder.layers.{i}.self_attn.out_proj.bias")
|
| 43 |
+
)
|
| 44 |
+
rename_keys.append((f"transformer.encoder.layers.{i}.linear1.weight", f"encoder.layers.{i}.fc1.weight"))
|
| 45 |
+
rename_keys.append((f"transformer.encoder.layers.{i}.linear1.bias", f"encoder.layers.{i}.fc1.bias"))
|
| 46 |
+
rename_keys.append((f"transformer.encoder.layers.{i}.linear2.weight", f"encoder.layers.{i}.fc2.weight"))
|
| 47 |
+
rename_keys.append((f"transformer.encoder.layers.{i}.linear2.bias", f"encoder.layers.{i}.fc2.bias"))
|
| 48 |
+
rename_keys.append(
|
| 49 |
+
(f"transformer.encoder.layers.{i}.norm1.weight", f"encoder.layers.{i}.self_attn_layer_norm.weight")
|
| 50 |
+
)
|
| 51 |
+
rename_keys.append((f"transformer.encoder.layers.{i}.norm1.bias", f"encoder.layers.{i}.self_attn_layer_norm.bias"))
|
| 52 |
+
rename_keys.append((f"transformer.encoder.layers.{i}.norm2.weight", f"encoder.layers.{i}.final_layer_norm.weight"))
|
| 53 |
+
rename_keys.append((f"transformer.encoder.layers.{i}.norm2.bias", f"encoder.layers.{i}.final_layer_norm.bias"))
|
| 54 |
+
# decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms
|
| 55 |
+
rename_keys.append(
|
| 56 |
+
(f"transformer.decoder.layers.{i}.self_attn.out_proj.weight", f"decoder.layers.{i}.self_attn.out_proj.weight")
|
| 57 |
+
)
|
| 58 |
+
rename_keys.append(
|
| 59 |
+
(f"transformer.decoder.layers.{i}.self_attn.out_proj.bias", f"decoder.layers.{i}.self_attn.out_proj.bias")
|
| 60 |
+
)
|
| 61 |
+
rename_keys.append(
|
| 62 |
+
(
|
| 63 |
+
f"transformer.decoder.layers.{i}.multihead_attn.out_proj.weight",
|
| 64 |
+
f"decoder.layers.{i}.encoder_attn.out_proj.weight",
|
| 65 |
+
)
|
| 66 |
+
)
|
| 67 |
+
rename_keys.append(
|
| 68 |
+
(
|
| 69 |
+
f"transformer.decoder.layers.{i}.multihead_attn.out_proj.bias",
|
| 70 |
+
f"decoder.layers.{i}.encoder_attn.out_proj.bias",
|
| 71 |
+
)
|
| 72 |
+
)
|
| 73 |
+
rename_keys.append((f"transformer.decoder.layers.{i}.linear1.weight", f"decoder.layers.{i}.fc1.weight"))
|
| 74 |
+
rename_keys.append((f"transformer.decoder.layers.{i}.linear1.bias", f"decoder.layers.{i}.fc1.bias"))
|
| 75 |
+
rename_keys.append((f"transformer.decoder.layers.{i}.linear2.weight", f"decoder.layers.{i}.fc2.weight"))
|
| 76 |
+
rename_keys.append((f"transformer.decoder.layers.{i}.linear2.bias", f"decoder.layers.{i}.fc2.bias"))
|
| 77 |
+
rename_keys.append(
|
| 78 |
+
(f"transformer.decoder.layers.{i}.norm1.weight", f"decoder.layers.{i}.self_attn_layer_norm.weight")
|
| 79 |
+
)
|
| 80 |
+
rename_keys.append((f"transformer.decoder.layers.{i}.norm1.bias", f"decoder.layers.{i}.self_attn_layer_norm.bias"))
|
| 81 |
+
rename_keys.append(
|
| 82 |
+
(f"transformer.decoder.layers.{i}.norm2.weight", f"decoder.layers.{i}.encoder_attn_layer_norm.weight")
|
| 83 |
+
)
|
| 84 |
+
rename_keys.append(
|
| 85 |
+
(f"transformer.decoder.layers.{i}.norm2.bias", f"decoder.layers.{i}.encoder_attn_layer_norm.bias")
|
| 86 |
+
)
|
| 87 |
+
rename_keys.append((f"transformer.decoder.layers.{i}.norm3.weight", f"decoder.layers.{i}.final_layer_norm.weight"))
|
| 88 |
+
rename_keys.append((f"transformer.decoder.layers.{i}.norm3.bias", f"decoder.layers.{i}.final_layer_norm.bias"))
|
| 89 |
+
|
| 90 |
+
# convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads
|
| 91 |
+
rename_keys.extend(
|
| 92 |
+
[
|
| 93 |
+
("input_proj.weight", "input_projection.weight"),
|
| 94 |
+
("input_proj.bias", "input_projection.bias"),
|
| 95 |
+
("query_embed.weight", "query_position_embeddings.weight"),
|
| 96 |
+
("transformer.decoder.norm.weight", "decoder.layernorm.weight"),
|
| 97 |
+
("transformer.decoder.norm.bias", "decoder.layernorm.bias"),
|
| 98 |
+
("class_embed.weight", "class_labels_classifier.weight"),
|
| 99 |
+
("class_embed.bias", "class_labels_classifier.bias"),
|
| 100 |
+
("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"),
|
| 101 |
+
("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"),
|
| 102 |
+
("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"),
|
| 103 |
+
("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"),
|
| 104 |
+
("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"),
|
| 105 |
+
("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"),
|
| 106 |
+
]
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def rename_key(state_dict, old, new):
|
| 111 |
+
val = state_dict.pop(old)
|
| 112 |
+
state_dict[new] = val
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def rename_backbone_keys(state_dict):
|
| 116 |
+
new_state_dict = OrderedDict()
|
| 117 |
+
for key, value in state_dict.items():
|
| 118 |
+
if "backbone.0.body" in key:
|
| 119 |
+
new_key = key.replace("backbone.0.body", "backbone.conv_encoder.model")
|
| 120 |
+
new_state_dict[new_key] = value
|
| 121 |
+
else:
|
| 122 |
+
new_state_dict[key] = value
|
| 123 |
+
|
| 124 |
+
return new_state_dict
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def read_in_q_k_v(state_dict, is_panoptic=False):
|
| 128 |
+
prefix = ""
|
| 129 |
+
if is_panoptic:
|
| 130 |
+
prefix = "detr."
|
| 131 |
+
|
| 132 |
+
# first: transformer encoder
|
| 133 |
+
for i in range(6):
|
| 134 |
+
# read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias)
|
| 135 |
+
in_proj_weight = state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight")
|
| 136 |
+
in_proj_bias = state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias")
|
| 137 |
+
# next, add query, keys and values (in that order) to the state dict
|
| 138 |
+
state_dict[f"encoder.layers.{i}.self_attn.q_proj.weight"] = in_proj_weight[:256, :]
|
| 139 |
+
state_dict[f"encoder.layers.{i}.self_attn.q_proj.bias"] = in_proj_bias[:256]
|
| 140 |
+
state_dict[f"encoder.layers.{i}.self_attn.k_proj.weight"] = in_proj_weight[256:512, :]
|
| 141 |
+
state_dict[f"encoder.layers.{i}.self_attn.k_proj.bias"] = in_proj_bias[256:512]
|
| 142 |
+
state_dict[f"encoder.layers.{i}.self_attn.v_proj.weight"] = in_proj_weight[-256:, :]
|
| 143 |
+
state_dict[f"encoder.layers.{i}.self_attn.v_proj.bias"] = in_proj_bias[-256:]
|
| 144 |
+
# next: transformer decoder (which is a bit more complex because it also includes cross-attention)
|
| 145 |
+
for i in range(6):
|
| 146 |
+
# read in weights + bias of input projection layer of self-attention
|
| 147 |
+
in_proj_weight = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight")
|
| 148 |
+
in_proj_bias = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias")
|
| 149 |
+
# next, add query, keys and values (in that order) to the state dict
|
| 150 |
+
state_dict[f"decoder.layers.{i}.self_attn.q_proj.weight"] = in_proj_weight[:256, :]
|
| 151 |
+
state_dict[f"decoder.layers.{i}.self_attn.q_proj.bias"] = in_proj_bias[:256]
|
| 152 |
+
state_dict[f"decoder.layers.{i}.self_attn.k_proj.weight"] = in_proj_weight[256:512, :]
|
| 153 |
+
state_dict[f"decoder.layers.{i}.self_attn.k_proj.bias"] = in_proj_bias[256:512]
|
| 154 |
+
state_dict[f"decoder.layers.{i}.self_attn.v_proj.weight"] = in_proj_weight[-256:, :]
|
| 155 |
+
state_dict[f"decoder.layers.{i}.self_attn.v_proj.bias"] = in_proj_bias[-256:]
|
| 156 |
+
# read in weights + bias of input projection layer of cross-attention
|
| 157 |
+
in_proj_weight_cross_attn = state_dict.pop(
|
| 158 |
+
f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight"
|
| 159 |
+
)
|
| 160 |
+
in_proj_bias_cross_attn = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias")
|
| 161 |
+
# next, add query, keys and values (in that order) of cross-attention to the state dict
|
| 162 |
+
state_dict[f"decoder.layers.{i}.encoder_attn.q_proj.weight"] = in_proj_weight_cross_attn[:256, :]
|
| 163 |
+
state_dict[f"decoder.layers.{i}.encoder_attn.q_proj.bias"] = in_proj_bias_cross_attn[:256]
|
| 164 |
+
state_dict[f"decoder.layers.{i}.encoder_attn.k_proj.weight"] = in_proj_weight_cross_attn[256:512, :]
|
| 165 |
+
state_dict[f"decoder.layers.{i}.encoder_attn.k_proj.bias"] = in_proj_bias_cross_attn[256:512]
|
| 166 |
+
state_dict[f"decoder.layers.{i}.encoder_attn.v_proj.weight"] = in_proj_weight_cross_attn[-256:, :]
|
| 167 |
+
state_dict[f"decoder.layers.{i}.encoder_attn.v_proj.bias"] = in_proj_bias_cross_attn[-256:]
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
# We will verify our results on an image of cute cats
|
| 171 |
+
def prepare_img():
|
| 172 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 173 |
+
im = Image.open(requests.get(url, stream=True).raw)
|
| 174 |
+
|
| 175 |
+
return im
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@torch.no_grad()
|
| 179 |
+
def convert_detr_checkpoint(model_name, pytorch_dump_folder_path):
|
| 180 |
+
"""
|
| 181 |
+
Copy/paste/tweak model's weights to our DETR structure.
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
# load default config
|
| 185 |
+
config = DetrConfig()
|
| 186 |
+
# set backbone and dilation attributes
|
| 187 |
+
if "resnet101" in model_name:
|
| 188 |
+
config.backbone = "resnet101"
|
| 189 |
+
if "dc5" in model_name:
|
| 190 |
+
config.dilation = True
|
| 191 |
+
is_panoptic = "panoptic" in model_name
|
| 192 |
+
if is_panoptic:
|
| 193 |
+
config.num_labels = 250
|
| 194 |
+
else:
|
| 195 |
+
config.num_labels = 91
|
| 196 |
+
repo_id = "huggingface/label-files"
|
| 197 |
+
filename = "coco-detection-id2label.json"
|
| 198 |
+
id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
|
| 199 |
+
id2label = {int(k): v for k, v in id2label.items()}
|
| 200 |
+
config.id2label = id2label
|
| 201 |
+
config.label2id = {v: k for k, v in id2label.items()}
|
| 202 |
+
|
| 203 |
+
# load image processor
|
| 204 |
+
format = "coco_panoptic" if is_panoptic else "coco_detection"
|
| 205 |
+
image_processor = DetrImageProcessor(format=format)
|
| 206 |
+
|
| 207 |
+
# prepare image
|
| 208 |
+
img = prepare_img()
|
| 209 |
+
encoding = image_processor(images=img, return_tensors="pt")
|
| 210 |
+
pixel_values = encoding["pixel_values"]
|
| 211 |
+
|
| 212 |
+
logger.info(f"Converting model {model_name}...")
|
| 213 |
+
|
| 214 |
+
# load original model from torch hub
|
| 215 |
+
detr = torch.hub.load("facebookresearch/detr", model_name, pretrained=True).eval()
|
| 216 |
+
state_dict = detr.state_dict()
|
| 217 |
+
# rename keys
|
| 218 |
+
for src, dest in rename_keys:
|
| 219 |
+
if is_panoptic:
|
| 220 |
+
src = "detr." + src
|
| 221 |
+
rename_key(state_dict, src, dest)
|
| 222 |
+
state_dict = rename_backbone_keys(state_dict)
|
| 223 |
+
# query, key and value matrices need special treatment
|
| 224 |
+
read_in_q_k_v(state_dict, is_panoptic=is_panoptic)
|
| 225 |
+
# important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
|
| 226 |
+
prefix = "detr.model." if is_panoptic else "model."
|
| 227 |
+
for key in state_dict.copy().keys():
|
| 228 |
+
if is_panoptic:
|
| 229 |
+
if (
|
| 230 |
+
key.startswith("detr")
|
| 231 |
+
and not key.startswith("class_labels_classifier")
|
| 232 |
+
and not key.startswith("bbox_predictor")
|
| 233 |
+
):
|
| 234 |
+
val = state_dict.pop(key)
|
| 235 |
+
state_dict["detr.model" + key[4:]] = val
|
| 236 |
+
elif "class_labels_classifier" in key or "bbox_predictor" in key:
|
| 237 |
+
val = state_dict.pop(key)
|
| 238 |
+
state_dict["detr." + key] = val
|
| 239 |
+
elif key.startswith("bbox_attention") or key.startswith("mask_head"):
|
| 240 |
+
continue
|
| 241 |
+
else:
|
| 242 |
+
val = state_dict.pop(key)
|
| 243 |
+
state_dict[prefix + key] = val
|
| 244 |
+
else:
|
| 245 |
+
if not key.startswith("class_labels_classifier") and not key.startswith("bbox_predictor"):
|
| 246 |
+
val = state_dict.pop(key)
|
| 247 |
+
state_dict[prefix + key] = val
|
| 248 |
+
# finally, create HuggingFace model and load state dict
|
| 249 |
+
model = DetrForSegmentation(config) if is_panoptic else DetrForObjectDetection(config)
|
| 250 |
+
model.load_state_dict(state_dict)
|
| 251 |
+
model.eval()
|
| 252 |
+
# verify our conversion
|
| 253 |
+
original_outputs = detr(pixel_values)
|
| 254 |
+
outputs = model(pixel_values)
|
| 255 |
+
assert torch.allclose(outputs.logits, original_outputs["pred_logits"], atol=1e-4)
|
| 256 |
+
assert torch.allclose(outputs.pred_boxes, original_outputs["pred_boxes"], atol=1e-4)
|
| 257 |
+
if is_panoptic:
|
| 258 |
+
assert torch.allclose(outputs.pred_masks, original_outputs["pred_masks"], atol=1e-4)
|
| 259 |
+
|
| 260 |
+
# Save model and image processor
|
| 261 |
+
logger.info(f"Saving PyTorch model and image processor to {pytorch_dump_folder_path}...")
|
| 262 |
+
Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
|
| 263 |
+
model.save_pretrained(pytorch_dump_folder_path)
|
| 264 |
+
image_processor.save_pretrained(pytorch_dump_folder_path)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
if __name__ == "__main__":
|
| 268 |
+
parser = argparse.ArgumentParser()
|
| 269 |
+
|
| 270 |
+
parser.add_argument(
|
| 271 |
+
"--model_name", default="detr_resnet50", type=str, help="Name of the DETR model you'd like to convert."
|
| 272 |
+
)
|
| 273 |
+
parser.add_argument(
|
| 274 |
+
"--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model."
|
| 275 |
+
)
|
| 276 |
+
args = parser.parse_args()
|
| 277 |
+
convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path)
|
tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/models/detr/convert_detr_to_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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert DETR checkpoints with native (Transformers) backbone."""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import json
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
import requests
|
| 22 |
+
import torch
|
| 23 |
+
from huggingface_hub import hf_hub_download
|
| 24 |
+
from PIL import Image
|
| 25 |
+
|
| 26 |
+
from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig
|
| 27 |
+
from transformers.utils import logging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logging.set_verbosity_info()
|
| 31 |
+
logger = logging.get_logger(__name__)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def get_detr_config(model_name):
|
| 35 |
+
# initialize config
|
| 36 |
+
if "resnet-50" in model_name:
|
| 37 |
+
backbone_config = ResNetConfig.from_pretrained("microsoft/resnet-50")
|
| 38 |
+
elif "resnet-101" in model_name:
|
| 39 |
+
backbone_config = ResNetConfig.from_pretrained("microsoft/resnet-101")
|
| 40 |
+
else:
|
| 41 |
+
raise ValueError("Model name should include either resnet50 or resnet101")
|
| 42 |
+
|
| 43 |
+
config = DetrConfig(use_timm_backbone=False, backbone_config=backbone_config)
|
| 44 |
+
|
| 45 |
+
# set label attributes
|
| 46 |
+
is_panoptic = "panoptic" in model_name
|
| 47 |
+
if is_panoptic:
|
| 48 |
+
config.num_labels = 250
|
| 49 |
+
else:
|
| 50 |
+
config.num_labels = 91
|
| 51 |
+
repo_id = "huggingface/label-files"
|
| 52 |
+
filename = "coco-detection-id2label.json"
|
| 53 |
+
id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
|
| 54 |
+
id2label = {int(k): v for k, v in id2label.items()}
|
| 55 |
+
config.id2label = id2label
|
| 56 |
+
config.label2id = {v: k for k, v in id2label.items()}
|
| 57 |
+
|
| 58 |
+
return config, is_panoptic
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def create_rename_keys(config):
|
| 62 |
+
# here we list all keys to be renamed (original name on the left, our name on the right)
|
| 63 |
+
rename_keys = []
|
| 64 |
+
|
| 65 |
+
# stem
|
| 66 |
+
# fmt: off
|
| 67 |
+
rename_keys.append(("backbone.0.body.conv1.weight", "backbone.conv_encoder.model.embedder.embedder.convolution.weight"))
|
| 68 |
+
rename_keys.append(("backbone.0.body.bn1.weight", "backbone.conv_encoder.model.embedder.embedder.normalization.weight"))
|
| 69 |
+
rename_keys.append(("backbone.0.body.bn1.bias", "backbone.conv_encoder.model.embedder.embedder.normalization.bias"))
|
| 70 |
+
rename_keys.append(("backbone.0.body.bn1.running_mean", "backbone.conv_encoder.model.embedder.embedder.normalization.running_mean"))
|
| 71 |
+
rename_keys.append(("backbone.0.body.bn1.running_var", "backbone.conv_encoder.model.embedder.embedder.normalization.running_var"))
|
| 72 |
+
# stages
|
| 73 |
+
for stage_idx in range(len(config.backbone_config.depths)):
|
| 74 |
+
for layer_idx in range(config.backbone_config.depths[stage_idx]):
|
| 75 |
+
# shortcut
|
| 76 |
+
if layer_idx == 0:
|
| 77 |
+
rename_keys.append(
|
| 78 |
+
(
|
| 79 |
+
f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight",
|
| 80 |
+
f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight",
|
| 81 |
+
)
|
| 82 |
+
)
|
| 83 |
+
rename_keys.append(
|
| 84 |
+
(
|
| 85 |
+
f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight",
|
| 86 |
+
f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight",
|
| 87 |
+
)
|
| 88 |
+
)
|
| 89 |
+
rename_keys.append(
|
| 90 |
+
(
|
| 91 |
+
f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias",
|
| 92 |
+
f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias",
|
| 93 |
+
)
|
| 94 |
+
)
|
| 95 |
+
rename_keys.append(
|
| 96 |
+
(
|
| 97 |
+
f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean",
|
| 98 |
+
f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean",
|
| 99 |
+
)
|
| 100 |
+
)
|
| 101 |
+
rename_keys.append(
|
| 102 |
+
(
|
| 103 |
+
f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var",
|
| 104 |
+
f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var",
|
| 105 |
+
)
|
| 106 |
+
)
|
| 107 |
+
# 3 convs
|
| 108 |
+
for i in range(3):
|
| 109 |
+
rename_keys.append(
|
| 110 |
+
(
|
| 111 |
+
f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight",
|
| 112 |
+
f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight",
|
| 113 |
+
)
|
| 114 |
+
)
|
| 115 |
+
rename_keys.append(
|
| 116 |
+
(
|
| 117 |
+
f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight",
|
| 118 |
+
f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight",
|
| 119 |
+
)
|
| 120 |
+
)
|
| 121 |
+
rename_keys.append(
|
| 122 |
+
(
|
| 123 |
+
f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias",
|
| 124 |
+
f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias",
|
| 125 |
+
)
|
| 126 |
+
)
|
| 127 |
+
rename_keys.append(
|
| 128 |
+
(
|
| 129 |
+
f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean",
|
| 130 |
+
f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean",
|
| 131 |
+
)
|
| 132 |
+
)
|
| 133 |
+
rename_keys.append(
|
| 134 |
+
(
|
| 135 |
+
f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var",
|
| 136 |
+
f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var",
|
| 137 |
+
)
|
| 138 |
+
)
|
| 139 |
+
# fmt: on
|
| 140 |
+
|
| 141 |
+
for i in range(config.encoder_layers):
|
| 142 |
+
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
|
| 143 |
+
rename_keys.append(
|
| 144 |
+
(
|
| 145 |
+
f"transformer.encoder.layers.{i}.self_attn.out_proj.weight",
|
| 146 |
+
f"encoder.layers.{i}.self_attn.out_proj.weight",
|
| 147 |
+
)
|
| 148 |
+
)
|
| 149 |
+
rename_keys.append(
|
| 150 |
+
(f"transformer.encoder.layers.{i}.self_attn.out_proj.bias", f"encoder.layers.{i}.self_attn.out_proj.bias")
|
| 151 |
+
)
|
| 152 |
+
rename_keys.append((f"transformer.encoder.layers.{i}.linear1.weight", f"encoder.layers.{i}.fc1.weight"))
|
| 153 |
+
rename_keys.append((f"transformer.encoder.layers.{i}.linear1.bias", f"encoder.layers.{i}.fc1.bias"))
|
| 154 |
+
rename_keys.append((f"transformer.encoder.layers.{i}.linear2.weight", f"encoder.layers.{i}.fc2.weight"))
|
| 155 |
+
rename_keys.append((f"transformer.encoder.layers.{i}.linear2.bias", f"encoder.layers.{i}.fc2.bias"))
|
| 156 |
+
rename_keys.append(
|
| 157 |
+
(f"transformer.encoder.layers.{i}.norm1.weight", f"encoder.layers.{i}.self_attn_layer_norm.weight")
|
| 158 |
+
)
|
| 159 |
+
rename_keys.append(
|
| 160 |
+
(f"transformer.encoder.layers.{i}.norm1.bias", f"encoder.layers.{i}.self_attn_layer_norm.bias")
|
| 161 |
+
)
|
| 162 |
+
rename_keys.append(
|
| 163 |
+
(f"transformer.encoder.layers.{i}.norm2.weight", f"encoder.layers.{i}.final_layer_norm.weight")
|
| 164 |
+
)
|
| 165 |
+
rename_keys.append((f"transformer.encoder.layers.{i}.norm2.bias", f"encoder.layers.{i}.final_layer_norm.bias"))
|
| 166 |
+
# decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms
|
| 167 |
+
rename_keys.append(
|
| 168 |
+
(
|
| 169 |
+
f"transformer.decoder.layers.{i}.self_attn.out_proj.weight",
|
| 170 |
+
f"decoder.layers.{i}.self_attn.out_proj.weight",
|
| 171 |
+
)
|
| 172 |
+
)
|
| 173 |
+
rename_keys.append(
|
| 174 |
+
(f"transformer.decoder.layers.{i}.self_attn.out_proj.bias", f"decoder.layers.{i}.self_attn.out_proj.bias")
|
| 175 |
+
)
|
| 176 |
+
rename_keys.append(
|
| 177 |
+
(
|
| 178 |
+
f"transformer.decoder.layers.{i}.multihead_attn.out_proj.weight",
|
| 179 |
+
f"decoder.layers.{i}.encoder_attn.out_proj.weight",
|
| 180 |
+
)
|
| 181 |
+
)
|
| 182 |
+
rename_keys.append(
|
| 183 |
+
(
|
| 184 |
+
f"transformer.decoder.layers.{i}.multihead_attn.out_proj.bias",
|
| 185 |
+
f"decoder.layers.{i}.encoder_attn.out_proj.bias",
|
| 186 |
+
)
|
| 187 |
+
)
|
| 188 |
+
rename_keys.append((f"transformer.decoder.layers.{i}.linear1.weight", f"decoder.layers.{i}.fc1.weight"))
|
| 189 |
+
rename_keys.append((f"transformer.decoder.layers.{i}.linear1.bias", f"decoder.layers.{i}.fc1.bias"))
|
| 190 |
+
rename_keys.append((f"transformer.decoder.layers.{i}.linear2.weight", f"decoder.layers.{i}.fc2.weight"))
|
| 191 |
+
rename_keys.append((f"transformer.decoder.layers.{i}.linear2.bias", f"decoder.layers.{i}.fc2.bias"))
|
| 192 |
+
rename_keys.append(
|
| 193 |
+
(f"transformer.decoder.layers.{i}.norm1.weight", f"decoder.layers.{i}.self_attn_layer_norm.weight")
|
| 194 |
+
)
|
| 195 |
+
rename_keys.append(
|
| 196 |
+
(f"transformer.decoder.layers.{i}.norm1.bias", f"decoder.layers.{i}.self_attn_layer_norm.bias")
|
| 197 |
+
)
|
| 198 |
+
rename_keys.append(
|
| 199 |
+
(f"transformer.decoder.layers.{i}.norm2.weight", f"decoder.layers.{i}.encoder_attn_layer_norm.weight")
|
| 200 |
+
)
|
| 201 |
+
rename_keys.append(
|
| 202 |
+
(f"transformer.decoder.layers.{i}.norm2.bias", f"decoder.layers.{i}.encoder_attn_layer_norm.bias")
|
| 203 |
+
)
|
| 204 |
+
rename_keys.append(
|
| 205 |
+
(f"transformer.decoder.layers.{i}.norm3.weight", f"decoder.layers.{i}.final_layer_norm.weight")
|
| 206 |
+
)
|
| 207 |
+
rename_keys.append((f"transformer.decoder.layers.{i}.norm3.bias", f"decoder.layers.{i}.final_layer_norm.bias"))
|
| 208 |
+
|
| 209 |
+
# convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads
|
| 210 |
+
rename_keys.extend(
|
| 211 |
+
[
|
| 212 |
+
("input_proj.weight", "input_projection.weight"),
|
| 213 |
+
("input_proj.bias", "input_projection.bias"),
|
| 214 |
+
("query_embed.weight", "query_position_embeddings.weight"),
|
| 215 |
+
("transformer.decoder.norm.weight", "decoder.layernorm.weight"),
|
| 216 |
+
("transformer.decoder.norm.bias", "decoder.layernorm.bias"),
|
| 217 |
+
("class_embed.weight", "class_labels_classifier.weight"),
|
| 218 |
+
("class_embed.bias", "class_labels_classifier.bias"),
|
| 219 |
+
("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"),
|
| 220 |
+
("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"),
|
| 221 |
+
("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"),
|
| 222 |
+
("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"),
|
| 223 |
+
("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"),
|
| 224 |
+
("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"),
|
| 225 |
+
]
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
return rename_keys
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def rename_key(state_dict, old, new):
|
| 232 |
+
val = state_dict.pop(old)
|
| 233 |
+
state_dict[new] = val
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def read_in_q_k_v(state_dict, is_panoptic=False):
|
| 237 |
+
prefix = ""
|
| 238 |
+
if is_panoptic:
|
| 239 |
+
prefix = "detr."
|
| 240 |
+
|
| 241 |
+
# first: transformer encoder
|
| 242 |
+
for i in range(6):
|
| 243 |
+
# read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias)
|
| 244 |
+
in_proj_weight = state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight")
|
| 245 |
+
in_proj_bias = state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias")
|
| 246 |
+
# next, add query, keys and values (in that order) to the state dict
|
| 247 |
+
state_dict[f"encoder.layers.{i}.self_attn.q_proj.weight"] = in_proj_weight[:256, :]
|
| 248 |
+
state_dict[f"encoder.layers.{i}.self_attn.q_proj.bias"] = in_proj_bias[:256]
|
| 249 |
+
state_dict[f"encoder.layers.{i}.self_attn.k_proj.weight"] = in_proj_weight[256:512, :]
|
| 250 |
+
state_dict[f"encoder.layers.{i}.self_attn.k_proj.bias"] = in_proj_bias[256:512]
|
| 251 |
+
state_dict[f"encoder.layers.{i}.self_attn.v_proj.weight"] = in_proj_weight[-256:, :]
|
| 252 |
+
state_dict[f"encoder.layers.{i}.self_attn.v_proj.bias"] = in_proj_bias[-256:]
|
| 253 |
+
# next: transformer decoder (which is a bit more complex because it also includes cross-attention)
|
| 254 |
+
for i in range(6):
|
| 255 |
+
# read in weights + bias of input projection layer of self-attention
|
| 256 |
+
in_proj_weight = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight")
|
| 257 |
+
in_proj_bias = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias")
|
| 258 |
+
# next, add query, keys and values (in that order) to the state dict
|
| 259 |
+
state_dict[f"decoder.layers.{i}.self_attn.q_proj.weight"] = in_proj_weight[:256, :]
|
| 260 |
+
state_dict[f"decoder.layers.{i}.self_attn.q_proj.bias"] = in_proj_bias[:256]
|
| 261 |
+
state_dict[f"decoder.layers.{i}.self_attn.k_proj.weight"] = in_proj_weight[256:512, :]
|
| 262 |
+
state_dict[f"decoder.layers.{i}.self_attn.k_proj.bias"] = in_proj_bias[256:512]
|
| 263 |
+
state_dict[f"decoder.layers.{i}.self_attn.v_proj.weight"] = in_proj_weight[-256:, :]
|
| 264 |
+
state_dict[f"decoder.layers.{i}.self_attn.v_proj.bias"] = in_proj_bias[-256:]
|
| 265 |
+
# read in weights + bias of input projection layer of cross-attention
|
| 266 |
+
in_proj_weight_cross_attn = state_dict.pop(
|
| 267 |
+
f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight"
|
| 268 |
+
)
|
| 269 |
+
in_proj_bias_cross_attn = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias")
|
| 270 |
+
# next, add query, keys and values (in that order) of cross-attention to the state dict
|
| 271 |
+
state_dict[f"decoder.layers.{i}.encoder_attn.q_proj.weight"] = in_proj_weight_cross_attn[:256, :]
|
| 272 |
+
state_dict[f"decoder.layers.{i}.encoder_attn.q_proj.bias"] = in_proj_bias_cross_attn[:256]
|
| 273 |
+
state_dict[f"decoder.layers.{i}.encoder_attn.k_proj.weight"] = in_proj_weight_cross_attn[256:512, :]
|
| 274 |
+
state_dict[f"decoder.layers.{i}.encoder_attn.k_proj.bias"] = in_proj_bias_cross_attn[256:512]
|
| 275 |
+
state_dict[f"decoder.layers.{i}.encoder_attn.v_proj.weight"] = in_proj_weight_cross_attn[-256:, :]
|
| 276 |
+
state_dict[f"decoder.layers.{i}.encoder_attn.v_proj.bias"] = in_proj_bias_cross_attn[-256:]
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
# We will verify our results on an image of cute cats
|
| 280 |
+
def prepare_img():
|
| 281 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 282 |
+
im = Image.open(requests.get(url, stream=True).raw)
|
| 283 |
+
|
| 284 |
+
return im
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
@torch.no_grad()
|
| 288 |
+
def convert_detr_checkpoint(model_name, pytorch_dump_folder_path=None, push_to_hub=False):
|
| 289 |
+
"""
|
| 290 |
+
Copy/paste/tweak model's weights to our DETR structure.
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
# load default config
|
| 294 |
+
config, is_panoptic = get_detr_config(model_name)
|
| 295 |
+
|
| 296 |
+
# load original model from torch hub
|
| 297 |
+
model_name_to_original_name = {
|
| 298 |
+
"detr-resnet-50": "detr_resnet50",
|
| 299 |
+
"detr-resnet-101": "detr_resnet101",
|
| 300 |
+
}
|
| 301 |
+
logger.info(f"Converting model {model_name}...")
|
| 302 |
+
detr = torch.hub.load("facebookresearch/detr", model_name_to_original_name[model_name], pretrained=True).eval()
|
| 303 |
+
state_dict = detr.state_dict()
|
| 304 |
+
# rename keys
|
| 305 |
+
for src, dest in create_rename_keys(config):
|
| 306 |
+
if is_panoptic:
|
| 307 |
+
src = "detr." + src
|
| 308 |
+
rename_key(state_dict, src, dest)
|
| 309 |
+
# query, key and value matrices need special treatment
|
| 310 |
+
read_in_q_k_v(state_dict, is_panoptic=is_panoptic)
|
| 311 |
+
# important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
|
| 312 |
+
prefix = "detr.model." if is_panoptic else "model."
|
| 313 |
+
for key in state_dict.copy().keys():
|
| 314 |
+
if is_panoptic:
|
| 315 |
+
if (
|
| 316 |
+
key.startswith("detr")
|
| 317 |
+
and not key.startswith("class_labels_classifier")
|
| 318 |
+
and not key.startswith("bbox_predictor")
|
| 319 |
+
):
|
| 320 |
+
val = state_dict.pop(key)
|
| 321 |
+
state_dict["detr.model" + key[4:]] = val
|
| 322 |
+
elif "class_labels_classifier" in key or "bbox_predictor" in key:
|
| 323 |
+
val = state_dict.pop(key)
|
| 324 |
+
state_dict["detr." + key] = val
|
| 325 |
+
elif key.startswith("bbox_attention") or key.startswith("mask_head"):
|
| 326 |
+
continue
|
| 327 |
+
else:
|
| 328 |
+
val = state_dict.pop(key)
|
| 329 |
+
state_dict[prefix + key] = val
|
| 330 |
+
else:
|
| 331 |
+
if not key.startswith("class_labels_classifier") and not key.startswith("bbox_predictor"):
|
| 332 |
+
val = state_dict.pop(key)
|
| 333 |
+
state_dict[prefix + key] = val
|
| 334 |
+
|
| 335 |
+
# finally, create HuggingFace model and load state dict
|
| 336 |
+
model = DetrForSegmentation(config) if is_panoptic else DetrForObjectDetection(config)
|
| 337 |
+
model.load_state_dict(state_dict)
|
| 338 |
+
model.eval()
|
| 339 |
+
|
| 340 |
+
# verify our conversion on an image
|
| 341 |
+
format = "coco_panoptic" if is_panoptic else "coco_detection"
|
| 342 |
+
processor = DetrImageProcessor(format=format)
|
| 343 |
+
|
| 344 |
+
encoding = processor(images=prepare_img(), return_tensors="pt")
|
| 345 |
+
pixel_values = encoding["pixel_values"]
|
| 346 |
+
|
| 347 |
+
original_outputs = detr(pixel_values)
|
| 348 |
+
outputs = model(pixel_values)
|
| 349 |
+
|
| 350 |
+
assert torch.allclose(outputs.logits, original_outputs["pred_logits"], atol=1e-3)
|
| 351 |
+
assert torch.allclose(outputs.pred_boxes, original_outputs["pred_boxes"], atol=1e-3)
|
| 352 |
+
if is_panoptic:
|
| 353 |
+
assert torch.allclose(outputs.pred_masks, original_outputs["pred_masks"], atol=1e-4)
|
| 354 |
+
print("Looks ok!")
|
| 355 |
+
|
| 356 |
+
if pytorch_dump_folder_path is not None:
|
| 357 |
+
# Save model and image processor
|
| 358 |
+
logger.info(f"Saving PyTorch model and image processor to {pytorch_dump_folder_path}...")
|
| 359 |
+
Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
|
| 360 |
+
model.save_pretrained(pytorch_dump_folder_path)
|
| 361 |
+
processor.save_pretrained(pytorch_dump_folder_path)
|
| 362 |
+
|
| 363 |
+
if push_to_hub:
|
| 364 |
+
# Upload model and image processor to the hub
|
| 365 |
+
logger.info("Uploading PyTorch model and image processor to the hub...")
|
| 366 |
+
model.push_to_hub(f"nielsr/{model_name}")
|
| 367 |
+
processor.push_to_hub(f"nielsr/{model_name}")
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
if __name__ == "__main__":
|
| 371 |
+
parser = argparse.ArgumentParser()
|
| 372 |
+
|
| 373 |
+
parser.add_argument(
|
| 374 |
+
"--model_name",
|
| 375 |
+
default="detr-resnet-50",
|
| 376 |
+
type=str,
|
| 377 |
+
choices=["detr-resnet-50", "detr-resnet-101"],
|
| 378 |
+
help="Name of the DETR model you'd like to convert.",
|
| 379 |
+
)
|
| 380 |
+
parser.add_argument(
|
| 381 |
+
"--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model."
|
| 382 |
+
)
|
| 383 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether to push the model to the hub or not.")
|
| 384 |
+
args = parser.parse_args()
|
| 385 |
+
convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
|