Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- lib/python3.11/site-packages/transformers/models/beit/__pycache__/__init__.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/beit/__pycache__/configuration_beit.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/beit/__pycache__/image_processing_beit.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/beit/__pycache__/image_processing_pil_beit.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/beit/__pycache__/modeling_beit.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/beit/__pycache__/modular_beit.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/beit/modeling_beit.py +1165 -0
- lib/python3.11/site-packages/transformers/models/beit/modular_beit.py +964 -0
- lib/python3.11/site-packages/transformers/models/bert/__init__.py +28 -0
- lib/python3.11/site-packages/transformers/models/bert/__pycache__/__init__.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/bert/__pycache__/configuration_bert.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/bert/__pycache__/modeling_bert.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/bert/__pycache__/tokenization_bert.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/bert/__pycache__/tokenization_bert_legacy.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/bert/configuration_bert.py +66 -0
- lib/python3.11/site-packages/transformers/models/bert/modeling_bert.py +1394 -0
- lib/python3.11/site-packages/transformers/models/bert/tokenization_bert.py +140 -0
- lib/python3.11/site-packages/transformers/models/bert/tokenization_bert_legacy.py +476 -0
- lib/python3.11/site-packages/transformers/models/bert_generation/__init__.py +28 -0
- lib/python3.11/site-packages/transformers/models/bert_generation/__pycache__/__init__.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/bert_generation/__pycache__/configuration_bert_generation.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/bert_generation/__pycache__/modeling_bert_generation.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/bert_generation/__pycache__/tokenization_bert_generation.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/bert_generation/configuration_bert_generation.py +63 -0
- lib/python3.11/site-packages/transformers/models/bert_generation/modeling_bert_generation.py +712 -0
- lib/python3.11/site-packages/transformers/models/bert_generation/tokenization_bert_generation.py +102 -0
- lib/python3.11/site-packages/transformers/models/bert_japanese/__init__.py +26 -0
- lib/python3.11/site-packages/transformers/models/bert_japanese/__pycache__/__init__.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/bert_japanese/__pycache__/tokenization_bert_japanese.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/bert_japanese/tokenization_bert_japanese.py +901 -0
- lib/python3.11/site-packages/transformers/models/bertweet/__init__.py +26 -0
- lib/python3.11/site-packages/transformers/models/bertweet/__pycache__/__init__.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/bertweet/__pycache__/tokenization_bertweet.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/bertweet/tokenization_bertweet.py +698 -0
- lib/python3.11/site-packages/transformers/models/big_bird/__init__.py +28 -0
- lib/python3.11/site-packages/transformers/models/big_bird/__pycache__/__init__.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/big_bird/__pycache__/configuration_big_bird.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/big_bird/__pycache__/tokenization_big_bird.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/big_bird/configuration_big_bird.py +84 -0
- lib/python3.11/site-packages/transformers/models/big_bird/modeling_big_bird.py +0 -0
- lib/python3.11/site-packages/transformers/models/big_bird/tokenization_big_bird.py +151 -0
- lib/python3.11/site-packages/transformers/models/bigbird_pegasus/__init__.py +27 -0
- lib/python3.11/site-packages/transformers/models/bigbird_pegasus/__pycache__/__init__.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/bigbird_pegasus/__pycache__/configuration_bigbird_pegasus.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/bigbird_pegasus/configuration_bigbird_pegasus.py +93 -0
- lib/python3.11/site-packages/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py +0 -0
- lib/python3.11/site-packages/transformers/models/biogpt/__init__.py +28 -0
- lib/python3.11/site-packages/transformers/models/biogpt/__pycache__/__init__.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/biogpt/__pycache__/configuration_biogpt.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/biogpt/__pycache__/modeling_biogpt.cpython-311.pyc +0 -0
lib/python3.11/site-packages/transformers/models/beit/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (862 Bytes). View file
|
|
|
lib/python3.11/site-packages/transformers/models/beit/__pycache__/configuration_beit.cpython-311.pyc
ADDED
|
Binary file (7.22 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/beit/__pycache__/image_processing_beit.cpython-311.pyc
ADDED
|
Binary file (10.9 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/beit/__pycache__/image_processing_pil_beit.cpython-311.pyc
ADDED
|
Binary file (9.53 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/beit/__pycache__/modeling_beit.cpython-311.pyc
ADDED
|
Binary file (65.7 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/beit/__pycache__/modular_beit.cpython-311.pyc
ADDED
|
Binary file (54 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/beit/modeling_beit.py
ADDED
|
@@ -0,0 +1,1165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/beit/modular_beit.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_beit.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2021 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from collections.abc import Callable, Iterable
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
from torch import Tensor, nn
|
| 26 |
+
|
| 27 |
+
from ... import initialization as init
|
| 28 |
+
from ...activations import ACT2FN
|
| 29 |
+
from ...backbone_utils import BackboneMixin, filter_output_hidden_states
|
| 30 |
+
from ...masking_utils import create_bidirectional_mask
|
| 31 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 32 |
+
from ...modeling_outputs import (
|
| 33 |
+
BackboneOutput,
|
| 34 |
+
BaseModelOutputWithPooling,
|
| 35 |
+
ImageClassifierOutput,
|
| 36 |
+
MaskedLMOutput,
|
| 37 |
+
SemanticSegmenterOutput,
|
| 38 |
+
)
|
| 39 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 40 |
+
from ...processing_utils import Unpack
|
| 41 |
+
from ...pytorch_utils import compile_compatible_method_lru_cache
|
| 42 |
+
from ...utils import TransformersKwargs, auto_docstring, torch_int
|
| 43 |
+
from ...utils.generic import can_return_tuple, merge_with_config_defaults
|
| 44 |
+
from ...utils.output_capturing import capture_outputs
|
| 45 |
+
from .configuration_beit import BeitConfig
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@auto_docstring(
|
| 49 |
+
custom_intro="""
|
| 50 |
+
Class for outputs of [`BeitModel`].
|
| 51 |
+
"""
|
| 52 |
+
)
|
| 53 |
+
@dataclass
|
| 54 |
+
class BeitModelOutputWithPooling(BaseModelOutputWithPooling):
|
| 55 |
+
r"""
|
| 56 |
+
pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
|
| 57 |
+
Average of the last layer hidden states of the patch tokens (excluding the *[CLS]* token) if
|
| 58 |
+
*config.use_mean_pooling* is set to True. If set to False, then the final hidden state of the *[CLS]* token
|
| 59 |
+
will be returned.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class BeitPatchEmbeddings(nn.Module):
|
| 64 |
+
"""
|
| 65 |
+
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
| 66 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
| 67 |
+
Transformer.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
def __init__(self, config: BeitConfig):
|
| 71 |
+
super().__init__()
|
| 72 |
+
image_size = config.image_size
|
| 73 |
+
patch_size = config.patch_size
|
| 74 |
+
image_size = image_size if isinstance(image_size, Iterable) else (image_size, image_size)
|
| 75 |
+
patch_size = patch_size if isinstance(patch_size, Iterable) else (patch_size, patch_size)
|
| 76 |
+
|
| 77 |
+
self.num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 78 |
+
self.image_size = image_size
|
| 79 |
+
self.patch_size = patch_size
|
| 80 |
+
self.num_channels = config.num_channels
|
| 81 |
+
self.projection = nn.Conv2d(config.num_channels, config.hidden_size, kernel_size=patch_size, stride=patch_size)
|
| 82 |
+
|
| 83 |
+
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
|
| 84 |
+
num_channels = pixel_values.shape[1]
|
| 85 |
+
if num_channels != self.num_channels:
|
| 86 |
+
raise ValueError(
|
| 87 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 88 |
+
f" Expected {self.num_channels} but got {num_channels}."
|
| 89 |
+
)
|
| 90 |
+
return self.projection(pixel_values).flatten(2).transpose(1, 2)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class BeitEmbeddings(nn.Module):
|
| 94 |
+
"""
|
| 95 |
+
Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 99 |
+
super().__init__()
|
| 100 |
+
|
| 101 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 102 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) if config.use_mask_token else None
|
| 103 |
+
self.patch_embeddings = BeitPatchEmbeddings(config)
|
| 104 |
+
self.patch_size = config.patch_size
|
| 105 |
+
num_patches = self.patch_embeddings.num_patches
|
| 106 |
+
self.position_embeddings = (
|
| 107 |
+
nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size))
|
| 108 |
+
if config.use_absolute_position_embeddings
|
| 109 |
+
else None
|
| 110 |
+
)
|
| 111 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 112 |
+
|
| 113 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 114 |
+
"""
|
| 115 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
|
| 116 |
+
images. This method is also adapted to support torch.jit tracing.
|
| 117 |
+
|
| 118 |
+
Adapted from:
|
| 119 |
+
- https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
|
| 120 |
+
- https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
|
| 121 |
+
"""
|
| 122 |
+
|
| 123 |
+
num_patches = embeddings.shape[1] - 1
|
| 124 |
+
num_positions = self.position_embeddings.shape[1] - 1
|
| 125 |
+
|
| 126 |
+
# always interpolate when tracing to ensure the exported model works for dynamic input shapes
|
| 127 |
+
if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
|
| 128 |
+
return self.position_embeddings
|
| 129 |
+
|
| 130 |
+
class_pos_embed = self.position_embeddings[:, :1]
|
| 131 |
+
patch_pos_embed = self.position_embeddings[:, 1:]
|
| 132 |
+
|
| 133 |
+
dim = embeddings.shape[-1]
|
| 134 |
+
|
| 135 |
+
new_height = height // self.patch_size
|
| 136 |
+
new_width = width // self.patch_size
|
| 137 |
+
|
| 138 |
+
sqrt_num_positions = torch_int(num_positions**0.5)
|
| 139 |
+
patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
|
| 140 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 141 |
+
|
| 142 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 143 |
+
patch_pos_embed,
|
| 144 |
+
size=(new_height, new_width),
|
| 145 |
+
mode="bicubic",
|
| 146 |
+
align_corners=False,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 150 |
+
|
| 151 |
+
return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
|
| 152 |
+
|
| 153 |
+
def forward(
|
| 154 |
+
self,
|
| 155 |
+
pixel_values: torch.Tensor,
|
| 156 |
+
bool_masked_pos: torch.BoolTensor | None = None,
|
| 157 |
+
) -> torch.Tensor:
|
| 158 |
+
_, _, height, width = pixel_values.shape
|
| 159 |
+
embeddings = self.patch_embeddings(pixel_values)
|
| 160 |
+
batch_size, seq_len, _ = embeddings.size()
|
| 161 |
+
|
| 162 |
+
if bool_masked_pos is not None:
|
| 163 |
+
mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
|
| 164 |
+
# replace the masked visual tokens by mask_tokens
|
| 165 |
+
mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
|
| 166 |
+
embeddings = embeddings * (1 - mask) + mask_tokens * mask
|
| 167 |
+
|
| 168 |
+
cls_tokens = self.cls_token.expand(batch_size, -1, -1)
|
| 169 |
+
embeddings = torch.cat((cls_tokens, embeddings), dim=1)
|
| 170 |
+
|
| 171 |
+
if self.position_embeddings is not None:
|
| 172 |
+
embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
|
| 173 |
+
|
| 174 |
+
embeddings = self.dropout(embeddings)
|
| 175 |
+
|
| 176 |
+
return embeddings
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class BeitRelativePositionBias(nn.Module):
|
| 180 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 181 |
+
super().__init__()
|
| 182 |
+
image_size = config.image_size
|
| 183 |
+
if not isinstance(image_size, (tuple, list)):
|
| 184 |
+
image_size = (image_size, image_size)
|
| 185 |
+
self.window_size = (image_size[0] // config.patch_size, image_size[1] // config.patch_size)
|
| 186 |
+
self.num_relative_distance = (2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1) + 3
|
| 187 |
+
self.relative_position_bias_table = nn.Parameter(
|
| 188 |
+
torch.zeros(self.num_relative_distance, config.num_attention_heads)
|
| 189 |
+
) # 2*Wh-1 * 2*Ww-1, nH
|
| 190 |
+
# cls to token & token 2 cls & cls to cls
|
| 191 |
+
|
| 192 |
+
@staticmethod
|
| 193 |
+
@compile_compatible_method_lru_cache(maxsize=10)
|
| 194 |
+
def generate_relative_position_index(window_size: tuple[int, int]) -> torch.Tensor:
|
| 195 |
+
"""
|
| 196 |
+
This method creates the relative position index, modified to support arbitrary window sizes,
|
| 197 |
+
as introduced in [MiDaS v3.1](https://huggingface.co/papers/2307.14460).
|
| 198 |
+
"""
|
| 199 |
+
num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
|
| 200 |
+
window_area = window_size[0] * window_size[1]
|
| 201 |
+
|
| 202 |
+
# Pair-wise relative position index for each token inside the window
|
| 203 |
+
coords_flatten = torch.flatten(
|
| 204 |
+
torch.stack(torch.meshgrid(torch.arange(window_size[0]), torch.arange(window_size[1]), indexing="ij")),
|
| 205 |
+
start_dim=1,
|
| 206 |
+
) # 2, Wh*Ww
|
| 207 |
+
relative_coords = (coords_flatten[:, :, None] - coords_flatten[:, None, :]).permute(1, 2, 0).contiguous()
|
| 208 |
+
# Wh*Ww, Wh*Ww, 2 — shift to start from 0
|
| 209 |
+
relative_coords[:, :, 0] += window_size[0] - 1
|
| 210 |
+
relative_coords[:, :, 1] += window_size[1] - 1
|
| 211 |
+
relative_coords[:, :, 0] *= 2 * window_size[1] - 1
|
| 212 |
+
|
| 213 |
+
relative_position_index = torch.zeros(size=(window_area + 1,) * 2, dtype=relative_coords.dtype)
|
| 214 |
+
relative_position_index[1:, 1:] = relative_coords.sum(-1)
|
| 215 |
+
relative_position_index[0, 0:] = num_relative_distance - 3 # cls to token
|
| 216 |
+
relative_position_index[0:, 0] = num_relative_distance - 2 # token to cls
|
| 217 |
+
relative_position_index[0, 0] = num_relative_distance - 1 # cls to cls
|
| 218 |
+
return relative_position_index
|
| 219 |
+
|
| 220 |
+
def forward(self, window_size, interpolate_pos_encoding: bool = False, dim_size=None) -> torch.Tensor:
|
| 221 |
+
"""
|
| 222 |
+
Modification of timm.models.beit.py: Attention._get_rel_pos_bias to support arbitrary window sizes.
|
| 223 |
+
"""
|
| 224 |
+
old_height = 2 * self.window_size[0] - 1
|
| 225 |
+
old_width = 2 * self.window_size[1] - 1
|
| 226 |
+
|
| 227 |
+
new_height = 2 * window_size[0] - 1
|
| 228 |
+
new_width = 2 * window_size[1] - 1
|
| 229 |
+
|
| 230 |
+
old_relative_position_bias_table = self.relative_position_bias_table
|
| 231 |
+
|
| 232 |
+
old_num_relative_distance = self.num_relative_distance
|
| 233 |
+
new_num_relative_distance = new_height * new_width + 3
|
| 234 |
+
|
| 235 |
+
old_sub_table = old_relative_position_bias_table[: old_num_relative_distance - 3]
|
| 236 |
+
|
| 237 |
+
old_sub_table = old_sub_table.reshape(1, old_width, old_height, -1).permute(0, 3, 1, 2)
|
| 238 |
+
new_sub_table = nn.functional.interpolate(
|
| 239 |
+
old_sub_table, size=(torch_int(new_height), torch_int(new_width)), mode="bilinear"
|
| 240 |
+
)
|
| 241 |
+
new_sub_table = new_sub_table.permute(0, 2, 3, 1).reshape(new_num_relative_distance - 3, -1)
|
| 242 |
+
|
| 243 |
+
new_relative_position_bias_table = torch.cat(
|
| 244 |
+
[new_sub_table, old_relative_position_bias_table[old_num_relative_distance - 3 :]]
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
relative_position_index = self.generate_relative_position_index(window_size)
|
| 248 |
+
relative_position_bias = new_relative_position_bias_table[relative_position_index.view(-1)]
|
| 249 |
+
|
| 250 |
+
# patch_size*num_patches_height, patch_size*num_patches_width, num_attention_heads
|
| 251 |
+
relative_position_bias = relative_position_bias.view(
|
| 252 |
+
window_size[0] * window_size[1] + 1, window_size[0] * window_size[1] + 1, -1
|
| 253 |
+
)
|
| 254 |
+
# num_attention_heads, patch_size*num_patches_width, patch_size*num_patches_height
|
| 255 |
+
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()
|
| 256 |
+
|
| 257 |
+
if interpolate_pos_encoding:
|
| 258 |
+
relative_position_bias = nn.functional.interpolate(
|
| 259 |
+
relative_position_bias.unsqueeze(1),
|
| 260 |
+
size=(dim_size, dim_size),
|
| 261 |
+
mode="bilinear",
|
| 262 |
+
align_corners=False,
|
| 263 |
+
).squeeze(1)
|
| 264 |
+
|
| 265 |
+
return relative_position_bias.unsqueeze(0)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def eager_attention_forward(
|
| 269 |
+
module: nn.Module,
|
| 270 |
+
query: torch.Tensor,
|
| 271 |
+
key: torch.Tensor,
|
| 272 |
+
value: torch.Tensor,
|
| 273 |
+
attention_mask: torch.Tensor | None,
|
| 274 |
+
scaling: float | None = None,
|
| 275 |
+
dropout: float = 0.0,
|
| 276 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 277 |
+
):
|
| 278 |
+
if scaling is None:
|
| 279 |
+
scaling = query.size(-1) ** -0.5
|
| 280 |
+
|
| 281 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 282 |
+
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
|
| 283 |
+
|
| 284 |
+
if attention_mask is not None:
|
| 285 |
+
attn_weights = attn_weights + attention_mask
|
| 286 |
+
|
| 287 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 288 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 289 |
+
|
| 290 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 291 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 292 |
+
|
| 293 |
+
return attn_output, attn_weights
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
class BeitAttention(nn.Module):
|
| 297 |
+
def __init__(self, config: BeitConfig):
|
| 298 |
+
super().__init__()
|
| 299 |
+
self.config = config
|
| 300 |
+
self.num_attention_heads = config.num_attention_heads
|
| 301 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 302 |
+
self.attention_dropout = config.attention_probs_dropout_prob
|
| 303 |
+
self.scaling = self.head_dim**-0.5
|
| 304 |
+
self.is_causal = False
|
| 305 |
+
self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim)
|
| 306 |
+
self.k_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
|
| 307 |
+
self.v_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim)
|
| 308 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size)
|
| 309 |
+
|
| 310 |
+
def forward(
|
| 311 |
+
self,
|
| 312 |
+
hidden_states: torch.Tensor,
|
| 313 |
+
attention_mask: torch.Tensor | None = None,
|
| 314 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 315 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 316 |
+
input_shape = hidden_states.shape[:-1]
|
| 317 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 318 |
+
|
| 319 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 320 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 321 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 322 |
+
|
| 323 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 324 |
+
self.config._attn_implementation, eager_attention_forward
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
attn_output, attn_weights = attention_interface(
|
| 328 |
+
self,
|
| 329 |
+
query_states,
|
| 330 |
+
key_states,
|
| 331 |
+
value_states,
|
| 332 |
+
attention_mask,
|
| 333 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 334 |
+
scaling=self.scaling,
|
| 335 |
+
**kwargs,
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 339 |
+
attn_output = self.o_proj(attn_output)
|
| 340 |
+
|
| 341 |
+
return attn_output, attn_weights
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
class BeitMLP(nn.Module):
|
| 345 |
+
def __init__(self, config: BeitConfig):
|
| 346 |
+
super().__init__()
|
| 347 |
+
self.config = config
|
| 348 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 349 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 350 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 351 |
+
|
| 352 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 353 |
+
hidden_states = self.fc1(hidden_states)
|
| 354 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 355 |
+
hidden_states = self.fc2(hidden_states)
|
| 356 |
+
|
| 357 |
+
return hidden_states
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
class BeitDropPath(nn.Module):
|
| 361 |
+
"""Stochastic depth (DropPath) per sample, for residual blocks.
|
| 362 |
+
|
| 363 |
+
Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
|
| 364 |
+
<https://arxiv.org/abs/1603.09382>`_.
|
| 365 |
+
"""
|
| 366 |
+
|
| 367 |
+
def __init__(self, drop_prob: float = 0.0) -> None:
|
| 368 |
+
super().__init__()
|
| 369 |
+
self.drop_prob = drop_prob
|
| 370 |
+
|
| 371 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 372 |
+
if self.drop_prob == 0.0 or not self.training:
|
| 373 |
+
return hidden_states
|
| 374 |
+
keep_prob = 1 - self.drop_prob
|
| 375 |
+
shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
|
| 376 |
+
random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
|
| 377 |
+
random_tensor = torch.floor(random_tensor + keep_prob)
|
| 378 |
+
return hidden_states.div(keep_prob) * random_tensor
|
| 379 |
+
|
| 380 |
+
def extra_repr(self) -> str:
|
| 381 |
+
return f"p={self.drop_prob}"
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
class BeitLayer(GradientCheckpointingLayer):
|
| 385 |
+
"""This corresponds to the Block class in the timm implementation."""
|
| 386 |
+
|
| 387 |
+
def __init__(self, config: BeitConfig, drop_path_rate: float = 0.0):
|
| 388 |
+
super().__init__()
|
| 389 |
+
self.attention = BeitAttention(config)
|
| 390 |
+
self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 391 |
+
self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 392 |
+
self.mlp = BeitMLP(config)
|
| 393 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 394 |
+
self.patch_size = config.patch_size
|
| 395 |
+
self.drop_path = BeitDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
|
| 396 |
+
|
| 397 |
+
init_values = config.layer_scale_init_value
|
| 398 |
+
self.lambda_1 = (
|
| 399 |
+
nn.Parameter(init_values * torch.ones(config.hidden_size), requires_grad=True) if init_values > 0 else 1.0
|
| 400 |
+
)
|
| 401 |
+
self.lambda_2 = (
|
| 402 |
+
nn.Parameter(init_values * torch.ones(config.hidden_size), requires_grad=True) if init_values > 0 else 1.0
|
| 403 |
+
)
|
| 404 |
+
self.relative_position_bias = BeitRelativePositionBias(config) if config.use_relative_position_bias else None
|
| 405 |
+
|
| 406 |
+
def forward(
|
| 407 |
+
self,
|
| 408 |
+
hidden_states: torch.Tensor,
|
| 409 |
+
attention_mask: torch.Tensor | None = None,
|
| 410 |
+
interpolate_pos_encoding: bool = False,
|
| 411 |
+
resolution: tuple[int, int] | None = None,
|
| 412 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 413 |
+
) -> torch.Tensor:
|
| 414 |
+
if self.relative_position_bias is not None:
|
| 415 |
+
height, width = resolution
|
| 416 |
+
window_size = (height // self.patch_size, width // self.patch_size)
|
| 417 |
+
relative_position_bias = self.relative_position_bias(
|
| 418 |
+
window_size, interpolate_pos_encoding, dim_size=hidden_states.shape[1]
|
| 419 |
+
)
|
| 420 |
+
attention_mask = (
|
| 421 |
+
relative_position_bias + attention_mask if attention_mask is not None else relative_position_bias
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
# Self Attention
|
| 425 |
+
residual = hidden_states
|
| 426 |
+
hidden_states = self.layernorm_before(hidden_states)
|
| 427 |
+
hidden_states, _ = self.attention(
|
| 428 |
+
hidden_states,
|
| 429 |
+
attention_mask=attention_mask,
|
| 430 |
+
**kwargs,
|
| 431 |
+
)
|
| 432 |
+
hidden_states = self.dropout(hidden_states)
|
| 433 |
+
hidden_states = self.lambda_1 * hidden_states
|
| 434 |
+
hidden_states = self.drop_path(hidden_states) + residual
|
| 435 |
+
|
| 436 |
+
# Fully Connected
|
| 437 |
+
residual = hidden_states
|
| 438 |
+
hidden_states = self.layernorm_after(hidden_states)
|
| 439 |
+
hidden_states = self.mlp(hidden_states)
|
| 440 |
+
hidden_states = self.dropout(hidden_states)
|
| 441 |
+
hidden_states = self.lambda_2 * hidden_states
|
| 442 |
+
hidden_states = self.drop_path(hidden_states) + residual
|
| 443 |
+
|
| 444 |
+
return hidden_states
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
@auto_docstring
|
| 448 |
+
class BeitPreTrainedModel(PreTrainedModel):
|
| 449 |
+
config: BeitConfig
|
| 450 |
+
base_model_prefix = "beit"
|
| 451 |
+
main_input_name = "pixel_values"
|
| 452 |
+
input_modalities = ("image",)
|
| 453 |
+
supports_gradient_checkpointing = True
|
| 454 |
+
_no_split_modules = ["BeitLayer"]
|
| 455 |
+
_supports_sdpa = True
|
| 456 |
+
_supports_flash_attn = False
|
| 457 |
+
_supports_flex_attn = False
|
| 458 |
+
_supports_attention_backend = True
|
| 459 |
+
_can_compile_fullgraph = True
|
| 460 |
+
_can_record_outputs = {
|
| 461 |
+
"hidden_states": BeitLayer,
|
| 462 |
+
"attentions": BeitAttention,
|
| 463 |
+
}
|
| 464 |
+
_input_embed_layer = "patch_embeddings"
|
| 465 |
+
_keys_to_ignore_on_load_unexpected = [r".*relative_position_index.*"]
|
| 466 |
+
|
| 467 |
+
@torch.no_grad()
|
| 468 |
+
def _init_weights(self, module):
|
| 469 |
+
"""Initialize the weights"""
|
| 470 |
+
super()._init_weights(module)
|
| 471 |
+
if isinstance(module, BeitEmbeddings):
|
| 472 |
+
init.zeros_(module.cls_token)
|
| 473 |
+
if module.mask_token is not None:
|
| 474 |
+
init.zeros_(module.mask_token)
|
| 475 |
+
if module.position_embeddings is not None:
|
| 476 |
+
init.zeros_(module.position_embeddings)
|
| 477 |
+
elif isinstance(module, BeitRelativePositionBias):
|
| 478 |
+
init.zeros_(module.relative_position_bias_table)
|
| 479 |
+
elif isinstance(module, BeitLayer):
|
| 480 |
+
if isinstance(module.lambda_1, nn.Parameter):
|
| 481 |
+
init.constant_(module.lambda_1, self.config.layer_scale_init_value)
|
| 482 |
+
init.constant_(module.lambda_2, self.config.layer_scale_init_value)
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
@auto_docstring
|
| 486 |
+
class BeitModel(BeitPreTrainedModel):
|
| 487 |
+
def __init__(self, config: BeitConfig, add_pooling_layer: bool = True) -> None:
|
| 488 |
+
r"""
|
| 489 |
+
add_pooling_layer (bool, *optional*, defaults to `True`):
|
| 490 |
+
Whether to add a pooling layer
|
| 491 |
+
"""
|
| 492 |
+
super().__init__(config)
|
| 493 |
+
self.config = config
|
| 494 |
+
|
| 495 |
+
self.embeddings = BeitEmbeddings(config)
|
| 496 |
+
self.shared_position_bias = (
|
| 497 |
+
BeitRelativePositionBias(config) if config.use_shared_relative_position_bias else None
|
| 498 |
+
)
|
| 499 |
+
drop_path_rates = [
|
| 500 |
+
config.drop_path_rate * i / max(config.num_hidden_layers - 1, 1) for i in range(config.num_hidden_layers)
|
| 501 |
+
]
|
| 502 |
+
self.layers = nn.ModuleList([BeitLayer(config, drop_path_rate=r) for r in drop_path_rates])
|
| 503 |
+
|
| 504 |
+
self.layernorm = (
|
| 505 |
+
nn.Identity() if config.use_mean_pooling else nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 506 |
+
)
|
| 507 |
+
self.pooler = BeitPooler(config) if add_pooling_layer else None
|
| 508 |
+
|
| 509 |
+
# Initialize weights and apply final processing
|
| 510 |
+
self.post_init()
|
| 511 |
+
|
| 512 |
+
@merge_with_config_defaults
|
| 513 |
+
@capture_outputs(tie_last_hidden_states=False)
|
| 514 |
+
@auto_docstring
|
| 515 |
+
def forward(
|
| 516 |
+
self,
|
| 517 |
+
pixel_values: torch.Tensor,
|
| 518 |
+
bool_masked_pos: torch.BoolTensor | None = None,
|
| 519 |
+
interpolate_pos_encoding: bool = False,
|
| 520 |
+
attention_mask: torch.Tensor | None = None,
|
| 521 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 522 |
+
) -> BeitModelOutputWithPooling:
|
| 523 |
+
r"""
|
| 524 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
|
| 525 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
|
| 526 |
+
"""
|
| 527 |
+
embedding_output = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
|
| 528 |
+
resolution = pixel_values.shape[2:]
|
| 529 |
+
|
| 530 |
+
attention_mask = create_bidirectional_mask(
|
| 531 |
+
config=self.config,
|
| 532 |
+
inputs_embeds=embedding_output,
|
| 533 |
+
attention_mask=attention_mask,
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
if self.shared_position_bias is not None:
|
| 537 |
+
height, width = resolution
|
| 538 |
+
window_size = (height // self.config.patch_size, width // self.config.patch_size)
|
| 539 |
+
shared_relative_position_bias = self.shared_position_bias(
|
| 540 |
+
window_size, interpolate_pos_encoding=interpolate_pos_encoding, dim_size=embedding_output.shape[1]
|
| 541 |
+
)
|
| 542 |
+
attention_mask = (
|
| 543 |
+
shared_relative_position_bias + attention_mask
|
| 544 |
+
if attention_mask is not None
|
| 545 |
+
else shared_relative_position_bias
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
hidden_states = embedding_output
|
| 549 |
+
for layer in self.layers:
|
| 550 |
+
hidden_states = layer(
|
| 551 |
+
hidden_states,
|
| 552 |
+
attention_mask=attention_mask,
|
| 553 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 554 |
+
resolution=resolution,
|
| 555 |
+
**kwargs,
|
| 556 |
+
)
|
| 557 |
+
sequence_output = self.layernorm(hidden_states)
|
| 558 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 559 |
+
|
| 560 |
+
return BeitModelOutputWithPooling(last_hidden_state=sequence_output, pooler_output=pooled_output)
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
class BeitPooler(nn.Module):
|
| 564 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 565 |
+
super().__init__()
|
| 566 |
+
self.layernorm = (
|
| 567 |
+
nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) if config.use_mean_pooling else None
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 571 |
+
# Mean pool patch tokens with layernorm, or take the [CLS] token
|
| 572 |
+
return self.layernorm(hidden_states[:, 1:, :].mean(1)) if self.layernorm is not None else hidden_states[:, 0]
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
@auto_docstring(
|
| 576 |
+
custom_intro="""
|
| 577 |
+
Beit Model transformer with a 'language' modeling head on top. BEiT does masked image modeling by predicting
|
| 578 |
+
visual tokens of a Vector-Quantize Variational Autoencoder (VQ-VAE), whereas other vision models like ViT and DeiT
|
| 579 |
+
predict RGB pixel values. As a result, this class is incompatible with [`AutoModelForMaskedImageModeling`], so you
|
| 580 |
+
will need to use [`BeitForMaskedImageModeling`] directly if you wish to do masked image modeling with BEiT.
|
| 581 |
+
"""
|
| 582 |
+
)
|
| 583 |
+
class BeitForMaskedImageModeling(BeitPreTrainedModel):
|
| 584 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 585 |
+
super().__init__(config)
|
| 586 |
+
|
| 587 |
+
self.num_labels = config.num_labels
|
| 588 |
+
self.beit = BeitModel(config, add_pooling_layer=False)
|
| 589 |
+
|
| 590 |
+
# Classifier head
|
| 591 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 592 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size)
|
| 593 |
+
|
| 594 |
+
# Initialize weights and apply final processing
|
| 595 |
+
self.post_init()
|
| 596 |
+
|
| 597 |
+
def get_output_embeddings(self):
|
| 598 |
+
return None
|
| 599 |
+
|
| 600 |
+
@can_return_tuple
|
| 601 |
+
@auto_docstring
|
| 602 |
+
def forward(
|
| 603 |
+
self,
|
| 604 |
+
pixel_values: torch.Tensor | None = None,
|
| 605 |
+
bool_masked_pos: torch.BoolTensor | None = None,
|
| 606 |
+
labels: torch.Tensor | None = None,
|
| 607 |
+
interpolate_pos_encoding: bool = False,
|
| 608 |
+
attention_mask: torch.Tensor | None = None,
|
| 609 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 610 |
+
) -> tuple | MaskedLMOutput:
|
| 611 |
+
r"""
|
| 612 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
|
| 613 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
|
| 614 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 615 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 616 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 617 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 618 |
+
|
| 619 |
+
Examples:
|
| 620 |
+
|
| 621 |
+
```python
|
| 622 |
+
>>> from transformers import AutoImageProcessor, BeitForMaskedImageModeling
|
| 623 |
+
>>> import torch
|
| 624 |
+
>>> from PIL import Image
|
| 625 |
+
>>> import requests
|
| 626 |
+
|
| 627 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 628 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 629 |
+
|
| 630 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-patch16-224-pt22k")
|
| 631 |
+
>>> model = BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k")
|
| 632 |
+
|
| 633 |
+
>>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
|
| 634 |
+
>>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
|
| 635 |
+
>>> # create random boolean mask of shape (batch_size, num_patches)
|
| 636 |
+
>>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
|
| 637 |
+
|
| 638 |
+
>>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
|
| 639 |
+
>>> loss, logits = outputs.loss, outputs.logits
|
| 640 |
+
>>> list(logits.shape)
|
| 641 |
+
[1, 196, 8192]
|
| 642 |
+
```"""
|
| 643 |
+
|
| 644 |
+
outputs = self.beit(
|
| 645 |
+
pixel_values,
|
| 646 |
+
bool_masked_pos=bool_masked_pos,
|
| 647 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 648 |
+
attention_mask=attention_mask,
|
| 649 |
+
**kwargs,
|
| 650 |
+
)
|
| 651 |
+
|
| 652 |
+
sequence_output = outputs.last_hidden_state
|
| 653 |
+
sequence_output = self.layernorm(sequence_output)
|
| 654 |
+
prediction_scores = self.lm_head(sequence_output[:, 1:])
|
| 655 |
+
|
| 656 |
+
masked_lm_loss = None
|
| 657 |
+
if labels is not None:
|
| 658 |
+
loss_fct = nn.CrossEntropyLoss() # -100 index = padding token
|
| 659 |
+
masked_lm_loss = loss_fct(prediction_scores[bool_masked_pos], labels)
|
| 660 |
+
|
| 661 |
+
return MaskedLMOutput(
|
| 662 |
+
loss=masked_lm_loss,
|
| 663 |
+
logits=prediction_scores,
|
| 664 |
+
hidden_states=outputs.hidden_states,
|
| 665 |
+
attentions=outputs.attentions,
|
| 666 |
+
)
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
@auto_docstring(
|
| 670 |
+
custom_intro="""
|
| 671 |
+
Beit Model transformer with an image classification head on top (a linear layer on top of the average of the final
|
| 672 |
+
hidden states of the patch tokens) e.g. for ImageNet.
|
| 673 |
+
"""
|
| 674 |
+
)
|
| 675 |
+
class BeitForImageClassification(BeitPreTrainedModel):
|
| 676 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 677 |
+
super().__init__(config)
|
| 678 |
+
|
| 679 |
+
self.num_labels = config.num_labels
|
| 680 |
+
self.beit = BeitModel(config, add_pooling_layer=True)
|
| 681 |
+
|
| 682 |
+
# Classifier head
|
| 683 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 684 |
+
|
| 685 |
+
# Initialize weights and apply final processing
|
| 686 |
+
self.post_init()
|
| 687 |
+
|
| 688 |
+
@can_return_tuple
|
| 689 |
+
@auto_docstring
|
| 690 |
+
def forward(
|
| 691 |
+
self,
|
| 692 |
+
pixel_values: torch.Tensor | None = None,
|
| 693 |
+
labels: torch.Tensor | None = None,
|
| 694 |
+
interpolate_pos_encoding: bool = False,
|
| 695 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 696 |
+
) -> tuple | ImageClassifierOutput:
|
| 697 |
+
r"""
|
| 698 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 699 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 700 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 701 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 702 |
+
"""
|
| 703 |
+
outputs = self.beit(
|
| 704 |
+
pixel_values,
|
| 705 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 706 |
+
**kwargs,
|
| 707 |
+
)
|
| 708 |
+
|
| 709 |
+
pooled_output = outputs.pooler_output
|
| 710 |
+
|
| 711 |
+
logits = self.classifier(pooled_output)
|
| 712 |
+
|
| 713 |
+
loss = None
|
| 714 |
+
if labels is not None:
|
| 715 |
+
loss = self.loss_function(labels, logits, self.config)
|
| 716 |
+
|
| 717 |
+
return ImageClassifierOutput(
|
| 718 |
+
loss=loss,
|
| 719 |
+
logits=logits,
|
| 720 |
+
hidden_states=outputs.hidden_states,
|
| 721 |
+
attentions=outputs.attentions,
|
| 722 |
+
)
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
class BeitConvLayer(nn.Module):
|
| 726 |
+
def __init__(
|
| 727 |
+
self,
|
| 728 |
+
in_channels: int,
|
| 729 |
+
out_channels: int,
|
| 730 |
+
kernel_size: int | tuple[int, int] = 3,
|
| 731 |
+
stride: int = 1,
|
| 732 |
+
padding: int | tuple[int, int] | str = 0,
|
| 733 |
+
bias: bool = False,
|
| 734 |
+
dilation: int | tuple[int, int] = 1,
|
| 735 |
+
groups: int = 1,
|
| 736 |
+
activation: str = "relu",
|
| 737 |
+
):
|
| 738 |
+
super().__init__()
|
| 739 |
+
self.convolution = nn.Conv2d(
|
| 740 |
+
in_channels=in_channels,
|
| 741 |
+
out_channels=out_channels,
|
| 742 |
+
kernel_size=kernel_size,
|
| 743 |
+
stride=stride,
|
| 744 |
+
padding=padding,
|
| 745 |
+
dilation=dilation,
|
| 746 |
+
groups=groups,
|
| 747 |
+
bias=bias,
|
| 748 |
+
)
|
| 749 |
+
self.normalization = nn.BatchNorm2d(out_channels)
|
| 750 |
+
self.activation = ACT2FN[activation] if activation is not None else nn.Identity()
|
| 751 |
+
|
| 752 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 753 |
+
hidden_states = self.convolution(hidden_states)
|
| 754 |
+
hidden_states = self.normalization(hidden_states)
|
| 755 |
+
hidden_states = self.activation(hidden_states)
|
| 756 |
+
return hidden_states
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
class BeitPyramidPoolingBlock(nn.Module):
|
| 760 |
+
def __init__(self, pool_scale: int, in_channels: int, channels: int) -> None:
|
| 761 |
+
super().__init__()
|
| 762 |
+
self.pooling = nn.AdaptiveAvgPool2d(pool_scale)
|
| 763 |
+
self.conv = BeitConvLayer(in_channels, channels, kernel_size=1)
|
| 764 |
+
|
| 765 |
+
def forward(self, input: torch.Tensor, size: tuple[int, int]) -> torch.Tensor:
|
| 766 |
+
hidden_state = self.pooling(input)
|
| 767 |
+
hidden_state = self.conv(hidden_state)
|
| 768 |
+
hidden_state = nn.functional.interpolate(hidden_state, size=size, mode="bilinear", align_corners=False)
|
| 769 |
+
return hidden_state
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
class BeitPyramidPoolingModule(nn.Module):
|
| 773 |
+
"""
|
| 774 |
+
Pyramid Pooling Module (PPM) used in PSPNet.
|
| 775 |
+
|
| 776 |
+
Args:
|
| 777 |
+
pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
|
| 778 |
+
Module.
|
| 779 |
+
in_channels (int): Input channels.
|
| 780 |
+
channels (int): Channels after modules, before conv_seg.
|
| 781 |
+
|
| 782 |
+
Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
|
| 783 |
+
"""
|
| 784 |
+
|
| 785 |
+
def __init__(self, pool_scales: tuple[int, ...], in_channels: int, channels: int) -> None:
|
| 786 |
+
super().__init__()
|
| 787 |
+
self.pool_scales = pool_scales
|
| 788 |
+
self.in_channels = in_channels
|
| 789 |
+
self.channels = channels
|
| 790 |
+
self.blocks = nn.ModuleList(
|
| 791 |
+
[
|
| 792 |
+
BeitPyramidPoolingBlock(pool_scale=pool_scale, in_channels=in_channels, channels=channels)
|
| 793 |
+
for pool_scale in pool_scales
|
| 794 |
+
]
|
| 795 |
+
)
|
| 796 |
+
|
| 797 |
+
def forward(self, hidden_states: torch.Tensor) -> list[torch.Tensor]:
|
| 798 |
+
original_size = hidden_states.size()[2:]
|
| 799 |
+
return [block(hidden_states, size=original_size) for block in self.blocks]
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
class BeitUperHead(nn.Module):
|
| 803 |
+
"""
|
| 804 |
+
Unified Perceptual Parsing for Scene Understanding. This head is the implementation of
|
| 805 |
+
[UPerNet](https://huggingface.co/papers/1807.10221).
|
| 806 |
+
|
| 807 |
+
Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
|
| 808 |
+
"""
|
| 809 |
+
|
| 810 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 811 |
+
super().__init__()
|
| 812 |
+
|
| 813 |
+
self.pool_scales = config.pool_scales # e.g. (1, 2, 3, 6)
|
| 814 |
+
self.in_channels = [config.hidden_size] * 4 # e.g. [768, 768, 768, 768]
|
| 815 |
+
self.channels = config.hidden_size
|
| 816 |
+
self.classifier = nn.Conv2d(self.channels, config.num_labels, kernel_size=1)
|
| 817 |
+
|
| 818 |
+
# PSP Module
|
| 819 |
+
self.psp_modules = BeitPyramidPoolingModule(
|
| 820 |
+
self.pool_scales,
|
| 821 |
+
self.in_channels[-1],
|
| 822 |
+
self.channels,
|
| 823 |
+
)
|
| 824 |
+
self.psp_bottleneck = BeitConvLayer(
|
| 825 |
+
self.in_channels[-1] + len(self.pool_scales) * self.channels,
|
| 826 |
+
self.channels,
|
| 827 |
+
kernel_size=3,
|
| 828 |
+
padding=1,
|
| 829 |
+
)
|
| 830 |
+
# FPN Module
|
| 831 |
+
self.lateral_convs = nn.ModuleList()
|
| 832 |
+
self.fpn_convs = nn.ModuleList()
|
| 833 |
+
for in_channels in self.in_channels[:-1]: # skip the top layer
|
| 834 |
+
self.lateral_convs.append(BeitConvLayer(in_channels, self.channels, kernel_size=1))
|
| 835 |
+
self.fpn_convs.append(BeitConvLayer(self.channels, self.channels, kernel_size=3, padding=1))
|
| 836 |
+
|
| 837 |
+
self.fpn_bottleneck = BeitConvLayer(
|
| 838 |
+
len(self.in_channels) * self.channels,
|
| 839 |
+
self.channels,
|
| 840 |
+
kernel_size=3,
|
| 841 |
+
padding=1,
|
| 842 |
+
)
|
| 843 |
+
|
| 844 |
+
def psp_forward(self, hidden_states: list[torch.Tensor]) -> torch.Tensor:
|
| 845 |
+
hidden_state = hidden_states[-1]
|
| 846 |
+
hidden_state = torch.cat([hidden_state, *self.psp_modules(hidden_state)], dim=1)
|
| 847 |
+
return self.psp_bottleneck(hidden_state)
|
| 848 |
+
|
| 849 |
+
def forward(self, encoder_hidden_states: list[torch.Tensor]) -> torch.Tensor:
|
| 850 |
+
# build laterals
|
| 851 |
+
laterals = []
|
| 852 |
+
for lateral_conv, hidden_state in zip(self.lateral_convs, encoder_hidden_states):
|
| 853 |
+
laterals.append(lateral_conv(hidden_state))
|
| 854 |
+
|
| 855 |
+
laterals.append(self.psp_forward(encoder_hidden_states))
|
| 856 |
+
|
| 857 |
+
# build top-down path
|
| 858 |
+
used_backbone_levels = len(laterals)
|
| 859 |
+
for i in range(used_backbone_levels - 1, 0, -1):
|
| 860 |
+
prev_shape = laterals[i - 1].shape[2:]
|
| 861 |
+
laterals[i - 1] = laterals[i - 1] + nn.functional.interpolate(
|
| 862 |
+
laterals[i], size=prev_shape, mode="bilinear", align_corners=False
|
| 863 |
+
)
|
| 864 |
+
|
| 865 |
+
# build outputs
|
| 866 |
+
fpn_outs = []
|
| 867 |
+
for i in range(used_backbone_levels - 1):
|
| 868 |
+
fpn_outs.append(self.fpn_convs[i](laterals[i]))
|
| 869 |
+
# append psp feature
|
| 870 |
+
fpn_outs.append(laterals[-1])
|
| 871 |
+
|
| 872 |
+
for i in range(used_backbone_levels - 1, 0, -1):
|
| 873 |
+
fpn_outs[i] = nn.functional.interpolate(
|
| 874 |
+
fpn_outs[i], size=fpn_outs[0].shape[2:], mode="bilinear", align_corners=False
|
| 875 |
+
)
|
| 876 |
+
fpn_outs = torch.cat(fpn_outs, dim=1)
|
| 877 |
+
output = self.fpn_bottleneck(fpn_outs)
|
| 878 |
+
output = self.classifier(output)
|
| 879 |
+
|
| 880 |
+
return output
|
| 881 |
+
|
| 882 |
+
|
| 883 |
+
class BeitFCNHead(nn.Module):
|
| 884 |
+
"""
|
| 885 |
+
Fully Convolution Networks for Semantic Segmentation. This head is implemented of
|
| 886 |
+
[FCNNet](https://huggingface.co/papers/1411.4038>).
|
| 887 |
+
|
| 888 |
+
Args:
|
| 889 |
+
config (BeitConfig): Configuration.
|
| 890 |
+
in_channels
|
| 891 |
+
kernel_size (int): The kernel size for convs in the head. Default: 3.
|
| 892 |
+
dilation (int): The dilation rate for convs in the head. Default: 1.
|
| 893 |
+
|
| 894 |
+
|
| 895 |
+
Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
|
| 896 |
+
"""
|
| 897 |
+
|
| 898 |
+
def __init__(
|
| 899 |
+
self, config: BeitConfig, in_index: int = 2, kernel_size: int = 3, dilation: int | tuple[int, int] = 1
|
| 900 |
+
) -> None:
|
| 901 |
+
super().__init__()
|
| 902 |
+
self.in_channels = config.hidden_size
|
| 903 |
+
self.channels = config.auxiliary_channels
|
| 904 |
+
self.num_convs = config.auxiliary_num_convs
|
| 905 |
+
self.concat_input = config.auxiliary_concat_input
|
| 906 |
+
self.in_index = in_index
|
| 907 |
+
|
| 908 |
+
conv_padding = (kernel_size // 2) * dilation
|
| 909 |
+
self.convs = nn.ModuleList()
|
| 910 |
+
if self.num_convs > 0:
|
| 911 |
+
self.convs.append(
|
| 912 |
+
BeitConvLayer(
|
| 913 |
+
self.in_channels, self.channels, kernel_size=kernel_size, padding=conv_padding, dilation=dilation
|
| 914 |
+
)
|
| 915 |
+
)
|
| 916 |
+
for _ in range(self.num_convs - 1):
|
| 917 |
+
self.convs.append(
|
| 918 |
+
BeitConvLayer(
|
| 919 |
+
self.channels,
|
| 920 |
+
self.channels,
|
| 921 |
+
kernel_size=kernel_size,
|
| 922 |
+
padding=conv_padding,
|
| 923 |
+
dilation=dilation,
|
| 924 |
+
)
|
| 925 |
+
)
|
| 926 |
+
if self.concat_input:
|
| 927 |
+
self.conv_cat = BeitConvLayer(
|
| 928 |
+
self.in_channels + self.channels, self.channels, kernel_size=kernel_size, padding=kernel_size // 2
|
| 929 |
+
)
|
| 930 |
+
|
| 931 |
+
self.classifier = nn.Conv2d(self.channels, config.num_labels, kernel_size=1)
|
| 932 |
+
|
| 933 |
+
def forward(self, encoder_hidden_states: list[torch.Tensor]) -> torch.Tensor:
|
| 934 |
+
residual = encoder_hidden_states[self.in_index]
|
| 935 |
+
hidden_states = residual
|
| 936 |
+
for conv in self.convs:
|
| 937 |
+
hidden_states = conv(hidden_states)
|
| 938 |
+
if self.concat_input:
|
| 939 |
+
hidden_states = self.conv_cat(torch.cat([residual, hidden_states], dim=1))
|
| 940 |
+
hidden_states = self.classifier(hidden_states)
|
| 941 |
+
return hidden_states
|
| 942 |
+
|
| 943 |
+
|
| 944 |
+
class BeitFPNUpBlock(nn.Module):
|
| 945 |
+
"""4x upsampling block: ConvTranspose → BN → GELU → ConvTranspose."""
|
| 946 |
+
|
| 947 |
+
def __init__(self, hidden_size: int, kernel_size: int = 2, stride: int = 2) -> None:
|
| 948 |
+
super().__init__()
|
| 949 |
+
self.conv_transpose1 = nn.ConvTranspose2d(hidden_size, hidden_size, kernel_size=kernel_size, stride=stride)
|
| 950 |
+
self.normalization = nn.BatchNorm2d(hidden_size)
|
| 951 |
+
self.activation = nn.GELU()
|
| 952 |
+
self.conv_transpose2 = nn.ConvTranspose2d(hidden_size, hidden_size, kernel_size=kernel_size, stride=stride)
|
| 953 |
+
|
| 954 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 955 |
+
hidden_states = self.conv_transpose1(hidden_states)
|
| 956 |
+
hidden_states = self.normalization(hidden_states)
|
| 957 |
+
hidden_states = self.activation(hidden_states)
|
| 958 |
+
hidden_states = self.conv_transpose2(hidden_states)
|
| 959 |
+
return hidden_states
|
| 960 |
+
|
| 961 |
+
|
| 962 |
+
class BeitFPNNeck(nn.Module):
|
| 963 |
+
"""
|
| 964 |
+
4-level feature pyramid neck for BeiT. Produces x4 upsample, x2 upsample,
|
| 965 |
+
identity, and x2 downsample outputs from the four selected ViT feature maps.
|
| 966 |
+
"""
|
| 967 |
+
|
| 968 |
+
def __init__(self, config: BeitConfig):
|
| 969 |
+
super().__init__()
|
| 970 |
+
self.fpn1 = BeitFPNUpBlock(config.hidden_size)
|
| 971 |
+
self.fpn2 = nn.ConvTranspose2d(config.hidden_size, config.hidden_size, kernel_size=2, stride=2)
|
| 972 |
+
self.fpn4 = nn.MaxPool2d(kernel_size=2, stride=2)
|
| 973 |
+
|
| 974 |
+
def forward(self, feature_maps: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
|
| 975 |
+
return (
|
| 976 |
+
self.fpn1(feature_maps[0]),
|
| 977 |
+
self.fpn2(feature_maps[1]),
|
| 978 |
+
feature_maps[2], # identity: native patch-grid resolution
|
| 979 |
+
self.fpn4(feature_maps[3]),
|
| 980 |
+
)
|
| 981 |
+
|
| 982 |
+
|
| 983 |
+
@auto_docstring
|
| 984 |
+
class BeitForSemanticSegmentation(BeitPreTrainedModel):
|
| 985 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 986 |
+
super().__init__(config)
|
| 987 |
+
|
| 988 |
+
self.num_labels = config.num_labels
|
| 989 |
+
self.beit = BeitModel(config, add_pooling_layer=False)
|
| 990 |
+
|
| 991 |
+
if len(self.config.out_indices) != 4:
|
| 992 |
+
raise ValueError(
|
| 993 |
+
"BeitForSemanticSegmentation requires config.out_indices to be a list of 4 integers, "
|
| 994 |
+
"specifying which features to use from the backbone. One can use [3, 5, 7, 11] in case of "
|
| 995 |
+
"a base-sized architecture."
|
| 996 |
+
)
|
| 997 |
+
self.fpn = BeitFPNNeck(config)
|
| 998 |
+
|
| 999 |
+
# Semantic segmentation head(s)
|
| 1000 |
+
self.decode_head = BeitUperHead(config)
|
| 1001 |
+
self.auxiliary_head = BeitFCNHead(config) if config.use_auxiliary_head else None
|
| 1002 |
+
|
| 1003 |
+
# Initialize weights and apply final processing
|
| 1004 |
+
self.post_init()
|
| 1005 |
+
|
| 1006 |
+
@can_return_tuple
|
| 1007 |
+
@filter_output_hidden_states
|
| 1008 |
+
@auto_docstring
|
| 1009 |
+
def forward(
|
| 1010 |
+
self,
|
| 1011 |
+
pixel_values: torch.Tensor | None = None,
|
| 1012 |
+
labels: torch.Tensor | None = None,
|
| 1013 |
+
interpolate_pos_encoding: bool = False,
|
| 1014 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1015 |
+
) -> tuple | SemanticSegmenterOutput:
|
| 1016 |
+
r"""
|
| 1017 |
+
labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
|
| 1018 |
+
Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ...,
|
| 1019 |
+
config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy).
|
| 1020 |
+
|
| 1021 |
+
Examples:
|
| 1022 |
+
|
| 1023 |
+
```python
|
| 1024 |
+
>>> from transformers import AutoImageProcessor, BeitForSemanticSegmentation
|
| 1025 |
+
>>> from PIL import Image
|
| 1026 |
+
>>> import requests
|
| 1027 |
+
|
| 1028 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1029 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1030 |
+
|
| 1031 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-finetuned-ade-640-640")
|
| 1032 |
+
>>> model = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640")
|
| 1033 |
+
|
| 1034 |
+
>>> inputs = image_processor(images=image, return_tensors="pt")
|
| 1035 |
+
>>> outputs = model(**inputs)
|
| 1036 |
+
>>> # logits are of shape (batch_size, num_labels, height, width)
|
| 1037 |
+
>>> logits = outputs.logits
|
| 1038 |
+
```"""
|
| 1039 |
+
if labels is not None and self.config.num_labels == 1:
|
| 1040 |
+
raise ValueError("The number of labels should be greater than one")
|
| 1041 |
+
kwargs["output_hidden_states"] = True
|
| 1042 |
+
outputs = self.beit(
|
| 1043 |
+
pixel_values,
|
| 1044 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1045 |
+
**kwargs,
|
| 1046 |
+
)
|
| 1047 |
+
|
| 1048 |
+
encoder_hidden_states = outputs.hidden_states
|
| 1049 |
+
batch_size, _, height, width = pixel_values.shape
|
| 1050 |
+
patch_height = height // self.config.patch_size
|
| 1051 |
+
patch_width = width // self.config.patch_size
|
| 1052 |
+
|
| 1053 |
+
# out_indices are 1-based into encoder_hidden_states (index 0 is the initial patch embedding).
|
| 1054 |
+
# Remove the CLS token ([:, 1:]) and reshape from sequence to 2D spatial feature maps.
|
| 1055 |
+
feature_maps = tuple(
|
| 1056 |
+
encoder_hidden_states[i - 1][:, 1:].transpose(1, 2).reshape(batch_size, -1, patch_height, patch_width)
|
| 1057 |
+
for i in self.config.out_indices
|
| 1058 |
+
)
|
| 1059 |
+
feature_maps = self.fpn(feature_maps)
|
| 1060 |
+
|
| 1061 |
+
logits = self.decode_head(feature_maps)
|
| 1062 |
+
|
| 1063 |
+
auxiliary_logits = None
|
| 1064 |
+
if self.auxiliary_head is not None:
|
| 1065 |
+
auxiliary_logits = self.auxiliary_head(feature_maps)
|
| 1066 |
+
|
| 1067 |
+
loss = None
|
| 1068 |
+
if labels is not None:
|
| 1069 |
+
loss = self.loss_function(
|
| 1070 |
+
logits,
|
| 1071 |
+
labels,
|
| 1072 |
+
ignore_index=self.config.semantic_loss_ignore_index,
|
| 1073 |
+
auxiliary_logits=auxiliary_logits,
|
| 1074 |
+
auxiliary_loss_weight=self.config.auxiliary_loss_weight,
|
| 1075 |
+
)
|
| 1076 |
+
return SemanticSegmenterOutput(
|
| 1077 |
+
loss=loss,
|
| 1078 |
+
logits=logits,
|
| 1079 |
+
hidden_states=outputs.hidden_states,
|
| 1080 |
+
attentions=outputs.attentions,
|
| 1081 |
+
)
|
| 1082 |
+
|
| 1083 |
+
|
| 1084 |
+
@auto_docstring(
|
| 1085 |
+
custom_intro="""
|
| 1086 |
+
BEiT backbone, to be used with frameworks like DETR and MaskFormer.
|
| 1087 |
+
"""
|
| 1088 |
+
)
|
| 1089 |
+
class BeitBackbone(BackboneMixin, BeitPreTrainedModel):
|
| 1090 |
+
def __init__(self, config):
|
| 1091 |
+
super().__init__(config)
|
| 1092 |
+
|
| 1093 |
+
self.num_features = [config.hidden_size for _ in range(config.num_hidden_layers + 1)]
|
| 1094 |
+
self.beit = BeitModel(config, add_pooling_layer=False)
|
| 1095 |
+
self.fpn = BeitFPNNeck(config) if config.add_fpn else nn.Identity()
|
| 1096 |
+
|
| 1097 |
+
# initialize weights and apply final processing
|
| 1098 |
+
self.post_init()
|
| 1099 |
+
|
| 1100 |
+
@can_return_tuple
|
| 1101 |
+
@filter_output_hidden_states
|
| 1102 |
+
@auto_docstring
|
| 1103 |
+
def forward(
|
| 1104 |
+
self,
|
| 1105 |
+
pixel_values: Tensor,
|
| 1106 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1107 |
+
) -> BackboneOutput:
|
| 1108 |
+
r"""
|
| 1109 |
+
Examples:
|
| 1110 |
+
|
| 1111 |
+
```python
|
| 1112 |
+
>>> from transformers import AutoImageProcessor, AutoBackbone
|
| 1113 |
+
>>> import torch
|
| 1114 |
+
>>> from PIL import Image
|
| 1115 |
+
>>> import requests
|
| 1116 |
+
|
| 1117 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1118 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1119 |
+
|
| 1120 |
+
>>> processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-patch16-224")
|
| 1121 |
+
>>> model = AutoBackbone.from_pretrained(
|
| 1122 |
+
... "microsoft/beit-base-patch16-224", out_features=["stage1", "stage2", "stage3", "stage4"]
|
| 1123 |
+
... )
|
| 1124 |
+
|
| 1125 |
+
>>> inputs = processor(image, return_tensors="pt")
|
| 1126 |
+
|
| 1127 |
+
>>> outputs = model(**inputs)
|
| 1128 |
+
>>> feature_maps = outputs.feature_maps
|
| 1129 |
+
>>> list(feature_maps[-1].shape)
|
| 1130 |
+
[1, 768, 14, 14]
|
| 1131 |
+
```"""
|
| 1132 |
+
batch_size, _, height, width = pixel_values.shape
|
| 1133 |
+
patch_height = height // self.config.patch_size
|
| 1134 |
+
patch_width = width // self.config.patch_size
|
| 1135 |
+
kwargs["output_hidden_states"] = True # required to extract per-stage feature maps from hidden_states
|
| 1136 |
+
outputs = self.beit(pixel_values, **kwargs)
|
| 1137 |
+
|
| 1138 |
+
hidden_states = outputs.hidden_states
|
| 1139 |
+
feature_maps = ()
|
| 1140 |
+
for stage, hidden_state in zip(self.stage_names, hidden_states):
|
| 1141 |
+
if stage in self.out_features:
|
| 1142 |
+
if self.config.reshape_hidden_states:
|
| 1143 |
+
hidden_state = hidden_state[:, 1:, :]
|
| 1144 |
+
hidden_state = hidden_state.transpose(1, 2)
|
| 1145 |
+
hidden_state = hidden_state.reshape(batch_size, -1, patch_height, patch_width)
|
| 1146 |
+
|
| 1147 |
+
feature_maps += (hidden_state,)
|
| 1148 |
+
|
| 1149 |
+
feature_maps = self.fpn(feature_maps)
|
| 1150 |
+
|
| 1151 |
+
return BackboneOutput(
|
| 1152 |
+
feature_maps=feature_maps,
|
| 1153 |
+
hidden_states=outputs.hidden_states,
|
| 1154 |
+
attentions=outputs.attentions,
|
| 1155 |
+
)
|
| 1156 |
+
|
| 1157 |
+
|
| 1158 |
+
__all__ = [
|
| 1159 |
+
"BeitForImageClassification",
|
| 1160 |
+
"BeitForMaskedImageModeling",
|
| 1161 |
+
"BeitForSemanticSegmentation",
|
| 1162 |
+
"BeitModel",
|
| 1163 |
+
"BeitPreTrainedModel",
|
| 1164 |
+
"BeitBackbone",
|
| 1165 |
+
]
|
lib/python3.11/site-packages/transformers/models/beit/modular_beit.py
ADDED
|
@@ -0,0 +1,964 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PyTorch BEiT model."""
|
| 15 |
+
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from torch import Tensor, nn
|
| 20 |
+
|
| 21 |
+
from ... import initialization as init
|
| 22 |
+
from ...backbone_utils import BackboneMixin, filter_output_hidden_states
|
| 23 |
+
from ...masking_utils import create_bidirectional_mask
|
| 24 |
+
from ...modeling_outputs import (
|
| 25 |
+
BackboneOutput,
|
| 26 |
+
BaseModelOutputWithPooling,
|
| 27 |
+
ImageClassifierOutput,
|
| 28 |
+
MaskedLMOutput,
|
| 29 |
+
SemanticSegmenterOutput,
|
| 30 |
+
)
|
| 31 |
+
from ...modeling_utils import PreTrainedModel
|
| 32 |
+
from ...processing_utils import Unpack
|
| 33 |
+
from ...pytorch_utils import compile_compatible_method_lru_cache
|
| 34 |
+
from ...utils import TransformersKwargs, auto_docstring, torch_int
|
| 35 |
+
from ...utils.generic import can_return_tuple, merge_with_config_defaults
|
| 36 |
+
from ...utils.output_capturing import capture_outputs
|
| 37 |
+
from ..resnet.modeling_resnet import ResNetConvLayer
|
| 38 |
+
from ..swin.modeling_swin import SwinDropPath
|
| 39 |
+
from ..vit.modeling_vit import ViTAttention, ViTEmbeddings, ViTLayer, ViTMLP, ViTPatchEmbeddings, ViTPreTrainedModel
|
| 40 |
+
from .configuration_beit import BeitConfig
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@auto_docstring(
|
| 44 |
+
custom_intro="""
|
| 45 |
+
Class for outputs of [`BeitModel`].
|
| 46 |
+
"""
|
| 47 |
+
)
|
| 48 |
+
@dataclass
|
| 49 |
+
class BeitModelOutputWithPooling(BaseModelOutputWithPooling):
|
| 50 |
+
r"""
|
| 51 |
+
pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
|
| 52 |
+
Average of the last layer hidden states of the patch tokens (excluding the *[CLS]* token) if
|
| 53 |
+
*config.use_mean_pooling* is set to True. If set to False, then the final hidden state of the *[CLS]* token
|
| 54 |
+
will be returned.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class BeitPatchEmbeddings(ViTPatchEmbeddings):
|
| 59 |
+
pass
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class BeitEmbeddings(ViTEmbeddings):
|
| 63 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 64 |
+
nn.Module.__init__(self)
|
| 65 |
+
|
| 66 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 67 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) if config.use_mask_token else None
|
| 68 |
+
self.patch_embeddings = BeitPatchEmbeddings(config)
|
| 69 |
+
self.patch_size = config.patch_size
|
| 70 |
+
num_patches = self.patch_embeddings.num_patches
|
| 71 |
+
self.position_embeddings = (
|
| 72 |
+
nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size))
|
| 73 |
+
if config.use_absolute_position_embeddings
|
| 74 |
+
else None
|
| 75 |
+
)
|
| 76 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 77 |
+
|
| 78 |
+
def forward(
|
| 79 |
+
self,
|
| 80 |
+
pixel_values: torch.Tensor,
|
| 81 |
+
bool_masked_pos: torch.BoolTensor | None = None,
|
| 82 |
+
) -> torch.Tensor:
|
| 83 |
+
_, _, height, width = pixel_values.shape
|
| 84 |
+
embeddings = self.patch_embeddings(pixel_values)
|
| 85 |
+
batch_size, seq_len, _ = embeddings.size()
|
| 86 |
+
|
| 87 |
+
if bool_masked_pos is not None:
|
| 88 |
+
mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
|
| 89 |
+
# replace the masked visual tokens by mask_tokens
|
| 90 |
+
mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
|
| 91 |
+
embeddings = embeddings * (1 - mask) + mask_tokens * mask
|
| 92 |
+
|
| 93 |
+
cls_tokens = self.cls_token.expand(batch_size, -1, -1)
|
| 94 |
+
embeddings = torch.cat((cls_tokens, embeddings), dim=1)
|
| 95 |
+
|
| 96 |
+
if self.position_embeddings is not None:
|
| 97 |
+
embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
|
| 98 |
+
|
| 99 |
+
embeddings = self.dropout(embeddings)
|
| 100 |
+
|
| 101 |
+
return embeddings
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class BeitRelativePositionBias(nn.Module):
|
| 105 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 106 |
+
super().__init__()
|
| 107 |
+
image_size = config.image_size
|
| 108 |
+
if not isinstance(image_size, (tuple, list)):
|
| 109 |
+
image_size = (image_size, image_size)
|
| 110 |
+
self.window_size = (image_size[0] // config.patch_size, image_size[1] // config.patch_size)
|
| 111 |
+
self.num_relative_distance = (2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1) + 3
|
| 112 |
+
self.relative_position_bias_table = nn.Parameter(
|
| 113 |
+
torch.zeros(self.num_relative_distance, config.num_attention_heads)
|
| 114 |
+
) # 2*Wh-1 * 2*Ww-1, nH
|
| 115 |
+
# cls to token & token 2 cls & cls to cls
|
| 116 |
+
|
| 117 |
+
@staticmethod
|
| 118 |
+
@compile_compatible_method_lru_cache(maxsize=10)
|
| 119 |
+
def generate_relative_position_index(window_size: tuple[int, int]) -> torch.Tensor:
|
| 120 |
+
"""
|
| 121 |
+
This method creates the relative position index, modified to support arbitrary window sizes,
|
| 122 |
+
as introduced in [MiDaS v3.1](https://huggingface.co/papers/2307.14460).
|
| 123 |
+
"""
|
| 124 |
+
num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
|
| 125 |
+
window_area = window_size[0] * window_size[1]
|
| 126 |
+
|
| 127 |
+
# Pair-wise relative position index for each token inside the window
|
| 128 |
+
coords_flatten = torch.flatten(
|
| 129 |
+
torch.stack(torch.meshgrid(torch.arange(window_size[0]), torch.arange(window_size[1]), indexing="ij")),
|
| 130 |
+
start_dim=1,
|
| 131 |
+
) # 2, Wh*Ww
|
| 132 |
+
relative_coords = (coords_flatten[:, :, None] - coords_flatten[:, None, :]).permute(1, 2, 0).contiguous()
|
| 133 |
+
# Wh*Ww, Wh*Ww, 2 — shift to start from 0
|
| 134 |
+
relative_coords[:, :, 0] += window_size[0] - 1
|
| 135 |
+
relative_coords[:, :, 1] += window_size[1] - 1
|
| 136 |
+
relative_coords[:, :, 0] *= 2 * window_size[1] - 1
|
| 137 |
+
|
| 138 |
+
relative_position_index = torch.zeros(size=(window_area + 1,) * 2, dtype=relative_coords.dtype)
|
| 139 |
+
relative_position_index[1:, 1:] = relative_coords.sum(-1)
|
| 140 |
+
relative_position_index[0, 0:] = num_relative_distance - 3 # cls to token
|
| 141 |
+
relative_position_index[0:, 0] = num_relative_distance - 2 # token to cls
|
| 142 |
+
relative_position_index[0, 0] = num_relative_distance - 1 # cls to cls
|
| 143 |
+
return relative_position_index
|
| 144 |
+
|
| 145 |
+
def forward(self, window_size, interpolate_pos_encoding: bool = False, dim_size=None) -> torch.Tensor:
|
| 146 |
+
"""
|
| 147 |
+
Modification of timm.models.beit.py: Attention._get_rel_pos_bias to support arbitrary window sizes.
|
| 148 |
+
"""
|
| 149 |
+
old_height = 2 * self.window_size[0] - 1
|
| 150 |
+
old_width = 2 * self.window_size[1] - 1
|
| 151 |
+
|
| 152 |
+
new_height = 2 * window_size[0] - 1
|
| 153 |
+
new_width = 2 * window_size[1] - 1
|
| 154 |
+
|
| 155 |
+
old_relative_position_bias_table = self.relative_position_bias_table
|
| 156 |
+
|
| 157 |
+
old_num_relative_distance = self.num_relative_distance
|
| 158 |
+
new_num_relative_distance = new_height * new_width + 3
|
| 159 |
+
|
| 160 |
+
old_sub_table = old_relative_position_bias_table[: old_num_relative_distance - 3]
|
| 161 |
+
|
| 162 |
+
old_sub_table = old_sub_table.reshape(1, old_width, old_height, -1).permute(0, 3, 1, 2)
|
| 163 |
+
new_sub_table = nn.functional.interpolate(
|
| 164 |
+
old_sub_table, size=(torch_int(new_height), torch_int(new_width)), mode="bilinear"
|
| 165 |
+
)
|
| 166 |
+
new_sub_table = new_sub_table.permute(0, 2, 3, 1).reshape(new_num_relative_distance - 3, -1)
|
| 167 |
+
|
| 168 |
+
new_relative_position_bias_table = torch.cat(
|
| 169 |
+
[new_sub_table, old_relative_position_bias_table[old_num_relative_distance - 3 :]]
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
relative_position_index = self.generate_relative_position_index(window_size)
|
| 173 |
+
relative_position_bias = new_relative_position_bias_table[relative_position_index.view(-1)]
|
| 174 |
+
|
| 175 |
+
# patch_size*num_patches_height, patch_size*num_patches_width, num_attention_heads
|
| 176 |
+
relative_position_bias = relative_position_bias.view(
|
| 177 |
+
window_size[0] * window_size[1] + 1, window_size[0] * window_size[1] + 1, -1
|
| 178 |
+
)
|
| 179 |
+
# num_attention_heads, patch_size*num_patches_width, patch_size*num_patches_height
|
| 180 |
+
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()
|
| 181 |
+
|
| 182 |
+
if interpolate_pos_encoding:
|
| 183 |
+
relative_position_bias = nn.functional.interpolate(
|
| 184 |
+
relative_position_bias.unsqueeze(1),
|
| 185 |
+
size=(dim_size, dim_size),
|
| 186 |
+
mode="bilinear",
|
| 187 |
+
align_corners=False,
|
| 188 |
+
).squeeze(1)
|
| 189 |
+
|
| 190 |
+
return relative_position_bias.unsqueeze(0)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class BeitAttention(ViTAttention):
|
| 194 |
+
def __init__(self, config: BeitConfig):
|
| 195 |
+
super().__init__(config)
|
| 196 |
+
self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim)
|
| 197 |
+
self.k_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
|
| 198 |
+
self.v_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim)
|
| 199 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
class BeitMLP(ViTMLP):
|
| 203 |
+
pass
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
class BeitDropPath(SwinDropPath):
|
| 207 |
+
pass
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class BeitLayer(ViTLayer):
|
| 211 |
+
"""This corresponds to the Block class in the timm implementation."""
|
| 212 |
+
|
| 213 |
+
def __init__(self, config: BeitConfig, drop_path_rate: float = 0.0):
|
| 214 |
+
super().__init__()
|
| 215 |
+
self.patch_size = config.patch_size
|
| 216 |
+
self.drop_path = BeitDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
|
| 217 |
+
|
| 218 |
+
init_values = config.layer_scale_init_value
|
| 219 |
+
self.lambda_1 = (
|
| 220 |
+
nn.Parameter(init_values * torch.ones(config.hidden_size), requires_grad=True) if init_values > 0 else 1.0
|
| 221 |
+
)
|
| 222 |
+
self.lambda_2 = (
|
| 223 |
+
nn.Parameter(init_values * torch.ones(config.hidden_size), requires_grad=True) if init_values > 0 else 1.0
|
| 224 |
+
)
|
| 225 |
+
self.relative_position_bias = BeitRelativePositionBias(config) if config.use_relative_position_bias else None
|
| 226 |
+
|
| 227 |
+
def forward(
|
| 228 |
+
self,
|
| 229 |
+
hidden_states: torch.Tensor,
|
| 230 |
+
attention_mask: torch.Tensor | None = None,
|
| 231 |
+
interpolate_pos_encoding: bool = False,
|
| 232 |
+
resolution: tuple[int, int] | None = None,
|
| 233 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 234 |
+
) -> torch.Tensor:
|
| 235 |
+
if self.relative_position_bias is not None:
|
| 236 |
+
height, width = resolution
|
| 237 |
+
window_size = (height // self.patch_size, width // self.patch_size)
|
| 238 |
+
relative_position_bias = self.relative_position_bias(
|
| 239 |
+
window_size, interpolate_pos_encoding, dim_size=hidden_states.shape[1]
|
| 240 |
+
)
|
| 241 |
+
attention_mask = (
|
| 242 |
+
relative_position_bias + attention_mask if attention_mask is not None else relative_position_bias
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
# Self Attention
|
| 246 |
+
residual = hidden_states
|
| 247 |
+
hidden_states = self.layernorm_before(hidden_states)
|
| 248 |
+
hidden_states, _ = self.attention(
|
| 249 |
+
hidden_states,
|
| 250 |
+
attention_mask=attention_mask,
|
| 251 |
+
**kwargs,
|
| 252 |
+
)
|
| 253 |
+
hidden_states = self.dropout(hidden_states)
|
| 254 |
+
hidden_states = self.lambda_1 * hidden_states
|
| 255 |
+
hidden_states = self.drop_path(hidden_states) + residual
|
| 256 |
+
|
| 257 |
+
# Fully Connected
|
| 258 |
+
residual = hidden_states
|
| 259 |
+
hidden_states = self.layernorm_after(hidden_states)
|
| 260 |
+
hidden_states = self.mlp(hidden_states)
|
| 261 |
+
hidden_states = self.dropout(hidden_states)
|
| 262 |
+
hidden_states = self.lambda_2 * hidden_states
|
| 263 |
+
hidden_states = self.drop_path(hidden_states) + residual
|
| 264 |
+
|
| 265 |
+
return hidden_states
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
@auto_docstring
|
| 269 |
+
class BeitPreTrainedModel(ViTPreTrainedModel):
|
| 270 |
+
_no_split_modules = ["BeitLayer"]
|
| 271 |
+
_keys_to_ignore_on_load_unexpected = [r".*relative_position_index.*"]
|
| 272 |
+
_supports_flash_attn = False
|
| 273 |
+
_supports_flex_attn = False
|
| 274 |
+
|
| 275 |
+
def _init_weights(self, module):
|
| 276 |
+
"""Initialize the weights"""
|
| 277 |
+
PreTrainedModel._init_weights(self, module)
|
| 278 |
+
if isinstance(module, BeitEmbeddings):
|
| 279 |
+
init.zeros_(module.cls_token)
|
| 280 |
+
if module.mask_token is not None:
|
| 281 |
+
init.zeros_(module.mask_token)
|
| 282 |
+
if module.position_embeddings is not None:
|
| 283 |
+
init.zeros_(module.position_embeddings)
|
| 284 |
+
elif isinstance(module, BeitRelativePositionBias):
|
| 285 |
+
init.zeros_(module.relative_position_bias_table)
|
| 286 |
+
elif isinstance(module, BeitLayer):
|
| 287 |
+
if isinstance(module.lambda_1, nn.Parameter):
|
| 288 |
+
init.constant_(module.lambda_1, self.config.layer_scale_init_value)
|
| 289 |
+
init.constant_(module.lambda_2, self.config.layer_scale_init_value)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
@auto_docstring
|
| 293 |
+
class BeitModel(BeitPreTrainedModel):
|
| 294 |
+
def __init__(self, config: BeitConfig, add_pooling_layer: bool = True) -> None:
|
| 295 |
+
r"""
|
| 296 |
+
add_pooling_layer (bool, *optional*, defaults to `True`):
|
| 297 |
+
Whether to add a pooling layer
|
| 298 |
+
"""
|
| 299 |
+
super().__init__(config)
|
| 300 |
+
self.config = config
|
| 301 |
+
|
| 302 |
+
self.embeddings = BeitEmbeddings(config)
|
| 303 |
+
self.shared_position_bias = (
|
| 304 |
+
BeitRelativePositionBias(config) if config.use_shared_relative_position_bias else None
|
| 305 |
+
)
|
| 306 |
+
drop_path_rates = [
|
| 307 |
+
config.drop_path_rate * i / max(config.num_hidden_layers - 1, 1) for i in range(config.num_hidden_layers)
|
| 308 |
+
]
|
| 309 |
+
self.layers = nn.ModuleList([BeitLayer(config, drop_path_rate=r) for r in drop_path_rates])
|
| 310 |
+
|
| 311 |
+
self.layernorm = (
|
| 312 |
+
nn.Identity() if config.use_mean_pooling else nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 313 |
+
)
|
| 314 |
+
self.pooler = BeitPooler(config) if add_pooling_layer else None
|
| 315 |
+
|
| 316 |
+
# Initialize weights and apply final processing
|
| 317 |
+
self.post_init()
|
| 318 |
+
|
| 319 |
+
@merge_with_config_defaults
|
| 320 |
+
@capture_outputs(tie_last_hidden_states=False)
|
| 321 |
+
@auto_docstring
|
| 322 |
+
def forward(
|
| 323 |
+
self,
|
| 324 |
+
pixel_values: torch.Tensor,
|
| 325 |
+
bool_masked_pos: torch.BoolTensor | None = None,
|
| 326 |
+
interpolate_pos_encoding: bool = False,
|
| 327 |
+
attention_mask: torch.Tensor | None = None,
|
| 328 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 329 |
+
) -> BeitModelOutputWithPooling:
|
| 330 |
+
r"""
|
| 331 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
|
| 332 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
|
| 333 |
+
"""
|
| 334 |
+
embedding_output = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
|
| 335 |
+
resolution = pixel_values.shape[2:]
|
| 336 |
+
|
| 337 |
+
attention_mask = create_bidirectional_mask(
|
| 338 |
+
config=self.config,
|
| 339 |
+
inputs_embeds=embedding_output,
|
| 340 |
+
attention_mask=attention_mask,
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
if self.shared_position_bias is not None:
|
| 344 |
+
height, width = resolution
|
| 345 |
+
window_size = (height // self.config.patch_size, width // self.config.patch_size)
|
| 346 |
+
shared_relative_position_bias = self.shared_position_bias(
|
| 347 |
+
window_size, interpolate_pos_encoding=interpolate_pos_encoding, dim_size=embedding_output.shape[1]
|
| 348 |
+
)
|
| 349 |
+
attention_mask = (
|
| 350 |
+
shared_relative_position_bias + attention_mask
|
| 351 |
+
if attention_mask is not None
|
| 352 |
+
else shared_relative_position_bias
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
hidden_states = embedding_output
|
| 356 |
+
for layer in self.layers:
|
| 357 |
+
hidden_states = layer(
|
| 358 |
+
hidden_states,
|
| 359 |
+
attention_mask=attention_mask,
|
| 360 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 361 |
+
resolution=resolution,
|
| 362 |
+
**kwargs,
|
| 363 |
+
)
|
| 364 |
+
sequence_output = self.layernorm(hidden_states)
|
| 365 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 366 |
+
|
| 367 |
+
return BeitModelOutputWithPooling(last_hidden_state=sequence_output, pooler_output=pooled_output)
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
class BeitPooler(nn.Module):
|
| 371 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 372 |
+
super().__init__()
|
| 373 |
+
self.layernorm = (
|
| 374 |
+
nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) if config.use_mean_pooling else None
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 378 |
+
# Mean pool patch tokens with layernorm, or take the [CLS] token
|
| 379 |
+
return self.layernorm(hidden_states[:, 1:, :].mean(1)) if self.layernorm is not None else hidden_states[:, 0]
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
@auto_docstring(
|
| 383 |
+
custom_intro="""
|
| 384 |
+
Beit Model transformer with a 'language' modeling head on top. BEiT does masked image modeling by predicting
|
| 385 |
+
visual tokens of a Vector-Quantize Variational Autoencoder (VQ-VAE), whereas other vision models like ViT and DeiT
|
| 386 |
+
predict RGB pixel values. As a result, this class is incompatible with [`AutoModelForMaskedImageModeling`], so you
|
| 387 |
+
will need to use [`BeitForMaskedImageModeling`] directly if you wish to do masked image modeling with BEiT.
|
| 388 |
+
"""
|
| 389 |
+
)
|
| 390 |
+
class BeitForMaskedImageModeling(BeitPreTrainedModel):
|
| 391 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 392 |
+
super().__init__(config)
|
| 393 |
+
|
| 394 |
+
self.num_labels = config.num_labels
|
| 395 |
+
self.beit = BeitModel(config, add_pooling_layer=False)
|
| 396 |
+
|
| 397 |
+
# Classifier head
|
| 398 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 399 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size)
|
| 400 |
+
|
| 401 |
+
# Initialize weights and apply final processing
|
| 402 |
+
self.post_init()
|
| 403 |
+
|
| 404 |
+
def get_output_embeddings(self):
|
| 405 |
+
return None
|
| 406 |
+
|
| 407 |
+
@can_return_tuple
|
| 408 |
+
@auto_docstring
|
| 409 |
+
def forward(
|
| 410 |
+
self,
|
| 411 |
+
pixel_values: torch.Tensor | None = None,
|
| 412 |
+
bool_masked_pos: torch.BoolTensor | None = None,
|
| 413 |
+
labels: torch.Tensor | None = None,
|
| 414 |
+
interpolate_pos_encoding: bool = False,
|
| 415 |
+
attention_mask: torch.Tensor | None = None,
|
| 416 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 417 |
+
) -> tuple | MaskedLMOutput:
|
| 418 |
+
r"""
|
| 419 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
|
| 420 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
|
| 421 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 422 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 423 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 424 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 425 |
+
|
| 426 |
+
Examples:
|
| 427 |
+
|
| 428 |
+
```python
|
| 429 |
+
>>> from transformers import AutoImageProcessor, BeitForMaskedImageModeling
|
| 430 |
+
>>> import torch
|
| 431 |
+
>>> from PIL import Image
|
| 432 |
+
>>> import requests
|
| 433 |
+
|
| 434 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 435 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 436 |
+
|
| 437 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-patch16-224-pt22k")
|
| 438 |
+
>>> model = BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k")
|
| 439 |
+
|
| 440 |
+
>>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
|
| 441 |
+
>>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
|
| 442 |
+
>>> # create random boolean mask of shape (batch_size, num_patches)
|
| 443 |
+
>>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
|
| 444 |
+
|
| 445 |
+
>>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
|
| 446 |
+
>>> loss, logits = outputs.loss, outputs.logits
|
| 447 |
+
>>> list(logits.shape)
|
| 448 |
+
[1, 196, 8192]
|
| 449 |
+
```"""
|
| 450 |
+
|
| 451 |
+
outputs = self.beit(
|
| 452 |
+
pixel_values,
|
| 453 |
+
bool_masked_pos=bool_masked_pos,
|
| 454 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 455 |
+
attention_mask=attention_mask,
|
| 456 |
+
**kwargs,
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
sequence_output = outputs.last_hidden_state
|
| 460 |
+
sequence_output = self.layernorm(sequence_output)
|
| 461 |
+
prediction_scores = self.lm_head(sequence_output[:, 1:])
|
| 462 |
+
|
| 463 |
+
masked_lm_loss = None
|
| 464 |
+
if labels is not None:
|
| 465 |
+
loss_fct = nn.CrossEntropyLoss() # -100 index = padding token
|
| 466 |
+
masked_lm_loss = loss_fct(prediction_scores[bool_masked_pos], labels)
|
| 467 |
+
|
| 468 |
+
return MaskedLMOutput(
|
| 469 |
+
loss=masked_lm_loss,
|
| 470 |
+
logits=prediction_scores,
|
| 471 |
+
hidden_states=outputs.hidden_states,
|
| 472 |
+
attentions=outputs.attentions,
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
@auto_docstring(
|
| 477 |
+
custom_intro="""
|
| 478 |
+
Beit Model transformer with an image classification head on top (a linear layer on top of the average of the final
|
| 479 |
+
hidden states of the patch tokens) e.g. for ImageNet.
|
| 480 |
+
"""
|
| 481 |
+
)
|
| 482 |
+
class BeitForImageClassification(BeitPreTrainedModel):
|
| 483 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 484 |
+
super().__init__(config)
|
| 485 |
+
|
| 486 |
+
self.num_labels = config.num_labels
|
| 487 |
+
self.beit = BeitModel(config, add_pooling_layer=True)
|
| 488 |
+
|
| 489 |
+
# Classifier head
|
| 490 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 491 |
+
|
| 492 |
+
# Initialize weights and apply final processing
|
| 493 |
+
self.post_init()
|
| 494 |
+
|
| 495 |
+
@can_return_tuple
|
| 496 |
+
@auto_docstring
|
| 497 |
+
def forward(
|
| 498 |
+
self,
|
| 499 |
+
pixel_values: torch.Tensor | None = None,
|
| 500 |
+
labels: torch.Tensor | None = None,
|
| 501 |
+
interpolate_pos_encoding: bool = False,
|
| 502 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 503 |
+
) -> tuple | ImageClassifierOutput:
|
| 504 |
+
r"""
|
| 505 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 506 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 507 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 508 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 509 |
+
"""
|
| 510 |
+
outputs = self.beit(
|
| 511 |
+
pixel_values,
|
| 512 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 513 |
+
**kwargs,
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
pooled_output = outputs.pooler_output
|
| 517 |
+
|
| 518 |
+
logits = self.classifier(pooled_output)
|
| 519 |
+
|
| 520 |
+
loss = None
|
| 521 |
+
if labels is not None:
|
| 522 |
+
loss = self.loss_function(labels, logits, self.config)
|
| 523 |
+
|
| 524 |
+
return ImageClassifierOutput(
|
| 525 |
+
loss=loss,
|
| 526 |
+
logits=logits,
|
| 527 |
+
hidden_states=outputs.hidden_states,
|
| 528 |
+
attentions=outputs.attentions,
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
class BeitConvLayer(ResNetConvLayer):
|
| 533 |
+
def __init__(
|
| 534 |
+
self,
|
| 535 |
+
in_channels: int,
|
| 536 |
+
out_channels: int,
|
| 537 |
+
kernel_size: int | tuple[int, int] = 3,
|
| 538 |
+
stride: int = 1,
|
| 539 |
+
padding: int | tuple[int, int] | str = 0,
|
| 540 |
+
bias: bool = False,
|
| 541 |
+
dilation: int | tuple[int, int] = 1,
|
| 542 |
+
groups: int = 1,
|
| 543 |
+
activation: str = "relu",
|
| 544 |
+
):
|
| 545 |
+
super().__init__()
|
| 546 |
+
self.convolution = nn.Conv2d(
|
| 547 |
+
in_channels=in_channels,
|
| 548 |
+
out_channels=out_channels,
|
| 549 |
+
kernel_size=kernel_size,
|
| 550 |
+
stride=stride,
|
| 551 |
+
padding=padding,
|
| 552 |
+
dilation=dilation,
|
| 553 |
+
groups=groups,
|
| 554 |
+
bias=bias,
|
| 555 |
+
)
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
class BeitPyramidPoolingBlock(nn.Module):
|
| 559 |
+
def __init__(self, pool_scale: int, in_channels: int, channels: int) -> None:
|
| 560 |
+
super().__init__()
|
| 561 |
+
self.pooling = nn.AdaptiveAvgPool2d(pool_scale)
|
| 562 |
+
self.conv = BeitConvLayer(in_channels, channels, kernel_size=1)
|
| 563 |
+
|
| 564 |
+
def forward(self, input: torch.Tensor, size: tuple[int, int]) -> torch.Tensor:
|
| 565 |
+
hidden_state = self.pooling(input)
|
| 566 |
+
hidden_state = self.conv(hidden_state)
|
| 567 |
+
hidden_state = nn.functional.interpolate(hidden_state, size=size, mode="bilinear", align_corners=False)
|
| 568 |
+
return hidden_state
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
class BeitPyramidPoolingModule(nn.Module):
|
| 572 |
+
"""
|
| 573 |
+
Pyramid Pooling Module (PPM) used in PSPNet.
|
| 574 |
+
|
| 575 |
+
Args:
|
| 576 |
+
pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
|
| 577 |
+
Module.
|
| 578 |
+
in_channels (int): Input channels.
|
| 579 |
+
channels (int): Channels after modules, before conv_seg.
|
| 580 |
+
|
| 581 |
+
Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
|
| 582 |
+
"""
|
| 583 |
+
|
| 584 |
+
def __init__(self, pool_scales: tuple[int, ...], in_channels: int, channels: int) -> None:
|
| 585 |
+
super().__init__()
|
| 586 |
+
self.pool_scales = pool_scales
|
| 587 |
+
self.in_channels = in_channels
|
| 588 |
+
self.channels = channels
|
| 589 |
+
self.blocks = nn.ModuleList(
|
| 590 |
+
[
|
| 591 |
+
BeitPyramidPoolingBlock(pool_scale=pool_scale, in_channels=in_channels, channels=channels)
|
| 592 |
+
for pool_scale in pool_scales
|
| 593 |
+
]
|
| 594 |
+
)
|
| 595 |
+
|
| 596 |
+
def forward(self, hidden_states: torch.Tensor) -> list[torch.Tensor]:
|
| 597 |
+
original_size = hidden_states.size()[2:]
|
| 598 |
+
return [block(hidden_states, size=original_size) for block in self.blocks]
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
class BeitUperHead(nn.Module):
|
| 602 |
+
"""
|
| 603 |
+
Unified Perceptual Parsing for Scene Understanding. This head is the implementation of
|
| 604 |
+
[UPerNet](https://huggingface.co/papers/1807.10221).
|
| 605 |
+
|
| 606 |
+
Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
|
| 607 |
+
"""
|
| 608 |
+
|
| 609 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 610 |
+
super().__init__()
|
| 611 |
+
|
| 612 |
+
self.pool_scales = config.pool_scales # e.g. (1, 2, 3, 6)
|
| 613 |
+
self.in_channels = [config.hidden_size] * 4 # e.g. [768, 768, 768, 768]
|
| 614 |
+
self.channels = config.hidden_size
|
| 615 |
+
self.classifier = nn.Conv2d(self.channels, config.num_labels, kernel_size=1)
|
| 616 |
+
|
| 617 |
+
# PSP Module
|
| 618 |
+
self.psp_modules = BeitPyramidPoolingModule(
|
| 619 |
+
self.pool_scales,
|
| 620 |
+
self.in_channels[-1],
|
| 621 |
+
self.channels,
|
| 622 |
+
)
|
| 623 |
+
self.psp_bottleneck = BeitConvLayer(
|
| 624 |
+
self.in_channels[-1] + len(self.pool_scales) * self.channels,
|
| 625 |
+
self.channels,
|
| 626 |
+
kernel_size=3,
|
| 627 |
+
padding=1,
|
| 628 |
+
)
|
| 629 |
+
# FPN Module
|
| 630 |
+
self.lateral_convs = nn.ModuleList()
|
| 631 |
+
self.fpn_convs = nn.ModuleList()
|
| 632 |
+
for in_channels in self.in_channels[:-1]: # skip the top layer
|
| 633 |
+
self.lateral_convs.append(BeitConvLayer(in_channels, self.channels, kernel_size=1))
|
| 634 |
+
self.fpn_convs.append(BeitConvLayer(self.channels, self.channels, kernel_size=3, padding=1))
|
| 635 |
+
|
| 636 |
+
self.fpn_bottleneck = BeitConvLayer(
|
| 637 |
+
len(self.in_channels) * self.channels,
|
| 638 |
+
self.channels,
|
| 639 |
+
kernel_size=3,
|
| 640 |
+
padding=1,
|
| 641 |
+
)
|
| 642 |
+
|
| 643 |
+
def psp_forward(self, hidden_states: list[torch.Tensor]) -> torch.Tensor:
|
| 644 |
+
hidden_state = hidden_states[-1]
|
| 645 |
+
hidden_state = torch.cat([hidden_state, *self.psp_modules(hidden_state)], dim=1)
|
| 646 |
+
return self.psp_bottleneck(hidden_state)
|
| 647 |
+
|
| 648 |
+
def forward(self, encoder_hidden_states: list[torch.Tensor]) -> torch.Tensor:
|
| 649 |
+
# build laterals
|
| 650 |
+
laterals = []
|
| 651 |
+
for lateral_conv, hidden_state in zip(self.lateral_convs, encoder_hidden_states):
|
| 652 |
+
laterals.append(lateral_conv(hidden_state))
|
| 653 |
+
|
| 654 |
+
laterals.append(self.psp_forward(encoder_hidden_states))
|
| 655 |
+
|
| 656 |
+
# build top-down path
|
| 657 |
+
used_backbone_levels = len(laterals)
|
| 658 |
+
for i in range(used_backbone_levels - 1, 0, -1):
|
| 659 |
+
prev_shape = laterals[i - 1].shape[2:]
|
| 660 |
+
laterals[i - 1] = laterals[i - 1] + nn.functional.interpolate(
|
| 661 |
+
laterals[i], size=prev_shape, mode="bilinear", align_corners=False
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
# build outputs
|
| 665 |
+
fpn_outs = []
|
| 666 |
+
for i in range(used_backbone_levels - 1):
|
| 667 |
+
fpn_outs.append(self.fpn_convs[i](laterals[i]))
|
| 668 |
+
# append psp feature
|
| 669 |
+
fpn_outs.append(laterals[-1])
|
| 670 |
+
|
| 671 |
+
for i in range(used_backbone_levels - 1, 0, -1):
|
| 672 |
+
fpn_outs[i] = nn.functional.interpolate(
|
| 673 |
+
fpn_outs[i], size=fpn_outs[0].shape[2:], mode="bilinear", align_corners=False
|
| 674 |
+
)
|
| 675 |
+
fpn_outs = torch.cat(fpn_outs, dim=1)
|
| 676 |
+
output = self.fpn_bottleneck(fpn_outs)
|
| 677 |
+
output = self.classifier(output)
|
| 678 |
+
|
| 679 |
+
return output
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
class BeitFCNHead(nn.Module):
|
| 683 |
+
"""
|
| 684 |
+
Fully Convolution Networks for Semantic Segmentation. This head is implemented of
|
| 685 |
+
[FCNNet](https://huggingface.co/papers/1411.4038>).
|
| 686 |
+
|
| 687 |
+
Args:
|
| 688 |
+
config (BeitConfig): Configuration.
|
| 689 |
+
in_channels
|
| 690 |
+
kernel_size (int): The kernel size for convs in the head. Default: 3.
|
| 691 |
+
dilation (int): The dilation rate for convs in the head. Default: 1.
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
|
| 695 |
+
"""
|
| 696 |
+
|
| 697 |
+
def __init__(
|
| 698 |
+
self, config: BeitConfig, in_index: int = 2, kernel_size: int = 3, dilation: int | tuple[int, int] = 1
|
| 699 |
+
) -> None:
|
| 700 |
+
super().__init__()
|
| 701 |
+
self.in_channels = config.hidden_size
|
| 702 |
+
self.channels = config.auxiliary_channels
|
| 703 |
+
self.num_convs = config.auxiliary_num_convs
|
| 704 |
+
self.concat_input = config.auxiliary_concat_input
|
| 705 |
+
self.in_index = in_index
|
| 706 |
+
|
| 707 |
+
conv_padding = (kernel_size // 2) * dilation
|
| 708 |
+
self.convs = nn.ModuleList()
|
| 709 |
+
if self.num_convs > 0:
|
| 710 |
+
self.convs.append(
|
| 711 |
+
BeitConvLayer(
|
| 712 |
+
self.in_channels, self.channels, kernel_size=kernel_size, padding=conv_padding, dilation=dilation
|
| 713 |
+
)
|
| 714 |
+
)
|
| 715 |
+
for _ in range(self.num_convs - 1):
|
| 716 |
+
self.convs.append(
|
| 717 |
+
BeitConvLayer(
|
| 718 |
+
self.channels,
|
| 719 |
+
self.channels,
|
| 720 |
+
kernel_size=kernel_size,
|
| 721 |
+
padding=conv_padding,
|
| 722 |
+
dilation=dilation,
|
| 723 |
+
)
|
| 724 |
+
)
|
| 725 |
+
if self.concat_input:
|
| 726 |
+
self.conv_cat = BeitConvLayer(
|
| 727 |
+
self.in_channels + self.channels, self.channels, kernel_size=kernel_size, padding=kernel_size // 2
|
| 728 |
+
)
|
| 729 |
+
|
| 730 |
+
self.classifier = nn.Conv2d(self.channels, config.num_labels, kernel_size=1)
|
| 731 |
+
|
| 732 |
+
def forward(self, encoder_hidden_states: list[torch.Tensor]) -> torch.Tensor:
|
| 733 |
+
residual = encoder_hidden_states[self.in_index]
|
| 734 |
+
hidden_states = residual
|
| 735 |
+
for conv in self.convs:
|
| 736 |
+
hidden_states = conv(hidden_states)
|
| 737 |
+
if self.concat_input:
|
| 738 |
+
hidden_states = self.conv_cat(torch.cat([residual, hidden_states], dim=1))
|
| 739 |
+
hidden_states = self.classifier(hidden_states)
|
| 740 |
+
return hidden_states
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
class BeitFPNUpBlock(nn.Module):
|
| 744 |
+
"""4x upsampling block: ConvTranspose → BN → GELU → ConvTranspose."""
|
| 745 |
+
|
| 746 |
+
def __init__(self, hidden_size: int, kernel_size: int = 2, stride: int = 2) -> None:
|
| 747 |
+
super().__init__()
|
| 748 |
+
self.conv_transpose1 = nn.ConvTranspose2d(hidden_size, hidden_size, kernel_size=kernel_size, stride=stride)
|
| 749 |
+
self.normalization = nn.BatchNorm2d(hidden_size)
|
| 750 |
+
self.activation = nn.GELU()
|
| 751 |
+
self.conv_transpose2 = nn.ConvTranspose2d(hidden_size, hidden_size, kernel_size=kernel_size, stride=stride)
|
| 752 |
+
|
| 753 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 754 |
+
hidden_states = self.conv_transpose1(hidden_states)
|
| 755 |
+
hidden_states = self.normalization(hidden_states)
|
| 756 |
+
hidden_states = self.activation(hidden_states)
|
| 757 |
+
hidden_states = self.conv_transpose2(hidden_states)
|
| 758 |
+
return hidden_states
|
| 759 |
+
|
| 760 |
+
|
| 761 |
+
class BeitFPNNeck(nn.Module):
|
| 762 |
+
"""
|
| 763 |
+
4-level feature pyramid neck for BeiT. Produces x4 upsample, x2 upsample,
|
| 764 |
+
identity, and x2 downsample outputs from the four selected ViT feature maps.
|
| 765 |
+
"""
|
| 766 |
+
|
| 767 |
+
def __init__(self, config: BeitConfig):
|
| 768 |
+
super().__init__()
|
| 769 |
+
self.fpn1 = BeitFPNUpBlock(config.hidden_size)
|
| 770 |
+
self.fpn2 = nn.ConvTranspose2d(config.hidden_size, config.hidden_size, kernel_size=2, stride=2)
|
| 771 |
+
self.fpn4 = nn.MaxPool2d(kernel_size=2, stride=2)
|
| 772 |
+
|
| 773 |
+
def forward(self, feature_maps: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
|
| 774 |
+
return (
|
| 775 |
+
self.fpn1(feature_maps[0]),
|
| 776 |
+
self.fpn2(feature_maps[1]),
|
| 777 |
+
feature_maps[2], # identity: native patch-grid resolution
|
| 778 |
+
self.fpn4(feature_maps[3]),
|
| 779 |
+
)
|
| 780 |
+
|
| 781 |
+
|
| 782 |
+
@auto_docstring
|
| 783 |
+
class BeitForSemanticSegmentation(BeitPreTrainedModel):
|
| 784 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 785 |
+
super().__init__(config)
|
| 786 |
+
|
| 787 |
+
self.num_labels = config.num_labels
|
| 788 |
+
self.beit = BeitModel(config, add_pooling_layer=False)
|
| 789 |
+
|
| 790 |
+
if len(self.config.out_indices) != 4:
|
| 791 |
+
raise ValueError(
|
| 792 |
+
"BeitForSemanticSegmentation requires config.out_indices to be a list of 4 integers, "
|
| 793 |
+
"specifying which features to use from the backbone. One can use [3, 5, 7, 11] in case of "
|
| 794 |
+
"a base-sized architecture."
|
| 795 |
+
)
|
| 796 |
+
self.fpn = BeitFPNNeck(config)
|
| 797 |
+
|
| 798 |
+
# Semantic segmentation head(s)
|
| 799 |
+
self.decode_head = BeitUperHead(config)
|
| 800 |
+
self.auxiliary_head = BeitFCNHead(config) if config.use_auxiliary_head else None
|
| 801 |
+
|
| 802 |
+
# Initialize weights and apply final processing
|
| 803 |
+
self.post_init()
|
| 804 |
+
|
| 805 |
+
@can_return_tuple
|
| 806 |
+
@filter_output_hidden_states
|
| 807 |
+
@auto_docstring
|
| 808 |
+
def forward(
|
| 809 |
+
self,
|
| 810 |
+
pixel_values: torch.Tensor | None = None,
|
| 811 |
+
labels: torch.Tensor | None = None,
|
| 812 |
+
interpolate_pos_encoding: bool = False,
|
| 813 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 814 |
+
) -> tuple | SemanticSegmenterOutput:
|
| 815 |
+
r"""
|
| 816 |
+
labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
|
| 817 |
+
Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ...,
|
| 818 |
+
config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy).
|
| 819 |
+
|
| 820 |
+
Examples:
|
| 821 |
+
|
| 822 |
+
```python
|
| 823 |
+
>>> from transformers import AutoImageProcessor, BeitForSemanticSegmentation
|
| 824 |
+
>>> from PIL import Image
|
| 825 |
+
>>> import requests
|
| 826 |
+
|
| 827 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 828 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 829 |
+
|
| 830 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-finetuned-ade-640-640")
|
| 831 |
+
>>> model = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640")
|
| 832 |
+
|
| 833 |
+
>>> inputs = image_processor(images=image, return_tensors="pt")
|
| 834 |
+
>>> outputs = model(**inputs)
|
| 835 |
+
>>> # logits are of shape (batch_size, num_labels, height, width)
|
| 836 |
+
>>> logits = outputs.logits
|
| 837 |
+
```"""
|
| 838 |
+
if labels is not None and self.config.num_labels == 1:
|
| 839 |
+
raise ValueError("The number of labels should be greater than one")
|
| 840 |
+
kwargs["output_hidden_states"] = True
|
| 841 |
+
outputs = self.beit(
|
| 842 |
+
pixel_values,
|
| 843 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 844 |
+
**kwargs,
|
| 845 |
+
)
|
| 846 |
+
|
| 847 |
+
encoder_hidden_states = outputs.hidden_states
|
| 848 |
+
batch_size, _, height, width = pixel_values.shape
|
| 849 |
+
patch_height = height // self.config.patch_size
|
| 850 |
+
patch_width = width // self.config.patch_size
|
| 851 |
+
|
| 852 |
+
# out_indices are 1-based into encoder_hidden_states (index 0 is the initial patch embedding).
|
| 853 |
+
# Remove the CLS token ([:, 1:]) and reshape from sequence to 2D spatial feature maps.
|
| 854 |
+
feature_maps = tuple(
|
| 855 |
+
encoder_hidden_states[i - 1][:, 1:].transpose(1, 2).reshape(batch_size, -1, patch_height, patch_width)
|
| 856 |
+
for i in self.config.out_indices
|
| 857 |
+
)
|
| 858 |
+
feature_maps = self.fpn(feature_maps)
|
| 859 |
+
|
| 860 |
+
logits = self.decode_head(feature_maps)
|
| 861 |
+
|
| 862 |
+
auxiliary_logits = None
|
| 863 |
+
if self.auxiliary_head is not None:
|
| 864 |
+
auxiliary_logits = self.auxiliary_head(feature_maps)
|
| 865 |
+
|
| 866 |
+
loss = None
|
| 867 |
+
if labels is not None:
|
| 868 |
+
loss = self.loss_function(
|
| 869 |
+
logits,
|
| 870 |
+
labels,
|
| 871 |
+
ignore_index=self.config.semantic_loss_ignore_index,
|
| 872 |
+
auxiliary_logits=auxiliary_logits,
|
| 873 |
+
auxiliary_loss_weight=self.config.auxiliary_loss_weight,
|
| 874 |
+
)
|
| 875 |
+
return SemanticSegmenterOutput(
|
| 876 |
+
loss=loss,
|
| 877 |
+
logits=logits,
|
| 878 |
+
hidden_states=outputs.hidden_states,
|
| 879 |
+
attentions=outputs.attentions,
|
| 880 |
+
)
|
| 881 |
+
|
| 882 |
+
|
| 883 |
+
@auto_docstring(
|
| 884 |
+
custom_intro="""
|
| 885 |
+
BEiT backbone, to be used with frameworks like DETR and MaskFormer.
|
| 886 |
+
"""
|
| 887 |
+
)
|
| 888 |
+
class BeitBackbone(BackboneMixin, BeitPreTrainedModel):
|
| 889 |
+
def __init__(self, config):
|
| 890 |
+
super().__init__(config)
|
| 891 |
+
|
| 892 |
+
self.num_features = [config.hidden_size for _ in range(config.num_hidden_layers + 1)]
|
| 893 |
+
self.beit = BeitModel(config, add_pooling_layer=False)
|
| 894 |
+
self.fpn = BeitFPNNeck(config) if config.add_fpn else nn.Identity()
|
| 895 |
+
|
| 896 |
+
# initialize weights and apply final processing
|
| 897 |
+
self.post_init()
|
| 898 |
+
|
| 899 |
+
@can_return_tuple
|
| 900 |
+
@filter_output_hidden_states
|
| 901 |
+
@auto_docstring
|
| 902 |
+
def forward(
|
| 903 |
+
self,
|
| 904 |
+
pixel_values: Tensor,
|
| 905 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 906 |
+
) -> BackboneOutput:
|
| 907 |
+
r"""
|
| 908 |
+
Examples:
|
| 909 |
+
|
| 910 |
+
```python
|
| 911 |
+
>>> from transformers import AutoImageProcessor, AutoBackbone
|
| 912 |
+
>>> import torch
|
| 913 |
+
>>> from PIL import Image
|
| 914 |
+
>>> import requests
|
| 915 |
+
|
| 916 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 917 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 918 |
+
|
| 919 |
+
>>> processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-patch16-224")
|
| 920 |
+
>>> model = AutoBackbone.from_pretrained(
|
| 921 |
+
... "microsoft/beit-base-patch16-224", out_features=["stage1", "stage2", "stage3", "stage4"]
|
| 922 |
+
... )
|
| 923 |
+
|
| 924 |
+
>>> inputs = processor(image, return_tensors="pt")
|
| 925 |
+
|
| 926 |
+
>>> outputs = model(**inputs)
|
| 927 |
+
>>> feature_maps = outputs.feature_maps
|
| 928 |
+
>>> list(feature_maps[-1].shape)
|
| 929 |
+
[1, 768, 14, 14]
|
| 930 |
+
```"""
|
| 931 |
+
batch_size, _, height, width = pixel_values.shape
|
| 932 |
+
patch_height = height // self.config.patch_size
|
| 933 |
+
patch_width = width // self.config.patch_size
|
| 934 |
+
kwargs["output_hidden_states"] = True # required to extract per-stage feature maps from hidden_states
|
| 935 |
+
outputs = self.beit(pixel_values, **kwargs)
|
| 936 |
+
|
| 937 |
+
hidden_states = outputs.hidden_states
|
| 938 |
+
feature_maps = ()
|
| 939 |
+
for stage, hidden_state in zip(self.stage_names, hidden_states):
|
| 940 |
+
if stage in self.out_features:
|
| 941 |
+
if self.config.reshape_hidden_states:
|
| 942 |
+
hidden_state = hidden_state[:, 1:, :]
|
| 943 |
+
hidden_state = hidden_state.transpose(1, 2)
|
| 944 |
+
hidden_state = hidden_state.reshape(batch_size, -1, patch_height, patch_width)
|
| 945 |
+
|
| 946 |
+
feature_maps += (hidden_state,)
|
| 947 |
+
|
| 948 |
+
feature_maps = self.fpn(feature_maps)
|
| 949 |
+
|
| 950 |
+
return BackboneOutput(
|
| 951 |
+
feature_maps=feature_maps,
|
| 952 |
+
hidden_states=outputs.hidden_states,
|
| 953 |
+
attentions=outputs.attentions,
|
| 954 |
+
)
|
| 955 |
+
|
| 956 |
+
|
| 957 |
+
__all__ = [
|
| 958 |
+
"BeitForImageClassification",
|
| 959 |
+
"BeitForMaskedImageModeling",
|
| 960 |
+
"BeitForSemanticSegmentation",
|
| 961 |
+
"BeitModel",
|
| 962 |
+
"BeitPreTrainedModel",
|
| 963 |
+
"BeitBackbone",
|
| 964 |
+
]
|
lib/python3.11/site-packages/transformers/models/bert/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_bert import *
|
| 22 |
+
from .modeling_bert import *
|
| 23 |
+
from .tokenization_bert import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.11/site-packages/transformers/models/bert/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (811 Bytes). View file
|
|
|
lib/python3.11/site-packages/transformers/models/bert/__pycache__/configuration_bert.cpython-311.pyc
ADDED
|
Binary file (2.64 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/bert/__pycache__/modeling_bert.cpython-311.pyc
ADDED
|
Binary file (68.8 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/bert/__pycache__/tokenization_bert.cpython-311.pyc
ADDED
|
Binary file (6.96 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/bert/__pycache__/tokenization_bert_legacy.cpython-311.pyc
ADDED
|
Binary file (23.3 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/bert/configuration_bert.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 2 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. 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 |
+
"""BERT model configuration"""
|
| 16 |
+
|
| 17 |
+
from huggingface_hub.dataclasses import strict
|
| 18 |
+
|
| 19 |
+
from ...configuration_utils import PreTrainedConfig
|
| 20 |
+
from ...utils import auto_docstring
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@auto_docstring(checkpoint="google-bert/bert-base-uncased")
|
| 24 |
+
@strict
|
| 25 |
+
class BertConfig(PreTrainedConfig):
|
| 26 |
+
r"""
|
| 27 |
+
Examples:
|
| 28 |
+
|
| 29 |
+
```python
|
| 30 |
+
>>> from transformers import BertConfig, BertModel
|
| 31 |
+
|
| 32 |
+
>>> # Initializing a BERT google-bert/bert-base-uncased style configuration
|
| 33 |
+
>>> configuration = BertConfig()
|
| 34 |
+
|
| 35 |
+
>>> # Initializing a model (with random weights) from the google-bert/bert-base-uncased style configuration
|
| 36 |
+
>>> model = BertModel(configuration)
|
| 37 |
+
|
| 38 |
+
>>> # Accessing the model configuration
|
| 39 |
+
>>> configuration = model.config
|
| 40 |
+
```"""
|
| 41 |
+
|
| 42 |
+
model_type = "bert"
|
| 43 |
+
|
| 44 |
+
vocab_size: int = 30522
|
| 45 |
+
hidden_size: int = 768
|
| 46 |
+
num_hidden_layers: int = 12
|
| 47 |
+
num_attention_heads: int = 12
|
| 48 |
+
intermediate_size: int = 3072
|
| 49 |
+
hidden_act: str = "gelu"
|
| 50 |
+
hidden_dropout_prob: float | int = 0.1
|
| 51 |
+
attention_probs_dropout_prob: float | int = 0.1
|
| 52 |
+
max_position_embeddings: int = 512
|
| 53 |
+
type_vocab_size: int = 2
|
| 54 |
+
initializer_range: float = 0.02
|
| 55 |
+
layer_norm_eps: float = 1e-12
|
| 56 |
+
pad_token_id: int | None = 0
|
| 57 |
+
use_cache: bool = True
|
| 58 |
+
classifier_dropout: float | int | None = None
|
| 59 |
+
is_decoder: bool = False
|
| 60 |
+
add_cross_attention: bool = False
|
| 61 |
+
bos_token_id: int | None = None
|
| 62 |
+
eos_token_id: int | list[int] | None = None
|
| 63 |
+
tie_word_embeddings: bool = True
|
| 64 |
+
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 2 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. 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 BERT model."""
|
| 16 |
+
|
| 17 |
+
from collections.abc import Callable
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import nn
|
| 22 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 23 |
+
|
| 24 |
+
from ... import initialization as init
|
| 25 |
+
from ...activations import ACT2FN
|
| 26 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 27 |
+
from ...generation import GenerationMixin
|
| 28 |
+
from ...masking_utils import create_bidirectional_mask, create_causal_mask
|
| 29 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 30 |
+
from ...modeling_outputs import (
|
| 31 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 32 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
| 33 |
+
CausalLMOutputWithCrossAttentions,
|
| 34 |
+
MaskedLMOutput,
|
| 35 |
+
MultipleChoiceModelOutput,
|
| 36 |
+
NextSentencePredictorOutput,
|
| 37 |
+
QuestionAnsweringModelOutput,
|
| 38 |
+
SequenceClassifierOutput,
|
| 39 |
+
TokenClassifierOutput,
|
| 40 |
+
)
|
| 41 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 42 |
+
from ...processing_utils import Unpack
|
| 43 |
+
from ...pytorch_utils import apply_chunking_to_forward
|
| 44 |
+
from ...utils import ModelOutput, TransformersKwargs, auto_docstring, logging
|
| 45 |
+
from ...utils.generic import can_return_tuple, merge_with_config_defaults
|
| 46 |
+
from ...utils.output_capturing import capture_outputs
|
| 47 |
+
from .configuration_bert import BertConfig
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
logger = logging.get_logger(__name__)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class BertEmbeddings(nn.Module):
|
| 54 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 55 |
+
|
| 56 |
+
def __init__(self, config):
|
| 57 |
+
super().__init__()
|
| 58 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 59 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 60 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
| 61 |
+
|
| 62 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 63 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 64 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 65 |
+
self.register_buffer(
|
| 66 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 67 |
+
)
|
| 68 |
+
self.register_buffer(
|
| 69 |
+
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
def forward(
|
| 73 |
+
self,
|
| 74 |
+
input_ids: torch.LongTensor | None = None,
|
| 75 |
+
token_type_ids: torch.LongTensor | None = None,
|
| 76 |
+
position_ids: torch.LongTensor | None = None,
|
| 77 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 78 |
+
past_key_values_length: int = 0,
|
| 79 |
+
) -> torch.Tensor:
|
| 80 |
+
if input_ids is not None:
|
| 81 |
+
input_shape = input_ids.size()
|
| 82 |
+
else:
|
| 83 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 84 |
+
|
| 85 |
+
batch_size, seq_length = input_shape
|
| 86 |
+
|
| 87 |
+
if position_ids is None:
|
| 88 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
| 89 |
+
|
| 90 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
| 91 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
| 92 |
+
# issue #5664
|
| 93 |
+
if token_type_ids is None:
|
| 94 |
+
if hasattr(self, "token_type_ids"):
|
| 95 |
+
# NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
|
| 96 |
+
buffered_token_type_ids = self.token_type_ids.expand(position_ids.shape[0], -1)
|
| 97 |
+
buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
|
| 98 |
+
token_type_ids = buffered_token_type_ids.expand(batch_size, seq_length)
|
| 99 |
+
else:
|
| 100 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 101 |
+
|
| 102 |
+
if inputs_embeds is None:
|
| 103 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 104 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 105 |
+
embeddings = inputs_embeds + token_type_embeddings
|
| 106 |
+
|
| 107 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 108 |
+
embeddings = embeddings + position_embeddings
|
| 109 |
+
|
| 110 |
+
embeddings = self.LayerNorm(embeddings)
|
| 111 |
+
embeddings = self.dropout(embeddings)
|
| 112 |
+
return embeddings
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def eager_attention_forward(
|
| 116 |
+
module: nn.Module,
|
| 117 |
+
query: torch.Tensor,
|
| 118 |
+
key: torch.Tensor,
|
| 119 |
+
value: torch.Tensor,
|
| 120 |
+
attention_mask: torch.Tensor | None,
|
| 121 |
+
scaling: float | None = None,
|
| 122 |
+
dropout: float = 0.0,
|
| 123 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 124 |
+
):
|
| 125 |
+
if scaling is None:
|
| 126 |
+
scaling = query.size(-1) ** -0.5
|
| 127 |
+
|
| 128 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 129 |
+
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
|
| 130 |
+
|
| 131 |
+
if attention_mask is not None:
|
| 132 |
+
attn_weights = attn_weights + attention_mask
|
| 133 |
+
|
| 134 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 135 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 136 |
+
|
| 137 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 138 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 139 |
+
|
| 140 |
+
return attn_output, attn_weights
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class BertSelfAttention(nn.Module):
|
| 144 |
+
def __init__(self, config, is_causal=False, layer_idx=None):
|
| 145 |
+
super().__init__()
|
| 146 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 147 |
+
raise ValueError(
|
| 148 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 149 |
+
f"heads ({config.num_attention_heads})"
|
| 150 |
+
)
|
| 151 |
+
self.config = config
|
| 152 |
+
|
| 153 |
+
self.num_attention_heads = config.num_attention_heads
|
| 154 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 155 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 156 |
+
self.scaling = self.attention_head_size**-0.5
|
| 157 |
+
|
| 158 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 159 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 160 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 161 |
+
|
| 162 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 163 |
+
|
| 164 |
+
self.is_decoder = config.is_decoder
|
| 165 |
+
self.is_causal = is_causal
|
| 166 |
+
self.layer_idx = layer_idx
|
| 167 |
+
|
| 168 |
+
def forward(
|
| 169 |
+
self,
|
| 170 |
+
hidden_states: torch.Tensor,
|
| 171 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 172 |
+
past_key_values: Cache | None = None,
|
| 173 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 174 |
+
) -> tuple[torch.Tensor]:
|
| 175 |
+
input_shape = hidden_states.shape[:-1]
|
| 176 |
+
hidden_shape = (*input_shape, -1, self.attention_head_size)
|
| 177 |
+
|
| 178 |
+
# get all proj
|
| 179 |
+
query_layer = self.query(hidden_states).view(*hidden_shape).transpose(1, 2)
|
| 180 |
+
key_layer = self.key(hidden_states).view(*hidden_shape).transpose(1, 2)
|
| 181 |
+
value_layer = self.value(hidden_states).view(*hidden_shape).transpose(1, 2)
|
| 182 |
+
|
| 183 |
+
if past_key_values is not None:
|
| 184 |
+
# decoder-only bert can have a simple dynamic cache for example
|
| 185 |
+
current_past_key_values = past_key_values
|
| 186 |
+
if isinstance(past_key_values, EncoderDecoderCache):
|
| 187 |
+
current_past_key_values = past_key_values.self_attention_cache
|
| 188 |
+
|
| 189 |
+
# save all key/value_layer to cache to be re-used for fast auto-regressive generation
|
| 190 |
+
key_layer, value_layer = current_past_key_values.update(key_layer, value_layer, self.layer_idx)
|
| 191 |
+
|
| 192 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 193 |
+
self.config._attn_implementation, eager_attention_forward
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
attn_output, attn_weights = attention_interface(
|
| 197 |
+
self,
|
| 198 |
+
query_layer,
|
| 199 |
+
key_layer,
|
| 200 |
+
value_layer,
|
| 201 |
+
attention_mask,
|
| 202 |
+
dropout=0.0 if not self.training else self.dropout.p,
|
| 203 |
+
scaling=self.scaling,
|
| 204 |
+
**kwargs,
|
| 205 |
+
)
|
| 206 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 207 |
+
return attn_output, attn_weights
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class BertCrossAttention(nn.Module):
|
| 211 |
+
def __init__(self, config, is_causal=False, layer_idx=None):
|
| 212 |
+
super().__init__()
|
| 213 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 214 |
+
raise ValueError(
|
| 215 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 216 |
+
f"heads ({config.num_attention_heads})"
|
| 217 |
+
)
|
| 218 |
+
self.config = config
|
| 219 |
+
|
| 220 |
+
self.num_attention_heads = config.num_attention_heads
|
| 221 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 222 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 223 |
+
self.scaling = self.attention_head_size**-0.5
|
| 224 |
+
|
| 225 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 226 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 227 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 228 |
+
|
| 229 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 230 |
+
|
| 231 |
+
self.is_causal = is_causal
|
| 232 |
+
self.layer_idx = layer_idx
|
| 233 |
+
|
| 234 |
+
def forward(
|
| 235 |
+
self,
|
| 236 |
+
hidden_states: torch.Tensor,
|
| 237 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 238 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 239 |
+
past_key_values: EncoderDecoderCache | None = None,
|
| 240 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 241 |
+
) -> tuple[torch.Tensor]:
|
| 242 |
+
# determine input shapes
|
| 243 |
+
input_shape = hidden_states.shape[:-1]
|
| 244 |
+
|
| 245 |
+
hidden_shape = (*input_shape, -1, self.attention_head_size)
|
| 246 |
+
|
| 247 |
+
# get query proj
|
| 248 |
+
query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 249 |
+
|
| 250 |
+
is_updated = past_key_values.is_updated.get(self.layer_idx) if past_key_values is not None else False
|
| 251 |
+
if past_key_values is not None and is_updated:
|
| 252 |
+
# reuse k,v, cross_attentions
|
| 253 |
+
key_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].keys
|
| 254 |
+
value_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].values
|
| 255 |
+
else:
|
| 256 |
+
kv_shape = (*encoder_hidden_states.shape[:-1], -1, self.attention_head_size)
|
| 257 |
+
key_layer = self.key(encoder_hidden_states).view(kv_shape).transpose(1, 2)
|
| 258 |
+
value_layer = self.value(encoder_hidden_states).view(kv_shape).transpose(1, 2)
|
| 259 |
+
|
| 260 |
+
if past_key_values is not None:
|
| 261 |
+
# save all states to the cache
|
| 262 |
+
key_layer, value_layer = past_key_values.cross_attention_cache.update(
|
| 263 |
+
key_layer, value_layer, self.layer_idx
|
| 264 |
+
)
|
| 265 |
+
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
|
| 266 |
+
past_key_values.is_updated[self.layer_idx] = True
|
| 267 |
+
|
| 268 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 269 |
+
self.config._attn_implementation, eager_attention_forward
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
attn_output, attn_weights = attention_interface(
|
| 273 |
+
self,
|
| 274 |
+
query_layer,
|
| 275 |
+
key_layer,
|
| 276 |
+
value_layer,
|
| 277 |
+
attention_mask,
|
| 278 |
+
dropout=0.0 if not self.training else self.dropout.p,
|
| 279 |
+
scaling=self.scaling,
|
| 280 |
+
**kwargs,
|
| 281 |
+
)
|
| 282 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 283 |
+
return attn_output, attn_weights
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
class BertSelfOutput(nn.Module):
|
| 287 |
+
def __init__(self, config):
|
| 288 |
+
super().__init__()
|
| 289 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 290 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 291 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 292 |
+
|
| 293 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 294 |
+
hidden_states = self.dense(hidden_states)
|
| 295 |
+
hidden_states = self.dropout(hidden_states)
|
| 296 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 297 |
+
return hidden_states
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
class BertAttention(nn.Module):
|
| 301 |
+
def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
|
| 302 |
+
super().__init__()
|
| 303 |
+
self.is_cross_attention = is_cross_attention
|
| 304 |
+
attention_class = BertCrossAttention if is_cross_attention else BertSelfAttention
|
| 305 |
+
self.self = attention_class(config, is_causal=is_causal, layer_idx=layer_idx)
|
| 306 |
+
self.output = BertSelfOutput(config)
|
| 307 |
+
|
| 308 |
+
def forward(
|
| 309 |
+
self,
|
| 310 |
+
hidden_states: torch.Tensor,
|
| 311 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 312 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 313 |
+
encoder_attention_mask: torch.FloatTensor | None = None,
|
| 314 |
+
past_key_values: Cache | None = None,
|
| 315 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 316 |
+
) -> tuple[torch.Tensor]:
|
| 317 |
+
attention_mask = attention_mask if not self.is_cross_attention else encoder_attention_mask
|
| 318 |
+
attention_output, attn_weights = self.self(
|
| 319 |
+
hidden_states,
|
| 320 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 321 |
+
attention_mask=attention_mask,
|
| 322 |
+
past_key_values=past_key_values,
|
| 323 |
+
**kwargs,
|
| 324 |
+
)
|
| 325 |
+
attention_output = self.output(attention_output, hidden_states)
|
| 326 |
+
return attention_output, attn_weights
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
class BertIntermediate(nn.Module):
|
| 330 |
+
def __init__(self, config):
|
| 331 |
+
super().__init__()
|
| 332 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 333 |
+
if isinstance(config.hidden_act, str):
|
| 334 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 335 |
+
else:
|
| 336 |
+
self.intermediate_act_fn = config.hidden_act
|
| 337 |
+
|
| 338 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 339 |
+
hidden_states = self.dense(hidden_states)
|
| 340 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 341 |
+
return hidden_states
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
class BertOutput(nn.Module):
|
| 345 |
+
def __init__(self, config):
|
| 346 |
+
super().__init__()
|
| 347 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 348 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 349 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 350 |
+
|
| 351 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 352 |
+
hidden_states = self.dense(hidden_states)
|
| 353 |
+
hidden_states = self.dropout(hidden_states)
|
| 354 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 355 |
+
return hidden_states
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
class BertLayer(GradientCheckpointingLayer):
|
| 359 |
+
def __init__(self, config, layer_idx=None):
|
| 360 |
+
super().__init__()
|
| 361 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 362 |
+
self.seq_len_dim = 1
|
| 363 |
+
self.attention = BertAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx)
|
| 364 |
+
self.is_decoder = config.is_decoder
|
| 365 |
+
self.add_cross_attention = config.add_cross_attention
|
| 366 |
+
if self.add_cross_attention:
|
| 367 |
+
if not self.is_decoder:
|
| 368 |
+
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
|
| 369 |
+
self.crossattention = BertAttention(
|
| 370 |
+
config,
|
| 371 |
+
is_causal=False,
|
| 372 |
+
layer_idx=layer_idx,
|
| 373 |
+
is_cross_attention=True,
|
| 374 |
+
)
|
| 375 |
+
self.intermediate = BertIntermediate(config)
|
| 376 |
+
self.output = BertOutput(config)
|
| 377 |
+
|
| 378 |
+
def forward(
|
| 379 |
+
self,
|
| 380 |
+
hidden_states: torch.Tensor,
|
| 381 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 382 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 383 |
+
encoder_attention_mask: torch.FloatTensor | None = None,
|
| 384 |
+
past_key_values: Cache | None = None,
|
| 385 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 386 |
+
) -> torch.Tensor:
|
| 387 |
+
self_attention_output, _ = self.attention(
|
| 388 |
+
hidden_states,
|
| 389 |
+
attention_mask,
|
| 390 |
+
past_key_values=past_key_values,
|
| 391 |
+
**kwargs,
|
| 392 |
+
)
|
| 393 |
+
attention_output = self_attention_output
|
| 394 |
+
|
| 395 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
| 396 |
+
if not hasattr(self, "crossattention"):
|
| 397 |
+
raise ValueError(
|
| 398 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
| 399 |
+
" by setting `config.add_cross_attention=True`"
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
cross_attention_output, _ = self.crossattention(
|
| 403 |
+
self_attention_output,
|
| 404 |
+
None, # attention_mask
|
| 405 |
+
encoder_hidden_states,
|
| 406 |
+
encoder_attention_mask,
|
| 407 |
+
past_key_values=past_key_values,
|
| 408 |
+
**kwargs,
|
| 409 |
+
)
|
| 410 |
+
attention_output = cross_attention_output
|
| 411 |
+
|
| 412 |
+
layer_output = apply_chunking_to_forward(
|
| 413 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 414 |
+
)
|
| 415 |
+
return layer_output
|
| 416 |
+
|
| 417 |
+
def feed_forward_chunk(self, attention_output):
|
| 418 |
+
intermediate_output = self.intermediate(attention_output)
|
| 419 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 420 |
+
return layer_output
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
class BertEncoder(nn.Module):
|
| 424 |
+
def __init__(self, config):
|
| 425 |
+
super().__init__()
|
| 426 |
+
self.config = config
|
| 427 |
+
self.layer = nn.ModuleList([BertLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
|
| 428 |
+
|
| 429 |
+
def forward(
|
| 430 |
+
self,
|
| 431 |
+
hidden_states: torch.Tensor,
|
| 432 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 433 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 434 |
+
encoder_attention_mask: torch.FloatTensor | None = None,
|
| 435 |
+
past_key_values: Cache | None = None,
|
| 436 |
+
use_cache: bool | None = None,
|
| 437 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 438 |
+
) -> tuple[torch.Tensor] | BaseModelOutputWithPastAndCrossAttentions:
|
| 439 |
+
for i, layer_module in enumerate(self.layer):
|
| 440 |
+
hidden_states = layer_module(
|
| 441 |
+
hidden_states,
|
| 442 |
+
attention_mask,
|
| 443 |
+
encoder_hidden_states, # as a positional argument for gradient checkpointing
|
| 444 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 445 |
+
past_key_values=past_key_values,
|
| 446 |
+
**kwargs,
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 450 |
+
last_hidden_state=hidden_states,
|
| 451 |
+
past_key_values=past_key_values if use_cache else None,
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
class BertPooler(nn.Module):
|
| 456 |
+
def __init__(self, config):
|
| 457 |
+
super().__init__()
|
| 458 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 459 |
+
self.activation = nn.Tanh()
|
| 460 |
+
|
| 461 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 462 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 463 |
+
# to the first token.
|
| 464 |
+
first_token_tensor = hidden_states[:, 0]
|
| 465 |
+
pooled_output = self.dense(first_token_tensor)
|
| 466 |
+
pooled_output = self.activation(pooled_output)
|
| 467 |
+
return pooled_output
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
class BertPredictionHeadTransform(nn.Module):
|
| 471 |
+
def __init__(self, config):
|
| 472 |
+
super().__init__()
|
| 473 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 474 |
+
if isinstance(config.hidden_act, str):
|
| 475 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
| 476 |
+
else:
|
| 477 |
+
self.transform_act_fn = config.hidden_act
|
| 478 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 479 |
+
|
| 480 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 481 |
+
hidden_states = self.dense(hidden_states)
|
| 482 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
| 483 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 484 |
+
return hidden_states
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
class BertLMPredictionHead(nn.Module):
|
| 488 |
+
def __init__(self, config):
|
| 489 |
+
super().__init__()
|
| 490 |
+
self.transform = BertPredictionHeadTransform(config)
|
| 491 |
+
|
| 492 |
+
# The output weights are the same as the input embeddings, but there is
|
| 493 |
+
# an output-only bias for each token.
|
| 494 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
|
| 495 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 496 |
+
|
| 497 |
+
def forward(self, hidden_states):
|
| 498 |
+
hidden_states = self.transform(hidden_states)
|
| 499 |
+
hidden_states = self.decoder(hidden_states)
|
| 500 |
+
return hidden_states
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
class BertOnlyMLMHead(nn.Module):
|
| 504 |
+
def __init__(self, config):
|
| 505 |
+
super().__init__()
|
| 506 |
+
self.predictions = BertLMPredictionHead(config)
|
| 507 |
+
|
| 508 |
+
def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
|
| 509 |
+
prediction_scores = self.predictions(sequence_output)
|
| 510 |
+
return prediction_scores
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
class BertOnlyNSPHead(nn.Module):
|
| 514 |
+
def __init__(self, config):
|
| 515 |
+
super().__init__()
|
| 516 |
+
self.seq_relationship = nn.Linear(config.hidden_size, 2)
|
| 517 |
+
|
| 518 |
+
def forward(self, pooled_output):
|
| 519 |
+
seq_relationship_score = self.seq_relationship(pooled_output)
|
| 520 |
+
return seq_relationship_score
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
class BertPreTrainingHeads(nn.Module):
|
| 524 |
+
def __init__(self, config):
|
| 525 |
+
super().__init__()
|
| 526 |
+
self.predictions = BertLMPredictionHead(config)
|
| 527 |
+
self.seq_relationship = nn.Linear(config.hidden_size, 2)
|
| 528 |
+
|
| 529 |
+
def forward(self, sequence_output, pooled_output):
|
| 530 |
+
prediction_scores = self.predictions(sequence_output)
|
| 531 |
+
seq_relationship_score = self.seq_relationship(pooled_output)
|
| 532 |
+
return prediction_scores, seq_relationship_score
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
@auto_docstring
|
| 536 |
+
class BertPreTrainedModel(PreTrainedModel):
|
| 537 |
+
config_class = BertConfig
|
| 538 |
+
base_model_prefix = "bert"
|
| 539 |
+
supports_gradient_checkpointing = True
|
| 540 |
+
_supports_flash_attn = True
|
| 541 |
+
_supports_sdpa = True
|
| 542 |
+
_supports_flex_attn = True
|
| 543 |
+
_supports_attention_backend = True
|
| 544 |
+
_can_record_outputs = {
|
| 545 |
+
"hidden_states": BertLayer,
|
| 546 |
+
"attentions": BertSelfAttention,
|
| 547 |
+
"cross_attentions": BertCrossAttention,
|
| 548 |
+
}
|
| 549 |
+
|
| 550 |
+
@torch.no_grad()
|
| 551 |
+
def _init_weights(self, module):
|
| 552 |
+
"""Initialize the weights"""
|
| 553 |
+
super()._init_weights(module)
|
| 554 |
+
if isinstance(module, BertLMPredictionHead):
|
| 555 |
+
init.zeros_(module.bias)
|
| 556 |
+
elif isinstance(module, BertEmbeddings):
|
| 557 |
+
init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
|
| 558 |
+
init.zeros_(module.token_type_ids)
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
@auto_docstring(
|
| 562 |
+
custom_intro="""
|
| 563 |
+
Output type of [`BertForPreTraining`].
|
| 564 |
+
"""
|
| 565 |
+
)
|
| 566 |
+
@dataclass
|
| 567 |
+
class BertForPreTrainingOutput(ModelOutput):
|
| 568 |
+
r"""
|
| 569 |
+
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
|
| 570 |
+
Total loss as the sum of the masked language modeling loss and the next sequence prediction
|
| 571 |
+
(classification) loss.
|
| 572 |
+
prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 573 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 574 |
+
seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
|
| 575 |
+
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
|
| 576 |
+
before SoftMax).
|
| 577 |
+
"""
|
| 578 |
+
|
| 579 |
+
loss: torch.FloatTensor | None = None
|
| 580 |
+
prediction_logits: torch.FloatTensor | None = None
|
| 581 |
+
seq_relationship_logits: torch.FloatTensor | None = None
|
| 582 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 583 |
+
attentions: tuple[torch.FloatTensor] | None = None
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
@auto_docstring(
|
| 587 |
+
custom_intro="""
|
| 588 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
| 589 |
+
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
|
| 590 |
+
all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
|
| 591 |
+
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
|
| 592 |
+
|
| 593 |
+
To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
|
| 594 |
+
to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
|
| 595 |
+
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
|
| 596 |
+
"""
|
| 597 |
+
)
|
| 598 |
+
class BertModel(BertPreTrainedModel):
|
| 599 |
+
_no_split_modules = ["BertEmbeddings", "BertLayer"]
|
| 600 |
+
|
| 601 |
+
def __init__(self, config, add_pooling_layer=True):
|
| 602 |
+
r"""
|
| 603 |
+
add_pooling_layer (bool, *optional*, defaults to `True`):
|
| 604 |
+
Whether to add a pooling layer
|
| 605 |
+
"""
|
| 606 |
+
super().__init__(config)
|
| 607 |
+
self.config = config
|
| 608 |
+
self.gradient_checkpointing = False
|
| 609 |
+
|
| 610 |
+
self.embeddings = BertEmbeddings(config)
|
| 611 |
+
self.encoder = BertEncoder(config)
|
| 612 |
+
|
| 613 |
+
self.pooler = BertPooler(config) if add_pooling_layer else None
|
| 614 |
+
|
| 615 |
+
# Initialize weights and apply final processing
|
| 616 |
+
self.post_init()
|
| 617 |
+
|
| 618 |
+
def get_input_embeddings(self):
|
| 619 |
+
return self.embeddings.word_embeddings
|
| 620 |
+
|
| 621 |
+
def set_input_embeddings(self, value):
|
| 622 |
+
self.embeddings.word_embeddings = value
|
| 623 |
+
|
| 624 |
+
@merge_with_config_defaults
|
| 625 |
+
@capture_outputs
|
| 626 |
+
@auto_docstring
|
| 627 |
+
def forward(
|
| 628 |
+
self,
|
| 629 |
+
input_ids: torch.Tensor | None = None,
|
| 630 |
+
attention_mask: torch.Tensor | None = None,
|
| 631 |
+
token_type_ids: torch.Tensor | None = None,
|
| 632 |
+
position_ids: torch.Tensor | None = None,
|
| 633 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 634 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 635 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 636 |
+
past_key_values: Cache | None = None,
|
| 637 |
+
use_cache: bool | None = None,
|
| 638 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 639 |
+
) -> tuple[torch.Tensor] | BaseModelOutputWithPoolingAndCrossAttentions:
|
| 640 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 641 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 642 |
+
|
| 643 |
+
if self.config.is_decoder:
|
| 644 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 645 |
+
else:
|
| 646 |
+
use_cache = False
|
| 647 |
+
|
| 648 |
+
if use_cache and past_key_values is None:
|
| 649 |
+
past_key_values = (
|
| 650 |
+
EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
|
| 651 |
+
if encoder_hidden_states is not None or self.config.is_encoder_decoder
|
| 652 |
+
else DynamicCache(config=self.config)
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 656 |
+
|
| 657 |
+
embedding_output = self.embeddings(
|
| 658 |
+
input_ids=input_ids,
|
| 659 |
+
position_ids=position_ids,
|
| 660 |
+
token_type_ids=token_type_ids,
|
| 661 |
+
inputs_embeds=inputs_embeds,
|
| 662 |
+
past_key_values_length=past_key_values_length,
|
| 663 |
+
)
|
| 664 |
+
|
| 665 |
+
attention_mask, encoder_attention_mask = self._create_attention_masks(
|
| 666 |
+
attention_mask=attention_mask,
|
| 667 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 668 |
+
embedding_output=embedding_output,
|
| 669 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 670 |
+
past_key_values=past_key_values,
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
encoder_outputs = self.encoder(
|
| 674 |
+
embedding_output,
|
| 675 |
+
attention_mask=attention_mask,
|
| 676 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 677 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 678 |
+
past_key_values=past_key_values,
|
| 679 |
+
use_cache=use_cache,
|
| 680 |
+
position_ids=position_ids,
|
| 681 |
+
**kwargs,
|
| 682 |
+
)
|
| 683 |
+
sequence_output = encoder_outputs.last_hidden_state
|
| 684 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 685 |
+
|
| 686 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
| 687 |
+
last_hidden_state=sequence_output,
|
| 688 |
+
pooler_output=pooled_output,
|
| 689 |
+
past_key_values=encoder_outputs.past_key_values,
|
| 690 |
+
)
|
| 691 |
+
|
| 692 |
+
def _create_attention_masks(
|
| 693 |
+
self,
|
| 694 |
+
attention_mask,
|
| 695 |
+
encoder_attention_mask,
|
| 696 |
+
embedding_output,
|
| 697 |
+
encoder_hidden_states,
|
| 698 |
+
past_key_values,
|
| 699 |
+
):
|
| 700 |
+
if self.config.is_decoder:
|
| 701 |
+
attention_mask = create_causal_mask(
|
| 702 |
+
config=self.config,
|
| 703 |
+
inputs_embeds=embedding_output,
|
| 704 |
+
attention_mask=attention_mask,
|
| 705 |
+
past_key_values=past_key_values,
|
| 706 |
+
)
|
| 707 |
+
else:
|
| 708 |
+
attention_mask = create_bidirectional_mask(
|
| 709 |
+
config=self.config,
|
| 710 |
+
inputs_embeds=embedding_output,
|
| 711 |
+
attention_mask=attention_mask,
|
| 712 |
+
)
|
| 713 |
+
|
| 714 |
+
if encoder_attention_mask is not None:
|
| 715 |
+
encoder_attention_mask = create_bidirectional_mask(
|
| 716 |
+
config=self.config,
|
| 717 |
+
inputs_embeds=embedding_output,
|
| 718 |
+
attention_mask=encoder_attention_mask,
|
| 719 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 720 |
+
)
|
| 721 |
+
|
| 722 |
+
return attention_mask, encoder_attention_mask
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
@auto_docstring(
|
| 726 |
+
custom_intro="""
|
| 727 |
+
Bert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
|
| 728 |
+
sentence prediction (classification)` head.
|
| 729 |
+
"""
|
| 730 |
+
)
|
| 731 |
+
class BertForPreTraining(BertPreTrainedModel):
|
| 732 |
+
_tied_weights_keys = {
|
| 733 |
+
"cls.predictions.decoder.weight": "bert.embeddings.word_embeddings.weight",
|
| 734 |
+
"cls.predictions.decoder.bias": "cls.predictions.bias",
|
| 735 |
+
}
|
| 736 |
+
|
| 737 |
+
def __init__(self, config):
|
| 738 |
+
super().__init__(config)
|
| 739 |
+
|
| 740 |
+
self.bert = BertModel(config)
|
| 741 |
+
self.cls = BertPreTrainingHeads(config)
|
| 742 |
+
|
| 743 |
+
# Initialize weights and apply final processing
|
| 744 |
+
self.post_init()
|
| 745 |
+
|
| 746 |
+
def get_output_embeddings(self):
|
| 747 |
+
return self.cls.predictions.decoder
|
| 748 |
+
|
| 749 |
+
def set_output_embeddings(self, new_embeddings):
|
| 750 |
+
self.cls.predictions.decoder = new_embeddings
|
| 751 |
+
self.cls.predictions.bias = new_embeddings.bias
|
| 752 |
+
|
| 753 |
+
@can_return_tuple
|
| 754 |
+
@auto_docstring
|
| 755 |
+
def forward(
|
| 756 |
+
self,
|
| 757 |
+
input_ids: torch.Tensor | None = None,
|
| 758 |
+
attention_mask: torch.Tensor | None = None,
|
| 759 |
+
token_type_ids: torch.Tensor | None = None,
|
| 760 |
+
position_ids: torch.Tensor | None = None,
|
| 761 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 762 |
+
labels: torch.Tensor | None = None,
|
| 763 |
+
next_sentence_label: torch.Tensor | None = None,
|
| 764 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 765 |
+
) -> tuple[torch.Tensor] | BertForPreTrainingOutput:
|
| 766 |
+
r"""
|
| 767 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 768 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 769 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
|
| 770 |
+
the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 771 |
+
next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 772 |
+
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
|
| 773 |
+
pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
|
| 774 |
+
|
| 775 |
+
- 0 indicates sequence B is a continuation of sequence A,
|
| 776 |
+
- 1 indicates sequence B is a random sequence.
|
| 777 |
+
|
| 778 |
+
Example:
|
| 779 |
+
|
| 780 |
+
```python
|
| 781 |
+
>>> from transformers import AutoTokenizer, BertForPreTraining
|
| 782 |
+
>>> import torch
|
| 783 |
+
|
| 784 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
|
| 785 |
+
>>> model = BertForPreTraining.from_pretrained("google-bert/bert-base-uncased")
|
| 786 |
+
|
| 787 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
| 788 |
+
>>> outputs = model(**inputs)
|
| 789 |
+
|
| 790 |
+
>>> prediction_logits = outputs.prediction_logits
|
| 791 |
+
>>> seq_relationship_logits = outputs.seq_relationship_logits
|
| 792 |
+
```
|
| 793 |
+
"""
|
| 794 |
+
outputs = self.bert(
|
| 795 |
+
input_ids,
|
| 796 |
+
attention_mask=attention_mask,
|
| 797 |
+
token_type_ids=token_type_ids,
|
| 798 |
+
position_ids=position_ids,
|
| 799 |
+
inputs_embeds=inputs_embeds,
|
| 800 |
+
return_dict=True,
|
| 801 |
+
**kwargs,
|
| 802 |
+
)
|
| 803 |
+
|
| 804 |
+
sequence_output, pooled_output = outputs[:2]
|
| 805 |
+
prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
|
| 806 |
+
|
| 807 |
+
total_loss = None
|
| 808 |
+
if labels is not None and next_sentence_label is not None:
|
| 809 |
+
loss_fct = CrossEntropyLoss()
|
| 810 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 811 |
+
next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
|
| 812 |
+
total_loss = masked_lm_loss + next_sentence_loss
|
| 813 |
+
|
| 814 |
+
return BertForPreTrainingOutput(
|
| 815 |
+
loss=total_loss,
|
| 816 |
+
prediction_logits=prediction_scores,
|
| 817 |
+
seq_relationship_logits=seq_relationship_score,
|
| 818 |
+
hidden_states=outputs.hidden_states,
|
| 819 |
+
attentions=outputs.attentions,
|
| 820 |
+
)
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
@auto_docstring(
|
| 824 |
+
custom_intro="""
|
| 825 |
+
Bert Model with a `language modeling` head on top for CLM fine-tuning.
|
| 826 |
+
"""
|
| 827 |
+
)
|
| 828 |
+
class BertLMHeadModel(BertPreTrainedModel, GenerationMixin):
|
| 829 |
+
_tied_weights_keys = {
|
| 830 |
+
"cls.predictions.decoder.weight": "bert.embeddings.word_embeddings.weight",
|
| 831 |
+
"cls.predictions.decoder.bias": "cls.predictions.bias",
|
| 832 |
+
}
|
| 833 |
+
|
| 834 |
+
def __init__(self, config):
|
| 835 |
+
super().__init__(config)
|
| 836 |
+
|
| 837 |
+
if not config.is_decoder:
|
| 838 |
+
logger.warning("If you want to use `BertLMHeadModel` as a standalone, add `is_decoder=True.`")
|
| 839 |
+
|
| 840 |
+
self.bert = BertModel(config, add_pooling_layer=False)
|
| 841 |
+
self.cls = BertOnlyMLMHead(config)
|
| 842 |
+
|
| 843 |
+
# Initialize weights and apply final processing
|
| 844 |
+
self.post_init()
|
| 845 |
+
|
| 846 |
+
def get_output_embeddings(self):
|
| 847 |
+
return self.cls.predictions.decoder
|
| 848 |
+
|
| 849 |
+
def set_output_embeddings(self, new_embeddings):
|
| 850 |
+
self.cls.predictions.decoder = new_embeddings
|
| 851 |
+
self.cls.predictions.bias = new_embeddings.bias
|
| 852 |
+
|
| 853 |
+
@can_return_tuple
|
| 854 |
+
@auto_docstring
|
| 855 |
+
def forward(
|
| 856 |
+
self,
|
| 857 |
+
input_ids: torch.Tensor | None = None,
|
| 858 |
+
attention_mask: torch.Tensor | None = None,
|
| 859 |
+
token_type_ids: torch.Tensor | None = None,
|
| 860 |
+
position_ids: torch.Tensor | None = None,
|
| 861 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 862 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 863 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 864 |
+
labels: torch.Tensor | None = None,
|
| 865 |
+
past_key_values: Cache | None = None,
|
| 866 |
+
use_cache: bool | None = None,
|
| 867 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 868 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 869 |
+
) -> tuple[torch.Tensor] | CausalLMOutputWithCrossAttentions:
|
| 870 |
+
r"""
|
| 871 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 872 |
+
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
|
| 873 |
+
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
|
| 874 |
+
ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
|
| 875 |
+
"""
|
| 876 |
+
if labels is not None:
|
| 877 |
+
use_cache = False
|
| 878 |
+
|
| 879 |
+
outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.bert(
|
| 880 |
+
input_ids,
|
| 881 |
+
attention_mask=attention_mask,
|
| 882 |
+
token_type_ids=token_type_ids,
|
| 883 |
+
position_ids=position_ids,
|
| 884 |
+
inputs_embeds=inputs_embeds,
|
| 885 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 886 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 887 |
+
past_key_values=past_key_values,
|
| 888 |
+
use_cache=use_cache,
|
| 889 |
+
return_dict=True,
|
| 890 |
+
**kwargs,
|
| 891 |
+
)
|
| 892 |
+
|
| 893 |
+
hidden_states = outputs.last_hidden_state
|
| 894 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 895 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 896 |
+
logits = self.cls(hidden_states[:, slice_indices, :])
|
| 897 |
+
|
| 898 |
+
loss = None
|
| 899 |
+
if labels is not None:
|
| 900 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 901 |
+
|
| 902 |
+
return CausalLMOutputWithCrossAttentions(
|
| 903 |
+
loss=loss,
|
| 904 |
+
logits=logits,
|
| 905 |
+
past_key_values=outputs.past_key_values,
|
| 906 |
+
hidden_states=outputs.hidden_states,
|
| 907 |
+
attentions=outputs.attentions,
|
| 908 |
+
cross_attentions=outputs.cross_attentions,
|
| 909 |
+
)
|
| 910 |
+
|
| 911 |
+
|
| 912 |
+
@auto_docstring
|
| 913 |
+
class BertForMaskedLM(BertPreTrainedModel):
|
| 914 |
+
_tied_weights_keys = {
|
| 915 |
+
"cls.predictions.decoder.weight": "bert.embeddings.word_embeddings.weight",
|
| 916 |
+
"cls.predictions.decoder.bias": "cls.predictions.bias",
|
| 917 |
+
}
|
| 918 |
+
|
| 919 |
+
def __init__(self, config):
|
| 920 |
+
super().__init__(config)
|
| 921 |
+
|
| 922 |
+
if config.is_decoder:
|
| 923 |
+
logger.warning(
|
| 924 |
+
"If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for "
|
| 925 |
+
"bi-directional self-attention."
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
self.bert = BertModel(config, add_pooling_layer=False)
|
| 929 |
+
self.cls = BertOnlyMLMHead(config)
|
| 930 |
+
|
| 931 |
+
# Initialize weights and apply final processing
|
| 932 |
+
self.post_init()
|
| 933 |
+
|
| 934 |
+
def get_output_embeddings(self):
|
| 935 |
+
return self.cls.predictions.decoder
|
| 936 |
+
|
| 937 |
+
def set_output_embeddings(self, new_embeddings):
|
| 938 |
+
self.cls.predictions.decoder = new_embeddings
|
| 939 |
+
self.cls.predictions.bias = new_embeddings.bias
|
| 940 |
+
|
| 941 |
+
@can_return_tuple
|
| 942 |
+
@auto_docstring
|
| 943 |
+
def forward(
|
| 944 |
+
self,
|
| 945 |
+
input_ids: torch.Tensor | None = None,
|
| 946 |
+
attention_mask: torch.Tensor | None = None,
|
| 947 |
+
token_type_ids: torch.Tensor | None = None,
|
| 948 |
+
position_ids: torch.Tensor | None = None,
|
| 949 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 950 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 951 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 952 |
+
labels: torch.Tensor | None = None,
|
| 953 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 954 |
+
) -> tuple[torch.Tensor] | MaskedLMOutput:
|
| 955 |
+
r"""
|
| 956 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 957 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 958 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 959 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 960 |
+
"""
|
| 961 |
+
outputs = self.bert(
|
| 962 |
+
input_ids,
|
| 963 |
+
attention_mask=attention_mask,
|
| 964 |
+
token_type_ids=token_type_ids,
|
| 965 |
+
position_ids=position_ids,
|
| 966 |
+
inputs_embeds=inputs_embeds,
|
| 967 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 968 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 969 |
+
return_dict=True,
|
| 970 |
+
**kwargs,
|
| 971 |
+
)
|
| 972 |
+
|
| 973 |
+
sequence_output = outputs[0]
|
| 974 |
+
prediction_scores = self.cls(sequence_output)
|
| 975 |
+
|
| 976 |
+
masked_lm_loss = None
|
| 977 |
+
if labels is not None:
|
| 978 |
+
loss_fct = CrossEntropyLoss() # -100 index = padding token
|
| 979 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 980 |
+
|
| 981 |
+
return MaskedLMOutput(
|
| 982 |
+
loss=masked_lm_loss,
|
| 983 |
+
logits=prediction_scores,
|
| 984 |
+
hidden_states=outputs.hidden_states,
|
| 985 |
+
attentions=outputs.attentions,
|
| 986 |
+
)
|
| 987 |
+
|
| 988 |
+
|
| 989 |
+
@auto_docstring(
|
| 990 |
+
custom_intro="""
|
| 991 |
+
Bert Model with a `next sentence prediction (classification)` head on top.
|
| 992 |
+
"""
|
| 993 |
+
)
|
| 994 |
+
class BertForNextSentencePrediction(BertPreTrainedModel):
|
| 995 |
+
def __init__(self, config):
|
| 996 |
+
super().__init__(config)
|
| 997 |
+
|
| 998 |
+
self.bert = BertModel(config)
|
| 999 |
+
self.cls = BertOnlyNSPHead(config)
|
| 1000 |
+
|
| 1001 |
+
# Initialize weights and apply final processing
|
| 1002 |
+
self.post_init()
|
| 1003 |
+
|
| 1004 |
+
@can_return_tuple
|
| 1005 |
+
@auto_docstring
|
| 1006 |
+
def forward(
|
| 1007 |
+
self,
|
| 1008 |
+
input_ids: torch.Tensor | None = None,
|
| 1009 |
+
attention_mask: torch.Tensor | None = None,
|
| 1010 |
+
token_type_ids: torch.Tensor | None = None,
|
| 1011 |
+
position_ids: torch.Tensor | None = None,
|
| 1012 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1013 |
+
labels: torch.Tensor | None = None,
|
| 1014 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1015 |
+
) -> tuple[torch.Tensor] | NextSentencePredictorOutput:
|
| 1016 |
+
r"""
|
| 1017 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1018 |
+
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
|
| 1019 |
+
(see `input_ids` docstring). Indices should be in `[0, 1]`:
|
| 1020 |
+
|
| 1021 |
+
- 0 indicates sequence B is a continuation of sequence A,
|
| 1022 |
+
- 1 indicates sequence B is a random sequence.
|
| 1023 |
+
|
| 1024 |
+
Example:
|
| 1025 |
+
|
| 1026 |
+
```python
|
| 1027 |
+
>>> from transformers import AutoTokenizer, BertForNextSentencePrediction
|
| 1028 |
+
>>> import torch
|
| 1029 |
+
|
| 1030 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
|
| 1031 |
+
>>> model = BertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")
|
| 1032 |
+
|
| 1033 |
+
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
|
| 1034 |
+
>>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
|
| 1035 |
+
>>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
|
| 1036 |
+
|
| 1037 |
+
>>> outputs = model(**encoding, labels=torch.LongTensor([1]))
|
| 1038 |
+
>>> logits = outputs.logits
|
| 1039 |
+
>>> assert logits[0, 0] < logits[0, 1] # next sentence was random
|
| 1040 |
+
```
|
| 1041 |
+
"""
|
| 1042 |
+
|
| 1043 |
+
outputs = self.bert(
|
| 1044 |
+
input_ids,
|
| 1045 |
+
attention_mask=attention_mask,
|
| 1046 |
+
token_type_ids=token_type_ids,
|
| 1047 |
+
position_ids=position_ids,
|
| 1048 |
+
inputs_embeds=inputs_embeds,
|
| 1049 |
+
return_dict=True,
|
| 1050 |
+
**kwargs,
|
| 1051 |
+
)
|
| 1052 |
+
|
| 1053 |
+
pooled_output = outputs[1]
|
| 1054 |
+
|
| 1055 |
+
seq_relationship_scores = self.cls(pooled_output)
|
| 1056 |
+
|
| 1057 |
+
next_sentence_loss = None
|
| 1058 |
+
if labels is not None:
|
| 1059 |
+
loss_fct = CrossEntropyLoss()
|
| 1060 |
+
next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
|
| 1061 |
+
|
| 1062 |
+
return NextSentencePredictorOutput(
|
| 1063 |
+
loss=next_sentence_loss,
|
| 1064 |
+
logits=seq_relationship_scores,
|
| 1065 |
+
hidden_states=outputs.hidden_states,
|
| 1066 |
+
attentions=outputs.attentions,
|
| 1067 |
+
)
|
| 1068 |
+
|
| 1069 |
+
|
| 1070 |
+
@auto_docstring(
|
| 1071 |
+
custom_intro="""
|
| 1072 |
+
Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
|
| 1073 |
+
output) e.g. for GLUE tasks.
|
| 1074 |
+
"""
|
| 1075 |
+
)
|
| 1076 |
+
class BertForSequenceClassification(BertPreTrainedModel):
|
| 1077 |
+
def __init__(self, config):
|
| 1078 |
+
super().__init__(config)
|
| 1079 |
+
self.num_labels = config.num_labels
|
| 1080 |
+
self.config = config
|
| 1081 |
+
|
| 1082 |
+
self.bert = BertModel(config)
|
| 1083 |
+
classifier_dropout = (
|
| 1084 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 1085 |
+
)
|
| 1086 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 1087 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 1088 |
+
|
| 1089 |
+
# Initialize weights and apply final processing
|
| 1090 |
+
self.post_init()
|
| 1091 |
+
|
| 1092 |
+
@can_return_tuple
|
| 1093 |
+
@auto_docstring
|
| 1094 |
+
def forward(
|
| 1095 |
+
self,
|
| 1096 |
+
input_ids: torch.Tensor | None = None,
|
| 1097 |
+
attention_mask: torch.Tensor | None = None,
|
| 1098 |
+
token_type_ids: torch.Tensor | None = None,
|
| 1099 |
+
position_ids: torch.Tensor | None = None,
|
| 1100 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1101 |
+
labels: torch.Tensor | None = None,
|
| 1102 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1103 |
+
) -> tuple[torch.Tensor] | SequenceClassifierOutput:
|
| 1104 |
+
r"""
|
| 1105 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1106 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1107 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1108 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1109 |
+
"""
|
| 1110 |
+
outputs = self.bert(
|
| 1111 |
+
input_ids,
|
| 1112 |
+
attention_mask=attention_mask,
|
| 1113 |
+
token_type_ids=token_type_ids,
|
| 1114 |
+
position_ids=position_ids,
|
| 1115 |
+
inputs_embeds=inputs_embeds,
|
| 1116 |
+
return_dict=True,
|
| 1117 |
+
**kwargs,
|
| 1118 |
+
)
|
| 1119 |
+
|
| 1120 |
+
pooled_output = outputs[1]
|
| 1121 |
+
|
| 1122 |
+
pooled_output = self.dropout(pooled_output)
|
| 1123 |
+
logits = self.classifier(pooled_output)
|
| 1124 |
+
|
| 1125 |
+
loss = None
|
| 1126 |
+
if labels is not None:
|
| 1127 |
+
if self.config.problem_type is None:
|
| 1128 |
+
if self.num_labels == 1:
|
| 1129 |
+
self.config.problem_type = "regression"
|
| 1130 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1131 |
+
self.config.problem_type = "single_label_classification"
|
| 1132 |
+
else:
|
| 1133 |
+
self.config.problem_type = "multi_label_classification"
|
| 1134 |
+
|
| 1135 |
+
if self.config.problem_type == "regression":
|
| 1136 |
+
loss_fct = MSELoss()
|
| 1137 |
+
if self.num_labels == 1:
|
| 1138 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 1139 |
+
else:
|
| 1140 |
+
loss = loss_fct(logits, labels)
|
| 1141 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1142 |
+
loss_fct = CrossEntropyLoss()
|
| 1143 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1144 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1145 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1146 |
+
loss = loss_fct(logits, labels)
|
| 1147 |
+
|
| 1148 |
+
return SequenceClassifierOutput(
|
| 1149 |
+
loss=loss,
|
| 1150 |
+
logits=logits,
|
| 1151 |
+
hidden_states=outputs.hidden_states,
|
| 1152 |
+
attentions=outputs.attentions,
|
| 1153 |
+
)
|
| 1154 |
+
|
| 1155 |
+
|
| 1156 |
+
@auto_docstring
|
| 1157 |
+
class BertForMultipleChoice(BertPreTrainedModel):
|
| 1158 |
+
def __init__(self, config):
|
| 1159 |
+
super().__init__(config)
|
| 1160 |
+
|
| 1161 |
+
self.bert = BertModel(config)
|
| 1162 |
+
classifier_dropout = (
|
| 1163 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 1164 |
+
)
|
| 1165 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 1166 |
+
self.classifier = nn.Linear(config.hidden_size, 1)
|
| 1167 |
+
|
| 1168 |
+
# Initialize weights and apply final processing
|
| 1169 |
+
self.post_init()
|
| 1170 |
+
|
| 1171 |
+
@can_return_tuple
|
| 1172 |
+
@auto_docstring
|
| 1173 |
+
def forward(
|
| 1174 |
+
self,
|
| 1175 |
+
input_ids: torch.Tensor | None = None,
|
| 1176 |
+
attention_mask: torch.Tensor | None = None,
|
| 1177 |
+
token_type_ids: torch.Tensor | None = None,
|
| 1178 |
+
position_ids: torch.Tensor | None = None,
|
| 1179 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1180 |
+
labels: torch.Tensor | None = None,
|
| 1181 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1182 |
+
) -> tuple[torch.Tensor] | MultipleChoiceModelOutput:
|
| 1183 |
+
r"""
|
| 1184 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
|
| 1185 |
+
Indices of input sequence tokens in the vocabulary.
|
| 1186 |
+
|
| 1187 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1188 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1189 |
+
|
| 1190 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1191 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
|
| 1192 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 1193 |
+
1]`:
|
| 1194 |
+
|
| 1195 |
+
- 0 corresponds to a *sentence A* token,
|
| 1196 |
+
- 1 corresponds to a *sentence B* token.
|
| 1197 |
+
|
| 1198 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 1199 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
|
| 1200 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 1201 |
+
config.max_position_embeddings - 1]`.
|
| 1202 |
+
|
| 1203 |
+
[What are position IDs?](../glossary#position-ids)
|
| 1204 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
|
| 1205 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 1206 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 1207 |
+
model's internal embedding lookup matrix.
|
| 1208 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1209 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
|
| 1210 |
+
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
|
| 1211 |
+
`input_ids` above)
|
| 1212 |
+
"""
|
| 1213 |
+
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
|
| 1214 |
+
|
| 1215 |
+
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
|
| 1216 |
+
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
|
| 1217 |
+
token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
|
| 1218 |
+
position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
|
| 1219 |
+
inputs_embeds = (
|
| 1220 |
+
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
|
| 1221 |
+
if inputs_embeds is not None
|
| 1222 |
+
else None
|
| 1223 |
+
)
|
| 1224 |
+
|
| 1225 |
+
outputs = self.bert(
|
| 1226 |
+
input_ids,
|
| 1227 |
+
attention_mask=attention_mask,
|
| 1228 |
+
token_type_ids=token_type_ids,
|
| 1229 |
+
position_ids=position_ids,
|
| 1230 |
+
inputs_embeds=inputs_embeds,
|
| 1231 |
+
return_dict=True,
|
| 1232 |
+
**kwargs,
|
| 1233 |
+
)
|
| 1234 |
+
|
| 1235 |
+
pooled_output = outputs[1]
|
| 1236 |
+
|
| 1237 |
+
pooled_output = self.dropout(pooled_output)
|
| 1238 |
+
logits = self.classifier(pooled_output)
|
| 1239 |
+
reshaped_logits = logits.view(-1, num_choices)
|
| 1240 |
+
|
| 1241 |
+
loss = None
|
| 1242 |
+
if labels is not None:
|
| 1243 |
+
loss_fct = CrossEntropyLoss()
|
| 1244 |
+
loss = loss_fct(reshaped_logits, labels)
|
| 1245 |
+
|
| 1246 |
+
return MultipleChoiceModelOutput(
|
| 1247 |
+
loss=loss,
|
| 1248 |
+
logits=reshaped_logits,
|
| 1249 |
+
hidden_states=outputs.hidden_states,
|
| 1250 |
+
attentions=outputs.attentions,
|
| 1251 |
+
)
|
| 1252 |
+
|
| 1253 |
+
|
| 1254 |
+
@auto_docstring
|
| 1255 |
+
class BertForTokenClassification(BertPreTrainedModel):
|
| 1256 |
+
def __init__(self, config):
|
| 1257 |
+
super().__init__(config)
|
| 1258 |
+
self.num_labels = config.num_labels
|
| 1259 |
+
|
| 1260 |
+
self.bert = BertModel(config, add_pooling_layer=False)
|
| 1261 |
+
classifier_dropout = (
|
| 1262 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 1263 |
+
)
|
| 1264 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 1265 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 1266 |
+
|
| 1267 |
+
# Initialize weights and apply final processing
|
| 1268 |
+
self.post_init()
|
| 1269 |
+
|
| 1270 |
+
@can_return_tuple
|
| 1271 |
+
@auto_docstring
|
| 1272 |
+
def forward(
|
| 1273 |
+
self,
|
| 1274 |
+
input_ids: torch.Tensor | None = None,
|
| 1275 |
+
attention_mask: torch.Tensor | None = None,
|
| 1276 |
+
token_type_ids: torch.Tensor | None = None,
|
| 1277 |
+
position_ids: torch.Tensor | None = None,
|
| 1278 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1279 |
+
labels: torch.Tensor | None = None,
|
| 1280 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1281 |
+
) -> tuple[torch.Tensor] | TokenClassifierOutput:
|
| 1282 |
+
r"""
|
| 1283 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1284 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 1285 |
+
"""
|
| 1286 |
+
outputs = self.bert(
|
| 1287 |
+
input_ids,
|
| 1288 |
+
attention_mask=attention_mask,
|
| 1289 |
+
token_type_ids=token_type_ids,
|
| 1290 |
+
position_ids=position_ids,
|
| 1291 |
+
inputs_embeds=inputs_embeds,
|
| 1292 |
+
return_dict=True,
|
| 1293 |
+
**kwargs,
|
| 1294 |
+
)
|
| 1295 |
+
|
| 1296 |
+
sequence_output = outputs[0]
|
| 1297 |
+
|
| 1298 |
+
sequence_output = self.dropout(sequence_output)
|
| 1299 |
+
logits = self.classifier(sequence_output)
|
| 1300 |
+
|
| 1301 |
+
loss = None
|
| 1302 |
+
if labels is not None:
|
| 1303 |
+
loss_fct = CrossEntropyLoss()
|
| 1304 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1305 |
+
|
| 1306 |
+
return TokenClassifierOutput(
|
| 1307 |
+
loss=loss,
|
| 1308 |
+
logits=logits,
|
| 1309 |
+
hidden_states=outputs.hidden_states,
|
| 1310 |
+
attentions=outputs.attentions,
|
| 1311 |
+
)
|
| 1312 |
+
|
| 1313 |
+
|
| 1314 |
+
@auto_docstring
|
| 1315 |
+
class BertForQuestionAnswering(BertPreTrainedModel):
|
| 1316 |
+
def __init__(self, config):
|
| 1317 |
+
super().__init__(config)
|
| 1318 |
+
self.num_labels = config.num_labels
|
| 1319 |
+
|
| 1320 |
+
self.bert = BertModel(config, add_pooling_layer=False)
|
| 1321 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
| 1322 |
+
|
| 1323 |
+
# Initialize weights and apply final processing
|
| 1324 |
+
self.post_init()
|
| 1325 |
+
|
| 1326 |
+
@can_return_tuple
|
| 1327 |
+
@auto_docstring
|
| 1328 |
+
def forward(
|
| 1329 |
+
self,
|
| 1330 |
+
input_ids: torch.Tensor | None = None,
|
| 1331 |
+
attention_mask: torch.Tensor | None = None,
|
| 1332 |
+
token_type_ids: torch.Tensor | None = None,
|
| 1333 |
+
position_ids: torch.Tensor | None = None,
|
| 1334 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1335 |
+
start_positions: torch.Tensor | None = None,
|
| 1336 |
+
end_positions: torch.Tensor | None = None,
|
| 1337 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1338 |
+
) -> tuple[torch.Tensor] | QuestionAnsweringModelOutput:
|
| 1339 |
+
outputs = self.bert(
|
| 1340 |
+
input_ids,
|
| 1341 |
+
attention_mask=attention_mask,
|
| 1342 |
+
token_type_ids=token_type_ids,
|
| 1343 |
+
position_ids=position_ids,
|
| 1344 |
+
inputs_embeds=inputs_embeds,
|
| 1345 |
+
return_dict=True,
|
| 1346 |
+
**kwargs,
|
| 1347 |
+
)
|
| 1348 |
+
|
| 1349 |
+
sequence_output = outputs[0]
|
| 1350 |
+
|
| 1351 |
+
logits = self.qa_outputs(sequence_output)
|
| 1352 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1353 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 1354 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 1355 |
+
|
| 1356 |
+
total_loss = None
|
| 1357 |
+
if start_positions is not None and end_positions is not None:
|
| 1358 |
+
# If we are on multi-GPU, split add a dimension
|
| 1359 |
+
if len(start_positions.size()) > 1:
|
| 1360 |
+
start_positions = start_positions.squeeze(-1)
|
| 1361 |
+
if len(end_positions.size()) > 1:
|
| 1362 |
+
end_positions = end_positions.squeeze(-1)
|
| 1363 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1364 |
+
ignored_index = start_logits.size(1)
|
| 1365 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 1366 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 1367 |
+
|
| 1368 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 1369 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1370 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1371 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1372 |
+
|
| 1373 |
+
return QuestionAnsweringModelOutput(
|
| 1374 |
+
loss=total_loss,
|
| 1375 |
+
start_logits=start_logits,
|
| 1376 |
+
end_logits=end_logits,
|
| 1377 |
+
hidden_states=outputs.hidden_states,
|
| 1378 |
+
attentions=outputs.attentions,
|
| 1379 |
+
)
|
| 1380 |
+
|
| 1381 |
+
|
| 1382 |
+
__all__ = [
|
| 1383 |
+
"BertForMaskedLM",
|
| 1384 |
+
"BertForMultipleChoice",
|
| 1385 |
+
"BertForNextSentencePrediction",
|
| 1386 |
+
"BertForPreTraining",
|
| 1387 |
+
"BertForQuestionAnswering",
|
| 1388 |
+
"BertForSequenceClassification",
|
| 1389 |
+
"BertForTokenClassification",
|
| 1390 |
+
"BertLayer",
|
| 1391 |
+
"BertLMHeadModel",
|
| 1392 |
+
"BertModel",
|
| 1393 |
+
"BertPreTrainedModel",
|
| 1394 |
+
]
|
lib/python3.11/site-packages/transformers/models/bert/tokenization_bert.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 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 |
+
"""Tokenization classes for Bert."""
|
| 15 |
+
|
| 16 |
+
import collections
|
| 17 |
+
|
| 18 |
+
from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
|
| 19 |
+
from tokenizers.models import WordPiece
|
| 20 |
+
|
| 21 |
+
from ...tokenization_utils_tokenizers import TokenizersBackend
|
| 22 |
+
from ...utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def load_vocab(vocab_file):
|
| 31 |
+
"""Loads a vocabulary file into a dictionary."""
|
| 32 |
+
vocab = collections.OrderedDict()
|
| 33 |
+
with open(vocab_file, "r", encoding="utf-8") as reader:
|
| 34 |
+
tokens = reader.readlines()
|
| 35 |
+
for index, token in enumerate(tokens):
|
| 36 |
+
token = token.rstrip("\n")
|
| 37 |
+
vocab[token] = index
|
| 38 |
+
return vocab
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class BertTokenizer(TokenizersBackend):
|
| 42 |
+
r"""
|
| 43 |
+
Construct a BERT tokenizer (backed by HuggingFace's tokenizers library). Based on WordPiece.
|
| 44 |
+
|
| 45 |
+
This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should refer to
|
| 46 |
+
this superclass for more information regarding those methods.
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
vocab (`str` or `dict[str, int]`, *optional*):
|
| 50 |
+
Custom vocabulary dictionary. If not provided, vocabulary is loaded from `vocab_file`.
|
| 51 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 52 |
+
Whether or not to lowercase the input when tokenizing.
|
| 53 |
+
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
|
| 54 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 55 |
+
token instead.
|
| 56 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 57 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 58 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 59 |
+
token of a sequence built with special tokens.
|
| 60 |
+
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
|
| 61 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 62 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 63 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 64 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 65 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 66 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 67 |
+
modeling. This is the token which the model will try to predict.
|
| 68 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 69 |
+
Whether or not to tokenize Chinese characters.
|
| 70 |
+
strip_accents (`bool`, *optional*):
|
| 71 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 72 |
+
value for `lowercase` (as in the original BERT).
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 76 |
+
model_input_names = ["input_ids", "token_type_ids", "attention_mask"]
|
| 77 |
+
model = WordPiece
|
| 78 |
+
|
| 79 |
+
def __init__(
|
| 80 |
+
self,
|
| 81 |
+
vocab: str | dict[str, int] | None = None,
|
| 82 |
+
do_lower_case: bool = True,
|
| 83 |
+
unk_token: str = "[UNK]",
|
| 84 |
+
sep_token: str = "[SEP]",
|
| 85 |
+
pad_token: str = "[PAD]",
|
| 86 |
+
cls_token: str = "[CLS]",
|
| 87 |
+
mask_token: str = "[MASK]",
|
| 88 |
+
tokenize_chinese_chars: bool = True,
|
| 89 |
+
strip_accents: bool | None = None,
|
| 90 |
+
**kwargs,
|
| 91 |
+
):
|
| 92 |
+
self.do_lower_case = do_lower_case
|
| 93 |
+
self.tokenize_chinese_chars = tokenize_chinese_chars
|
| 94 |
+
self.strip_accents = strip_accents
|
| 95 |
+
if vocab is None:
|
| 96 |
+
vocab = {
|
| 97 |
+
str(pad_token): 0,
|
| 98 |
+
str(unk_token): 1,
|
| 99 |
+
str(cls_token): 2,
|
| 100 |
+
str(sep_token): 3,
|
| 101 |
+
str(mask_token): 4,
|
| 102 |
+
}
|
| 103 |
+
self._vocab = vocab
|
| 104 |
+
self._tokenizer = Tokenizer(WordPiece(self._vocab, unk_token=str(unk_token)))
|
| 105 |
+
self._tokenizer.normalizer = normalizers.BertNormalizer(
|
| 106 |
+
clean_text=True,
|
| 107 |
+
handle_chinese_chars=tokenize_chinese_chars,
|
| 108 |
+
strip_accents=strip_accents,
|
| 109 |
+
lowercase=do_lower_case,
|
| 110 |
+
)
|
| 111 |
+
self._tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
|
| 112 |
+
self._tokenizer.decoder = decoders.WordPiece(prefix="##")
|
| 113 |
+
super().__init__(
|
| 114 |
+
do_lower_case=do_lower_case,
|
| 115 |
+
unk_token=unk_token,
|
| 116 |
+
sep_token=sep_token,
|
| 117 |
+
pad_token=pad_token,
|
| 118 |
+
cls_token=cls_token,
|
| 119 |
+
mask_token=mask_token,
|
| 120 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 121 |
+
strip_accents=strip_accents,
|
| 122 |
+
**kwargs,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
cls_token_id = self.cls_token_id if self.cls_token_id is not None else 2
|
| 126 |
+
sep_token_id = self.sep_token_id if self.sep_token_id is not None else 3
|
| 127 |
+
|
| 128 |
+
self._tokenizer.post_processor = processors.TemplateProcessing(
|
| 129 |
+
single=f"{str(self.cls_token)}:0 $A:0 {str(self.sep_token)}:0",
|
| 130 |
+
pair=f"{str(self.cls_token)}:0 $A:0 {str(self.sep_token)}:0 $B:1 {str(self.sep_token)}:1",
|
| 131 |
+
special_tokens=[
|
| 132 |
+
(str(self.cls_token), cls_token_id),
|
| 133 |
+
(str(self.sep_token), sep_token_id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ace Inc. team.
|
| 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 |
+
"""Tokenization classes for Bert."""
|
| 15 |
+
|
| 16 |
+
import collections
|
| 17 |
+
import os
|
| 18 |
+
import unicodedata
|
| 19 |
+
|
| 20 |
+
from ...tokenization_python import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
|
| 21 |
+
from ...utils import logging
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def load_vocab(vocab_file):
|
| 30 |
+
"""Loads a vocabulary file into a dictionary."""
|
| 31 |
+
vocab = collections.OrderedDict()
|
| 32 |
+
with open(vocab_file, "r", encoding="utf-8") as reader:
|
| 33 |
+
tokens = reader.readlines()
|
| 34 |
+
for index, token in enumerate(tokens):
|
| 35 |
+
token = token.rstrip("\n")
|
| 36 |
+
vocab[token] = index
|
| 37 |
+
return vocab
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def whitespace_tokenize(text):
|
| 41 |
+
"""Runs basic whitespace cleaning and splitting on a piece of text."""
|
| 42 |
+
text = text.strip()
|
| 43 |
+
if not text:
|
| 44 |
+
return []
|
| 45 |
+
tokens = text.split()
|
| 46 |
+
return tokens
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class BertTokenizerLegacy(PreTrainedTokenizer):
|
| 50 |
+
r"""
|
| 51 |
+
Construct a BERT tokenizer. Based on WordPiece.
|
| 52 |
+
|
| 53 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 54 |
+
this superclass for more information regarding those methods.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
vocab_file (`str`):
|
| 58 |
+
File containing the vocabulary.
|
| 59 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 60 |
+
Whether or not to lowercase the input when tokenizing.
|
| 61 |
+
do_basic_tokenize (`bool`, *optional*, defaults to `True`):
|
| 62 |
+
Whether or not to do basic tokenization before WordPiece.
|
| 63 |
+
never_split (`Iterable`, *optional*):
|
| 64 |
+
Collection of tokens which will never be split during tokenization. Only has an effect when
|
| 65 |
+
`do_basic_tokenize=True`
|
| 66 |
+
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
|
| 67 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 68 |
+
token instead.
|
| 69 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 70 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 71 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 72 |
+
token of a sequence built with special tokens.
|
| 73 |
+
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
|
| 74 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 75 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 76 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 77 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 78 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 79 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 80 |
+
modeling. This is the token which the model will try to predict.
|
| 81 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 82 |
+
Whether or not to tokenize Chinese characters.
|
| 83 |
+
|
| 84 |
+
This should likely be deactivated for Japanese (see this
|
| 85 |
+
[issue](https://github.com/huggingface/transformers/issues/328)).
|
| 86 |
+
strip_accents (`bool`, *optional*):
|
| 87 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 88 |
+
value for `lowercase` (as in the original BERT).
|
| 89 |
+
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
|
| 90 |
+
Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
|
| 91 |
+
extra spaces.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 95 |
+
|
| 96 |
+
def __init__(
|
| 97 |
+
self,
|
| 98 |
+
vocab_file,
|
| 99 |
+
do_lower_case=True,
|
| 100 |
+
do_basic_tokenize=True,
|
| 101 |
+
never_split=None,
|
| 102 |
+
unk_token="[UNK]",
|
| 103 |
+
sep_token="[SEP]",
|
| 104 |
+
pad_token="[PAD]",
|
| 105 |
+
cls_token="[CLS]",
|
| 106 |
+
mask_token="[MASK]",
|
| 107 |
+
tokenize_chinese_chars=True,
|
| 108 |
+
strip_accents=None,
|
| 109 |
+
clean_up_tokenization_spaces=True,
|
| 110 |
+
**kwargs,
|
| 111 |
+
):
|
| 112 |
+
if not os.path.isfile(vocab_file):
|
| 113 |
+
raise ValueError(
|
| 114 |
+
f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
|
| 115 |
+
" model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
|
| 116 |
+
)
|
| 117 |
+
self.vocab = load_vocab(vocab_file)
|
| 118 |
+
self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
|
| 119 |
+
self.do_basic_tokenize = do_basic_tokenize
|
| 120 |
+
if do_basic_tokenize:
|
| 121 |
+
self.basic_tokenizer = BasicTokenizer(
|
| 122 |
+
do_lower_case=do_lower_case,
|
| 123 |
+
never_split=never_split,
|
| 124 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 125 |
+
strip_accents=strip_accents,
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
|
| 129 |
+
|
| 130 |
+
super().__init__(
|
| 131 |
+
do_lower_case=do_lower_case,
|
| 132 |
+
do_basic_tokenize=do_basic_tokenize,
|
| 133 |
+
never_split=never_split,
|
| 134 |
+
unk_token=unk_token,
|
| 135 |
+
sep_token=sep_token,
|
| 136 |
+
pad_token=pad_token,
|
| 137 |
+
cls_token=cls_token,
|
| 138 |
+
mask_token=mask_token,
|
| 139 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 140 |
+
strip_accents=strip_accents,
|
| 141 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 142 |
+
**kwargs,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
@property
|
| 146 |
+
def do_lower_case(self):
|
| 147 |
+
return self.basic_tokenizer.do_lower_case
|
| 148 |
+
|
| 149 |
+
@property
|
| 150 |
+
def vocab_size(self):
|
| 151 |
+
return len(self.vocab)
|
| 152 |
+
|
| 153 |
+
def get_vocab(self):
|
| 154 |
+
return dict(self.vocab, **self.added_tokens_encoder)
|
| 155 |
+
|
| 156 |
+
def _tokenize(self, text, split_special_tokens=False):
|
| 157 |
+
split_tokens = []
|
| 158 |
+
if self.do_basic_tokenize:
|
| 159 |
+
for token in self.basic_tokenizer.tokenize(
|
| 160 |
+
text, never_split=self.all_special_tokens if not split_special_tokens else None
|
| 161 |
+
):
|
| 162 |
+
# If the token is part of the never_split set
|
| 163 |
+
if token in self.basic_tokenizer.never_split:
|
| 164 |
+
split_tokens.append(token)
|
| 165 |
+
else:
|
| 166 |
+
split_tokens += self.wordpiece_tokenizer.tokenize(token)
|
| 167 |
+
else:
|
| 168 |
+
split_tokens = self.wordpiece_tokenizer.tokenize(text)
|
| 169 |
+
return split_tokens
|
| 170 |
+
|
| 171 |
+
def _convert_token_to_id(self, token):
|
| 172 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 173 |
+
return self.vocab.get(token, self.vocab.get(self.unk_token))
|
| 174 |
+
|
| 175 |
+
def _convert_id_to_token(self, index):
|
| 176 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 177 |
+
return self.ids_to_tokens.get(index, self.unk_token)
|
| 178 |
+
|
| 179 |
+
def convert_tokens_to_string(self, tokens):
|
| 180 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 181 |
+
out_string = " ".join(tokens).replace(" ##", "").strip()
|
| 182 |
+
return out_string
|
| 183 |
+
|
| 184 |
+
def build_inputs_with_special_tokens(
|
| 185 |
+
self, token_ids_0: list[int], token_ids_1: list[int] | None = None
|
| 186 |
+
) -> list[int]:
|
| 187 |
+
"""
|
| 188 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 189 |
+
adding special tokens. A BERT sequence has the following format:
|
| 190 |
+
|
| 191 |
+
- single sequence: `[CLS] X [SEP]`
|
| 192 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 193 |
+
|
| 194 |
+
Args:
|
| 195 |
+
token_ids_0 (`List[int]`):
|
| 196 |
+
List of IDs to which the special tokens will be added.
|
| 197 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 198 |
+
Optional second list of IDs for sequence pairs.
|
| 199 |
+
|
| 200 |
+
Returns:
|
| 201 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 202 |
+
"""
|
| 203 |
+
if token_ids_1 is None:
|
| 204 |
+
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
| 205 |
+
cls = [self.cls_token_id]
|
| 206 |
+
sep = [self.sep_token_id]
|
| 207 |
+
return cls + token_ids_0 + sep + token_ids_1 + sep
|
| 208 |
+
|
| 209 |
+
def get_special_tokens_mask(
|
| 210 |
+
self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
|
| 211 |
+
) -> list[int]:
|
| 212 |
+
"""
|
| 213 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 214 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
token_ids_0 (`List[int]`):
|
| 218 |
+
List of IDs.
|
| 219 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 220 |
+
Optional second list of IDs for sequence pairs.
|
| 221 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 222 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 223 |
+
|
| 224 |
+
Returns:
|
| 225 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 226 |
+
"""
|
| 227 |
+
|
| 228 |
+
if already_has_special_tokens:
|
| 229 |
+
return super().get_special_tokens_mask(
|
| 230 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
if token_ids_1 is not None:
|
| 234 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
|
| 235 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
| 236 |
+
|
| 237 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
|
| 238 |
+
index = 0
|
| 239 |
+
if os.path.isdir(save_directory):
|
| 240 |
+
vocab_file = os.path.join(
|
| 241 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 242 |
+
)
|
| 243 |
+
else:
|
| 244 |
+
vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
|
| 245 |
+
with open(vocab_file, "w", encoding="utf-8") as writer:
|
| 246 |
+
for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
|
| 247 |
+
if index != token_index:
|
| 248 |
+
logger.warning(
|
| 249 |
+
f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
|
| 250 |
+
" Please check that the vocabulary is not corrupted!"
|
| 251 |
+
)
|
| 252 |
+
index = token_index
|
| 253 |
+
writer.write(token + "\n")
|
| 254 |
+
index += 1
|
| 255 |
+
return (vocab_file,)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
class BasicTokenizer:
|
| 259 |
+
"""
|
| 260 |
+
Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
|
| 261 |
+
|
| 262 |
+
Args:
|
| 263 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 264 |
+
Whether or not to lowercase the input when tokenizing.
|
| 265 |
+
never_split (`Iterable`, *optional*):
|
| 266 |
+
Collection of tokens which will never be split during tokenization. Only has an effect when
|
| 267 |
+
`do_basic_tokenize=True`
|
| 268 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 269 |
+
Whether or not to tokenize Chinese characters.
|
| 270 |
+
|
| 271 |
+
This should likely be deactivated for Japanese (see this
|
| 272 |
+
[issue](https://github.com/huggingface/transformers/issues/328)).
|
| 273 |
+
strip_accents (`bool`, *optional*):
|
| 274 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 275 |
+
value for `lowercase` (as in the original BERT).
|
| 276 |
+
do_split_on_punc (`bool`, *optional*, defaults to `True`):
|
| 277 |
+
In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
|
| 278 |
+
the full context of the words, such as contractions.
|
| 279 |
+
"""
|
| 280 |
+
|
| 281 |
+
def __init__(
|
| 282 |
+
self,
|
| 283 |
+
do_lower_case=True,
|
| 284 |
+
never_split=None,
|
| 285 |
+
tokenize_chinese_chars=True,
|
| 286 |
+
strip_accents=None,
|
| 287 |
+
do_split_on_punc=True,
|
| 288 |
+
):
|
| 289 |
+
if never_split is None:
|
| 290 |
+
never_split = []
|
| 291 |
+
self.do_lower_case = do_lower_case
|
| 292 |
+
self.never_split = set(never_split)
|
| 293 |
+
self.tokenize_chinese_chars = tokenize_chinese_chars
|
| 294 |
+
self.strip_accents = strip_accents
|
| 295 |
+
self.do_split_on_punc = do_split_on_punc
|
| 296 |
+
|
| 297 |
+
def tokenize(self, text, never_split=None):
|
| 298 |
+
"""
|
| 299 |
+
Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
|
| 300 |
+
|
| 301 |
+
Args:
|
| 302 |
+
never_split (`List[str]`, *optional*)
|
| 303 |
+
Kept for backward compatibility purposes. Now implemented directly at the base class level (see
|
| 304 |
+
[`PreTrainedTokenizer.tokenize`]) List of token not to split.
|
| 305 |
+
"""
|
| 306 |
+
# union() returns a new set by concatenating the two sets.
|
| 307 |
+
never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
|
| 308 |
+
text = self._clean_text(text)
|
| 309 |
+
|
| 310 |
+
# This was added on November 1st, 2018 for the multilingual and Chinese
|
| 311 |
+
# models. This is also applied to the English models now, but it doesn't
|
| 312 |
+
# matter since the English models were not trained on any Chinese data
|
| 313 |
+
# and generally don't have any Chinese data in them (there are Chinese
|
| 314 |
+
# characters in the vocabulary because Wikipedia does have some Chinese
|
| 315 |
+
# words in the English Wikipedia.).
|
| 316 |
+
if self.tokenize_chinese_chars:
|
| 317 |
+
text = self._tokenize_chinese_chars(text)
|
| 318 |
+
# prevents treating the same character with different unicode codepoints as different characters
|
| 319 |
+
unicode_normalized_text = unicodedata.normalize("NFC", text)
|
| 320 |
+
orig_tokens = whitespace_tokenize(unicode_normalized_text)
|
| 321 |
+
split_tokens = []
|
| 322 |
+
for token in orig_tokens:
|
| 323 |
+
if token not in never_split:
|
| 324 |
+
if self.do_lower_case:
|
| 325 |
+
token = token.lower()
|
| 326 |
+
if self.strip_accents is not False:
|
| 327 |
+
token = self._run_strip_accents(token)
|
| 328 |
+
elif self.strip_accents:
|
| 329 |
+
token = self._run_strip_accents(token)
|
| 330 |
+
split_tokens.extend(self._run_split_on_punc(token, never_split))
|
| 331 |
+
|
| 332 |
+
output_tokens = whitespace_tokenize(" ".join(split_tokens))
|
| 333 |
+
return output_tokens
|
| 334 |
+
|
| 335 |
+
def _run_strip_accents(self, text):
|
| 336 |
+
"""Strips accents from a piece of text."""
|
| 337 |
+
text = unicodedata.normalize("NFD", text)
|
| 338 |
+
output = []
|
| 339 |
+
for char in text:
|
| 340 |
+
cat = unicodedata.category(char)
|
| 341 |
+
if cat == "Mn":
|
| 342 |
+
continue
|
| 343 |
+
output.append(char)
|
| 344 |
+
return "".join(output)
|
| 345 |
+
|
| 346 |
+
def _run_split_on_punc(self, text, never_split=None):
|
| 347 |
+
"""Splits punctuation on a piece of text."""
|
| 348 |
+
if not self.do_split_on_punc or (never_split is not None and text in never_split):
|
| 349 |
+
return [text]
|
| 350 |
+
chars = list(text)
|
| 351 |
+
i = 0
|
| 352 |
+
start_new_word = True
|
| 353 |
+
output = []
|
| 354 |
+
while i < len(chars):
|
| 355 |
+
char = chars[i]
|
| 356 |
+
if _is_punctuation(char):
|
| 357 |
+
output.append([char])
|
| 358 |
+
start_new_word = True
|
| 359 |
+
else:
|
| 360 |
+
if start_new_word:
|
| 361 |
+
output.append([])
|
| 362 |
+
start_new_word = False
|
| 363 |
+
output[-1].append(char)
|
| 364 |
+
i += 1
|
| 365 |
+
|
| 366 |
+
return ["".join(x) for x in output]
|
| 367 |
+
|
| 368 |
+
def _tokenize_chinese_chars(self, text):
|
| 369 |
+
"""Adds whitespace around any CJK character."""
|
| 370 |
+
output = []
|
| 371 |
+
for char in text:
|
| 372 |
+
cp = ord(char)
|
| 373 |
+
if self._is_chinese_char(cp):
|
| 374 |
+
output.append(" ")
|
| 375 |
+
output.append(char)
|
| 376 |
+
output.append(" ")
|
| 377 |
+
else:
|
| 378 |
+
output.append(char)
|
| 379 |
+
return "".join(output)
|
| 380 |
+
|
| 381 |
+
def _is_chinese_char(self, cp):
|
| 382 |
+
"""Checks whether CP is the codepoint of a CJK character."""
|
| 383 |
+
# This defines a "chinese character" as anything in the CJK Unicode block:
|
| 384 |
+
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
|
| 385 |
+
#
|
| 386 |
+
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
|
| 387 |
+
# despite its name. The modern Korean Hangul alphabet is a different block,
|
| 388 |
+
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
|
| 389 |
+
# space-separated words, so they are not treated specially and handled
|
| 390 |
+
# like the all of the other languages.
|
| 391 |
+
if (
|
| 392 |
+
(cp >= 0x4E00 and cp <= 0x9FFF)
|
| 393 |
+
or (cp >= 0x3400 and cp <= 0x4DBF)
|
| 394 |
+
or (cp >= 0x20000 and cp <= 0x2A6DF)
|
| 395 |
+
or (cp >= 0x2A700 and cp <= 0x2B73F)
|
| 396 |
+
or (cp >= 0x2B740 and cp <= 0x2B81F)
|
| 397 |
+
or (cp >= 0x2B820 and cp <= 0x2CEAF)
|
| 398 |
+
or (cp >= 0xF900 and cp <= 0xFAFF)
|
| 399 |
+
or (cp >= 0x2F800 and cp <= 0x2FA1F)
|
| 400 |
+
):
|
| 401 |
+
return True
|
| 402 |
+
|
| 403 |
+
return False
|
| 404 |
+
|
| 405 |
+
def _clean_text(self, text):
|
| 406 |
+
"""Performs invalid character removal and whitespace cleanup on text."""
|
| 407 |
+
output = []
|
| 408 |
+
for char in text:
|
| 409 |
+
cp = ord(char)
|
| 410 |
+
if cp == 0 or cp == 0xFFFD or _is_control(char):
|
| 411 |
+
continue
|
| 412 |
+
if _is_whitespace(char):
|
| 413 |
+
output.append(" ")
|
| 414 |
+
else:
|
| 415 |
+
output.append(char)
|
| 416 |
+
return "".join(output)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
class WordpieceTokenizer:
|
| 420 |
+
"""Runs WordPiece tokenization."""
|
| 421 |
+
|
| 422 |
+
def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
|
| 423 |
+
self.vocab = vocab
|
| 424 |
+
self.unk_token = unk_token
|
| 425 |
+
self.max_input_chars_per_word = max_input_chars_per_word
|
| 426 |
+
|
| 427 |
+
def tokenize(self, text):
|
| 428 |
+
"""
|
| 429 |
+
Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
|
| 430 |
+
tokenization using the given vocabulary.
|
| 431 |
+
|
| 432 |
+
For example, `input = "unaffable"` will return as output `["un", "##aff", "##able"]`.
|
| 433 |
+
|
| 434 |
+
Args:
|
| 435 |
+
text: A single token or whitespace separated tokens. This should have
|
| 436 |
+
already been passed through *BasicTokenizer*.
|
| 437 |
+
|
| 438 |
+
Returns:
|
| 439 |
+
A list of wordpiece tokens.
|
| 440 |
+
"""
|
| 441 |
+
|
| 442 |
+
output_tokens = []
|
| 443 |
+
for token in whitespace_tokenize(text):
|
| 444 |
+
chars = list(token)
|
| 445 |
+
if len(chars) > self.max_input_chars_per_word:
|
| 446 |
+
output_tokens.append(self.unk_token)
|
| 447 |
+
continue
|
| 448 |
+
|
| 449 |
+
is_bad = False
|
| 450 |
+
start = 0
|
| 451 |
+
sub_tokens = []
|
| 452 |
+
while start < len(chars):
|
| 453 |
+
end = len(chars)
|
| 454 |
+
cur_substr = None
|
| 455 |
+
while start < end:
|
| 456 |
+
substr = "".join(chars[start:end])
|
| 457 |
+
if start > 0:
|
| 458 |
+
substr = "##" + substr
|
| 459 |
+
if substr in self.vocab:
|
| 460 |
+
cur_substr = substr
|
| 461 |
+
break
|
| 462 |
+
end -= 1
|
| 463 |
+
if cur_substr is None:
|
| 464 |
+
is_bad = True
|
| 465 |
+
break
|
| 466 |
+
sub_tokens.append(cur_substr)
|
| 467 |
+
start = end
|
| 468 |
+
|
| 469 |
+
if is_bad:
|
| 470 |
+
output_tokens.append(self.unk_token)
|
| 471 |
+
else:
|
| 472 |
+
output_tokens.extend(sub_tokens)
|
| 473 |
+
return output_tokens
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
__all__ = ["BasicTokenizer", "BertTokenizerLegacy", "WordpieceTokenizer"]
|
lib/python3.11/site-packages/transformers/models/bert_generation/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_bert_generation import *
|
| 22 |
+
from .modeling_bert_generation import *
|
| 23 |
+
from .tokenization_bert_generation import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.11/site-packages/transformers/models/bert_generation/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (855 Bytes). View file
|
|
|
lib/python3.11/site-packages/transformers/models/bert_generation/__pycache__/configuration_bert_generation.cpython-311.pyc
ADDED
|
Binary file (2.57 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/bert_generation/__pycache__/modeling_bert_generation.cpython-311.pyc
ADDED
|
Binary file (35.5 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/bert_generation/__pycache__/tokenization_bert_generation.cpython-311.pyc
ADDED
|
Binary file (4.48 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/bert_generation/configuration_bert_generation.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 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 |
+
"""BertGeneration model configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...utils import auto_docstring
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@auto_docstring(checkpoint="google/bert_for_seq_generation_L-24_bbc_encoder")
|
| 23 |
+
@strict
|
| 24 |
+
class BertGenerationConfig(PreTrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
Examples:
|
| 27 |
+
|
| 28 |
+
```python
|
| 29 |
+
>>> from transformers import BertGenerationConfig, BertGenerationEncoder
|
| 30 |
+
|
| 31 |
+
>>> # Initializing a BertGeneration config
|
| 32 |
+
>>> configuration = BertGenerationConfig()
|
| 33 |
+
|
| 34 |
+
>>> # Initializing a model (with random weights) from the config
|
| 35 |
+
>>> model = BertGenerationEncoder(configuration)
|
| 36 |
+
|
| 37 |
+
>>> # Accessing the model configuration
|
| 38 |
+
>>> configuration = model.config
|
| 39 |
+
```"""
|
| 40 |
+
|
| 41 |
+
model_type = "bert-generation"
|
| 42 |
+
|
| 43 |
+
vocab_size: int = 50358
|
| 44 |
+
hidden_size: int = 1024
|
| 45 |
+
num_hidden_layers: int = 24
|
| 46 |
+
num_attention_heads: int = 16
|
| 47 |
+
intermediate_size: int = 4096
|
| 48 |
+
hidden_act: str = "gelu"
|
| 49 |
+
hidden_dropout_prob: float | int = 0.1
|
| 50 |
+
attention_probs_dropout_prob: float | int = 0.1
|
| 51 |
+
max_position_embeddings: int = 512
|
| 52 |
+
initializer_range: float = 0.02
|
| 53 |
+
layer_norm_eps: float = 1e-12
|
| 54 |
+
pad_token_id: int | None = 0
|
| 55 |
+
bos_token_id: int | None = 2
|
| 56 |
+
eos_token_id: int | list[int] | None = 1
|
| 57 |
+
use_cache: bool = True
|
| 58 |
+
is_decoder: bool = False
|
| 59 |
+
add_cross_attention: bool = False
|
| 60 |
+
tie_word_embeddings: bool = True
|
| 61 |
+
|
| 62 |
+
|
| 63 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 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 |
+
"""PyTorch BERT model specific for generation."""
|
| 15 |
+
|
| 16 |
+
from collections.abc import Callable
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from torch import nn
|
| 20 |
+
|
| 21 |
+
from ... import initialization as init
|
| 22 |
+
from ...activations import ACT2FN
|
| 23 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 24 |
+
from ...generation import GenerationMixin
|
| 25 |
+
from ...masking_utils import create_bidirectional_mask, create_causal_mask
|
| 26 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 27 |
+
from ...modeling_outputs import BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions
|
| 28 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 29 |
+
from ...processing_utils import Unpack
|
| 30 |
+
from ...pytorch_utils import apply_chunking_to_forward
|
| 31 |
+
from ...utils import (
|
| 32 |
+
TransformersKwargs,
|
| 33 |
+
auto_docstring,
|
| 34 |
+
logging,
|
| 35 |
+
)
|
| 36 |
+
from ...utils.generic import can_return_tuple, merge_with_config_defaults
|
| 37 |
+
from ...utils.output_capturing import capture_outputs
|
| 38 |
+
from .configuration_bert_generation import BertGenerationConfig
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
logger = logging.get_logger(__name__)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->BertGeneration
|
| 45 |
+
class BertGenerationSelfOutput(nn.Module):
|
| 46 |
+
def __init__(self, config):
|
| 47 |
+
super().__init__()
|
| 48 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 49 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 50 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 51 |
+
|
| 52 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 53 |
+
hidden_states = self.dense(hidden_states)
|
| 54 |
+
hidden_states = self.dropout(hidden_states)
|
| 55 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 56 |
+
return hidden_states
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# Copied from transformers.models.bert.modeling_bert.eager_attention_forward
|
| 60 |
+
def eager_attention_forward(
|
| 61 |
+
module: nn.Module,
|
| 62 |
+
query: torch.Tensor,
|
| 63 |
+
key: torch.Tensor,
|
| 64 |
+
value: torch.Tensor,
|
| 65 |
+
attention_mask: torch.Tensor | None,
|
| 66 |
+
scaling: float | None = None,
|
| 67 |
+
dropout: float = 0.0,
|
| 68 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 69 |
+
):
|
| 70 |
+
if scaling is None:
|
| 71 |
+
scaling = query.size(-1) ** -0.5
|
| 72 |
+
|
| 73 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 74 |
+
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
|
| 75 |
+
|
| 76 |
+
if attention_mask is not None:
|
| 77 |
+
attn_weights = attn_weights + attention_mask
|
| 78 |
+
|
| 79 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 80 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 81 |
+
|
| 82 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 83 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 84 |
+
|
| 85 |
+
return attn_output, attn_weights
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->BertGeneration
|
| 89 |
+
class BertGenerationSelfAttention(nn.Module):
|
| 90 |
+
def __init__(self, config, is_causal=False, layer_idx=None):
|
| 91 |
+
super().__init__()
|
| 92 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 93 |
+
raise ValueError(
|
| 94 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 95 |
+
f"heads ({config.num_attention_heads})"
|
| 96 |
+
)
|
| 97 |
+
self.config = config
|
| 98 |
+
|
| 99 |
+
self.num_attention_heads = config.num_attention_heads
|
| 100 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 101 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 102 |
+
self.scaling = self.attention_head_size**-0.5
|
| 103 |
+
|
| 104 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 105 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 106 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 107 |
+
|
| 108 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 109 |
+
|
| 110 |
+
self.is_decoder = config.is_decoder
|
| 111 |
+
self.is_causal = is_causal
|
| 112 |
+
self.layer_idx = layer_idx
|
| 113 |
+
|
| 114 |
+
def forward(
|
| 115 |
+
self,
|
| 116 |
+
hidden_states: torch.Tensor,
|
| 117 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 118 |
+
past_key_values: Cache | None = None,
|
| 119 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 120 |
+
) -> tuple[torch.Tensor]:
|
| 121 |
+
input_shape = hidden_states.shape[:-1]
|
| 122 |
+
hidden_shape = (*input_shape, -1, self.attention_head_size)
|
| 123 |
+
|
| 124 |
+
# get all proj
|
| 125 |
+
query_layer = self.query(hidden_states).view(*hidden_shape).transpose(1, 2)
|
| 126 |
+
key_layer = self.key(hidden_states).view(*hidden_shape).transpose(1, 2)
|
| 127 |
+
value_layer = self.value(hidden_states).view(*hidden_shape).transpose(1, 2)
|
| 128 |
+
|
| 129 |
+
if past_key_values is not None:
|
| 130 |
+
# decoder-only bert can have a simple dynamic cache for example
|
| 131 |
+
current_past_key_values = past_key_values
|
| 132 |
+
if isinstance(past_key_values, EncoderDecoderCache):
|
| 133 |
+
current_past_key_values = past_key_values.self_attention_cache
|
| 134 |
+
|
| 135 |
+
# save all key/value_layer to cache to be re-used for fast auto-regressive generation
|
| 136 |
+
key_layer, value_layer = current_past_key_values.update(key_layer, value_layer, self.layer_idx)
|
| 137 |
+
|
| 138 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 139 |
+
self.config._attn_implementation, eager_attention_forward
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
attn_output, attn_weights = attention_interface(
|
| 143 |
+
self,
|
| 144 |
+
query_layer,
|
| 145 |
+
key_layer,
|
| 146 |
+
value_layer,
|
| 147 |
+
attention_mask,
|
| 148 |
+
dropout=0.0 if not self.training else self.dropout.p,
|
| 149 |
+
scaling=self.scaling,
|
| 150 |
+
**kwargs,
|
| 151 |
+
)
|
| 152 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 153 |
+
return attn_output, attn_weights
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
# Copied from transformers.models.bert.modeling_bert.BertCrossAttention with Bert->BertGeneration
|
| 157 |
+
class BertGenerationCrossAttention(nn.Module):
|
| 158 |
+
def __init__(self, config, is_causal=False, layer_idx=None):
|
| 159 |
+
super().__init__()
|
| 160 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 161 |
+
raise ValueError(
|
| 162 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 163 |
+
f"heads ({config.num_attention_heads})"
|
| 164 |
+
)
|
| 165 |
+
self.config = config
|
| 166 |
+
|
| 167 |
+
self.num_attention_heads = config.num_attention_heads
|
| 168 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 169 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 170 |
+
self.scaling = self.attention_head_size**-0.5
|
| 171 |
+
|
| 172 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 173 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 174 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 175 |
+
|
| 176 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 177 |
+
|
| 178 |
+
self.is_causal = is_causal
|
| 179 |
+
self.layer_idx = layer_idx
|
| 180 |
+
|
| 181 |
+
def forward(
|
| 182 |
+
self,
|
| 183 |
+
hidden_states: torch.Tensor,
|
| 184 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 185 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 186 |
+
past_key_values: EncoderDecoderCache | None = None,
|
| 187 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 188 |
+
) -> tuple[torch.Tensor]:
|
| 189 |
+
# determine input shapes
|
| 190 |
+
input_shape = hidden_states.shape[:-1]
|
| 191 |
+
|
| 192 |
+
hidden_shape = (*input_shape, -1, self.attention_head_size)
|
| 193 |
+
|
| 194 |
+
# get query proj
|
| 195 |
+
query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 196 |
+
|
| 197 |
+
is_updated = past_key_values.is_updated.get(self.layer_idx) if past_key_values is not None else False
|
| 198 |
+
if past_key_values is not None and is_updated:
|
| 199 |
+
# reuse k,v, cross_attentions
|
| 200 |
+
key_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].keys
|
| 201 |
+
value_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].values
|
| 202 |
+
else:
|
| 203 |
+
kv_shape = (*encoder_hidden_states.shape[:-1], -1, self.attention_head_size)
|
| 204 |
+
key_layer = self.key(encoder_hidden_states).view(kv_shape).transpose(1, 2)
|
| 205 |
+
value_layer = self.value(encoder_hidden_states).view(kv_shape).transpose(1, 2)
|
| 206 |
+
|
| 207 |
+
if past_key_values is not None:
|
| 208 |
+
# save all states to the cache
|
| 209 |
+
key_layer, value_layer = past_key_values.cross_attention_cache.update(
|
| 210 |
+
key_layer, value_layer, self.layer_idx
|
| 211 |
+
)
|
| 212 |
+
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
|
| 213 |
+
past_key_values.is_updated[self.layer_idx] = True
|
| 214 |
+
|
| 215 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 216 |
+
self.config._attn_implementation, eager_attention_forward
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
attn_output, attn_weights = attention_interface(
|
| 220 |
+
self,
|
| 221 |
+
query_layer,
|
| 222 |
+
key_layer,
|
| 223 |
+
value_layer,
|
| 224 |
+
attention_mask,
|
| 225 |
+
dropout=0.0 if not self.training else self.dropout.p,
|
| 226 |
+
scaling=self.scaling,
|
| 227 |
+
**kwargs,
|
| 228 |
+
)
|
| 229 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 230 |
+
return attn_output, attn_weights
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
# Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->BertGeneration,BERT->BERT_GENERATION
|
| 234 |
+
class BertGenerationAttention(nn.Module):
|
| 235 |
+
def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
|
| 236 |
+
super().__init__()
|
| 237 |
+
self.is_cross_attention = is_cross_attention
|
| 238 |
+
attention_class = BertGenerationCrossAttention if is_cross_attention else BertGenerationSelfAttention
|
| 239 |
+
self.self = attention_class(config, is_causal=is_causal, layer_idx=layer_idx)
|
| 240 |
+
self.output = BertGenerationSelfOutput(config)
|
| 241 |
+
|
| 242 |
+
def forward(
|
| 243 |
+
self,
|
| 244 |
+
hidden_states: torch.Tensor,
|
| 245 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 246 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 247 |
+
encoder_attention_mask: torch.FloatTensor | None = None,
|
| 248 |
+
past_key_values: Cache | None = None,
|
| 249 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 250 |
+
) -> tuple[torch.Tensor]:
|
| 251 |
+
attention_mask = attention_mask if not self.is_cross_attention else encoder_attention_mask
|
| 252 |
+
attention_output, attn_weights = self.self(
|
| 253 |
+
hidden_states,
|
| 254 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 255 |
+
attention_mask=attention_mask,
|
| 256 |
+
past_key_values=past_key_values,
|
| 257 |
+
**kwargs,
|
| 258 |
+
)
|
| 259 |
+
attention_output = self.output(attention_output, hidden_states)
|
| 260 |
+
return attention_output, attn_weights
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->BertGeneration
|
| 264 |
+
class BertGenerationIntermediate(nn.Module):
|
| 265 |
+
def __init__(self, config):
|
| 266 |
+
super().__init__()
|
| 267 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 268 |
+
if isinstance(config.hidden_act, str):
|
| 269 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 270 |
+
else:
|
| 271 |
+
self.intermediate_act_fn = config.hidden_act
|
| 272 |
+
|
| 273 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 274 |
+
hidden_states = self.dense(hidden_states)
|
| 275 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 276 |
+
return hidden_states
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->BertGeneration
|
| 280 |
+
class BertGenerationOutput(nn.Module):
|
| 281 |
+
def __init__(self, config):
|
| 282 |
+
super().__init__()
|
| 283 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 284 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 285 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 286 |
+
|
| 287 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 288 |
+
hidden_states = self.dense(hidden_states)
|
| 289 |
+
hidden_states = self.dropout(hidden_states)
|
| 290 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 291 |
+
return hidden_states
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
# Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->BertGeneration
|
| 295 |
+
class BertGenerationLayer(GradientCheckpointingLayer):
|
| 296 |
+
def __init__(self, config, layer_idx=None):
|
| 297 |
+
super().__init__()
|
| 298 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 299 |
+
self.seq_len_dim = 1
|
| 300 |
+
self.attention = BertGenerationAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx)
|
| 301 |
+
self.is_decoder = config.is_decoder
|
| 302 |
+
self.add_cross_attention = config.add_cross_attention
|
| 303 |
+
if self.add_cross_attention:
|
| 304 |
+
if not self.is_decoder:
|
| 305 |
+
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
|
| 306 |
+
self.crossattention = BertGenerationAttention(
|
| 307 |
+
config,
|
| 308 |
+
is_causal=False,
|
| 309 |
+
layer_idx=layer_idx,
|
| 310 |
+
is_cross_attention=True,
|
| 311 |
+
)
|
| 312 |
+
self.intermediate = BertGenerationIntermediate(config)
|
| 313 |
+
self.output = BertGenerationOutput(config)
|
| 314 |
+
|
| 315 |
+
def forward(
|
| 316 |
+
self,
|
| 317 |
+
hidden_states: torch.Tensor,
|
| 318 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 319 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 320 |
+
encoder_attention_mask: torch.FloatTensor | None = None,
|
| 321 |
+
past_key_values: Cache | None = None,
|
| 322 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 323 |
+
) -> torch.Tensor:
|
| 324 |
+
self_attention_output, _ = self.attention(
|
| 325 |
+
hidden_states,
|
| 326 |
+
attention_mask,
|
| 327 |
+
past_key_values=past_key_values,
|
| 328 |
+
**kwargs,
|
| 329 |
+
)
|
| 330 |
+
attention_output = self_attention_output
|
| 331 |
+
|
| 332 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
| 333 |
+
if not hasattr(self, "crossattention"):
|
| 334 |
+
raise ValueError(
|
| 335 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
| 336 |
+
" by setting `config.add_cross_attention=True`"
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
cross_attention_output, _ = self.crossattention(
|
| 340 |
+
self_attention_output,
|
| 341 |
+
None, # attention_mask
|
| 342 |
+
encoder_hidden_states,
|
| 343 |
+
encoder_attention_mask,
|
| 344 |
+
past_key_values=past_key_values,
|
| 345 |
+
**kwargs,
|
| 346 |
+
)
|
| 347 |
+
attention_output = cross_attention_output
|
| 348 |
+
|
| 349 |
+
layer_output = apply_chunking_to_forward(
|
| 350 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 351 |
+
)
|
| 352 |
+
return layer_output
|
| 353 |
+
|
| 354 |
+
def feed_forward_chunk(self, attention_output):
|
| 355 |
+
intermediate_output = self.intermediate(attention_output)
|
| 356 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 357 |
+
return layer_output
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
# Copied from transformers.models.bert.modeling_bert.BertEncoder
|
| 361 |
+
class BertEncoder(nn.Module):
|
| 362 |
+
def __init__(self, config):
|
| 363 |
+
super().__init__()
|
| 364 |
+
self.config = config
|
| 365 |
+
# Ignore copy
|
| 366 |
+
self.layer = nn.ModuleList([BertGenerationLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
|
| 367 |
+
|
| 368 |
+
def forward(
|
| 369 |
+
self,
|
| 370 |
+
hidden_states: torch.Tensor,
|
| 371 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 372 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 373 |
+
encoder_attention_mask: torch.FloatTensor | None = None,
|
| 374 |
+
past_key_values: Cache | None = None,
|
| 375 |
+
use_cache: bool | None = None,
|
| 376 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 377 |
+
) -> tuple[torch.Tensor] | BaseModelOutputWithPastAndCrossAttentions:
|
| 378 |
+
for i, layer_module in enumerate(self.layer):
|
| 379 |
+
hidden_states = layer_module(
|
| 380 |
+
hidden_states,
|
| 381 |
+
attention_mask,
|
| 382 |
+
encoder_hidden_states, # as a positional argument for gradient checkpointing
|
| 383 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 384 |
+
past_key_values=past_key_values,
|
| 385 |
+
**kwargs,
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 389 |
+
last_hidden_state=hidden_states,
|
| 390 |
+
past_key_values=past_key_values if use_cache else None,
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
class BertGenerationEmbeddings(nn.Module):
|
| 395 |
+
"""Construct the embeddings from word and position embeddings."""
|
| 396 |
+
|
| 397 |
+
def __init__(self, config):
|
| 398 |
+
super().__init__()
|
| 399 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 400 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 401 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 402 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 403 |
+
|
| 404 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 405 |
+
self.register_buffer(
|
| 406 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
def forward(self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0):
|
| 410 |
+
if input_ids is not None:
|
| 411 |
+
input_shape = input_ids.size()
|
| 412 |
+
else:
|
| 413 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 414 |
+
|
| 415 |
+
seq_length = input_shape[1]
|
| 416 |
+
|
| 417 |
+
if position_ids is None:
|
| 418 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
| 419 |
+
|
| 420 |
+
if inputs_embeds is None:
|
| 421 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 422 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 423 |
+
|
| 424 |
+
embeddings = inputs_embeds + position_embeddings
|
| 425 |
+
embeddings = self.LayerNorm(embeddings)
|
| 426 |
+
embeddings = self.dropout(embeddings)
|
| 427 |
+
return embeddings
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
@auto_docstring
|
| 431 |
+
class BertGenerationPreTrainedModel(PreTrainedModel):
|
| 432 |
+
config_class = BertGenerationConfig
|
| 433 |
+
base_model_prefix = "bert"
|
| 434 |
+
supports_gradient_checkpointing = True
|
| 435 |
+
_supports_flash_attn = True
|
| 436 |
+
_supports_sdpa = True
|
| 437 |
+
_supports_flex_attn = True
|
| 438 |
+
_supports_attention_backend = True
|
| 439 |
+
_can_record_outputs = {
|
| 440 |
+
"hidden_states": BertGenerationLayer,
|
| 441 |
+
"attentions": BertGenerationSelfAttention,
|
| 442 |
+
"cross_attentions": BertGenerationCrossAttention,
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
@torch.no_grad()
|
| 446 |
+
def _init_weights(self, module):
|
| 447 |
+
"""Initialize the weights"""
|
| 448 |
+
super()._init_weights(module)
|
| 449 |
+
if isinstance(module, BertGenerationOnlyLMHead):
|
| 450 |
+
init.zeros_(module.bias)
|
| 451 |
+
elif isinstance(module, BertGenerationEmbeddings):
|
| 452 |
+
init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
@auto_docstring(
|
| 456 |
+
custom_intro="""
|
| 457 |
+
The bare BertGeneration model transformer outputting raw hidden-states without any specific head on top.
|
| 458 |
+
"""
|
| 459 |
+
)
|
| 460 |
+
class BertGenerationEncoder(BertGenerationPreTrainedModel):
|
| 461 |
+
"""
|
| 462 |
+
|
| 463 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
| 464 |
+
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
|
| 465 |
+
all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
|
| 466 |
+
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
|
| 467 |
+
|
| 468 |
+
This model should be used when leveraging Bert or Roberta checkpoints for the [`EncoderDecoderModel`] class as
|
| 469 |
+
described in [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://huggingface.co/papers/1907.12461)
|
| 470 |
+
by Sascha Rothe, Shashi Narayan, and Aliaksei Severyn.
|
| 471 |
+
|
| 472 |
+
To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
|
| 473 |
+
to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
|
| 474 |
+
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
|
| 475 |
+
"""
|
| 476 |
+
|
| 477 |
+
def __init__(self, config):
|
| 478 |
+
super().__init__(config)
|
| 479 |
+
self.config = config
|
| 480 |
+
self.gradient_checkpointing = False
|
| 481 |
+
|
| 482 |
+
self.embeddings = BertGenerationEmbeddings(config)
|
| 483 |
+
self.encoder = BertEncoder(config)
|
| 484 |
+
|
| 485 |
+
# Initialize weights and apply final processing
|
| 486 |
+
self.post_init()
|
| 487 |
+
|
| 488 |
+
def get_input_embeddings(self):
|
| 489 |
+
return self.embeddings.word_embeddings
|
| 490 |
+
|
| 491 |
+
def set_input_embeddings(self, value):
|
| 492 |
+
self.embeddings.word_embeddings = value
|
| 493 |
+
|
| 494 |
+
@merge_with_config_defaults
|
| 495 |
+
@capture_outputs
|
| 496 |
+
@auto_docstring
|
| 497 |
+
def forward(
|
| 498 |
+
self,
|
| 499 |
+
input_ids: torch.Tensor | None = None,
|
| 500 |
+
attention_mask: torch.Tensor | None = None,
|
| 501 |
+
position_ids: torch.Tensor | None = None,
|
| 502 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 503 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 504 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 505 |
+
past_key_values: Cache | None = None,
|
| 506 |
+
use_cache: bool | None = None,
|
| 507 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 508 |
+
) -> tuple[torch.Tensor] | BaseModelOutputWithPastAndCrossAttentions:
|
| 509 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 510 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 511 |
+
|
| 512 |
+
if self.config.is_decoder:
|
| 513 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 514 |
+
else:
|
| 515 |
+
use_cache = False
|
| 516 |
+
|
| 517 |
+
if use_cache and past_key_values is None:
|
| 518 |
+
past_key_values = (
|
| 519 |
+
EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
|
| 520 |
+
if encoder_hidden_states is not None or self.config.is_encoder_decoder
|
| 521 |
+
else DynamicCache(config=self.config)
|
| 522 |
+
)
|
| 523 |
+
|
| 524 |
+
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 525 |
+
|
| 526 |
+
embedding_output = self.embeddings(
|
| 527 |
+
input_ids=input_ids,
|
| 528 |
+
position_ids=position_ids,
|
| 529 |
+
inputs_embeds=inputs_embeds,
|
| 530 |
+
past_key_values_length=past_key_values_length,
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
attention_mask, encoder_attention_mask = self._create_attention_masks(
|
| 534 |
+
attention_mask=attention_mask,
|
| 535 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 536 |
+
embedding_output=embedding_output,
|
| 537 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 538 |
+
past_key_values=past_key_values,
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
encoder_outputs = self.encoder(
|
| 542 |
+
embedding_output,
|
| 543 |
+
attention_mask=attention_mask,
|
| 544 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 545 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 546 |
+
past_key_values=past_key_values,
|
| 547 |
+
use_cache=use_cache,
|
| 548 |
+
position_ids=position_ids,
|
| 549 |
+
**kwargs,
|
| 550 |
+
)
|
| 551 |
+
sequence_output = encoder_outputs[0]
|
| 552 |
+
|
| 553 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 554 |
+
last_hidden_state=sequence_output,
|
| 555 |
+
past_key_values=encoder_outputs.past_key_values,
|
| 556 |
+
)
|
| 557 |
+
|
| 558 |
+
# Copied from transformers.models.bert.modeling_bert.BertModel._create_attention_masks
|
| 559 |
+
def _create_attention_masks(
|
| 560 |
+
self,
|
| 561 |
+
attention_mask,
|
| 562 |
+
encoder_attention_mask,
|
| 563 |
+
embedding_output,
|
| 564 |
+
encoder_hidden_states,
|
| 565 |
+
past_key_values,
|
| 566 |
+
):
|
| 567 |
+
if self.config.is_decoder:
|
| 568 |
+
attention_mask = create_causal_mask(
|
| 569 |
+
config=self.config,
|
| 570 |
+
inputs_embeds=embedding_output,
|
| 571 |
+
attention_mask=attention_mask,
|
| 572 |
+
past_key_values=past_key_values,
|
| 573 |
+
)
|
| 574 |
+
else:
|
| 575 |
+
attention_mask = create_bidirectional_mask(
|
| 576 |
+
config=self.config,
|
| 577 |
+
inputs_embeds=embedding_output,
|
| 578 |
+
attention_mask=attention_mask,
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
if encoder_attention_mask is not None:
|
| 582 |
+
encoder_attention_mask = create_bidirectional_mask(
|
| 583 |
+
config=self.config,
|
| 584 |
+
inputs_embeds=embedding_output,
|
| 585 |
+
attention_mask=encoder_attention_mask,
|
| 586 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 587 |
+
)
|
| 588 |
+
|
| 589 |
+
return attention_mask, encoder_attention_mask
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
class BertGenerationOnlyLMHead(nn.Module):
|
| 593 |
+
def __init__(self, config):
|
| 594 |
+
super().__init__()
|
| 595 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
|
| 596 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 597 |
+
|
| 598 |
+
def forward(self, hidden_states):
|
| 599 |
+
logits = self.decoder(hidden_states)
|
| 600 |
+
return logits
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
@auto_docstring(
|
| 604 |
+
custom_intro="""
|
| 605 |
+
BertGeneration Model with a `language modeling` head on top for CLM fine-tuning.
|
| 606 |
+
"""
|
| 607 |
+
)
|
| 608 |
+
class BertGenerationDecoder(BertGenerationPreTrainedModel, GenerationMixin):
|
| 609 |
+
_tied_weights_keys = {
|
| 610 |
+
"lm_head.decoder.weight": "bert.embeddings.word_embeddings.weight",
|
| 611 |
+
"lm_head.decoder.bias": "lm_head.bias",
|
| 612 |
+
}
|
| 613 |
+
|
| 614 |
+
def __init__(self, config):
|
| 615 |
+
super().__init__(config)
|
| 616 |
+
|
| 617 |
+
if not config.is_decoder:
|
| 618 |
+
logger.warning("If you want to use `BertGenerationDecoder` as a standalone, add `is_decoder=True.`")
|
| 619 |
+
|
| 620 |
+
self.bert = BertGenerationEncoder(config)
|
| 621 |
+
self.lm_head = BertGenerationOnlyLMHead(config)
|
| 622 |
+
|
| 623 |
+
# Initialize weights and apply final processing
|
| 624 |
+
self.post_init()
|
| 625 |
+
|
| 626 |
+
def get_output_embeddings(self):
|
| 627 |
+
return self.lm_head.decoder
|
| 628 |
+
|
| 629 |
+
def set_output_embeddings(self, new_embeddings):
|
| 630 |
+
self.lm_head.decoder = new_embeddings
|
| 631 |
+
self.lm_head.bias = new_embeddings.bias
|
| 632 |
+
|
| 633 |
+
@can_return_tuple
|
| 634 |
+
@auto_docstring
|
| 635 |
+
def forward(
|
| 636 |
+
self,
|
| 637 |
+
input_ids: torch.Tensor | None = None,
|
| 638 |
+
attention_mask: torch.Tensor | None = None,
|
| 639 |
+
position_ids: torch.Tensor | None = None,
|
| 640 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 641 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 642 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 643 |
+
labels: torch.Tensor | None = None,
|
| 644 |
+
past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
|
| 645 |
+
use_cache: bool | None = None,
|
| 646 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 647 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 648 |
+
) -> tuple | CausalLMOutputWithCrossAttentions:
|
| 649 |
+
r"""
|
| 650 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 651 |
+
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
|
| 652 |
+
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
|
| 653 |
+
ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 654 |
+
|
| 655 |
+
Example:
|
| 656 |
+
|
| 657 |
+
```python
|
| 658 |
+
>>> from transformers import AutoTokenizer, BertGenerationDecoder, BertGenerationConfig
|
| 659 |
+
>>> import torch
|
| 660 |
+
|
| 661 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder")
|
| 662 |
+
>>> config = BertGenerationConfig.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder")
|
| 663 |
+
>>> config.is_decoder = True
|
| 664 |
+
>>> model = BertGenerationDecoder.from_pretrained(
|
| 665 |
+
... "google/bert_for_seq_generation_L-24_bbc_encoder", config=config
|
| 666 |
+
... )
|
| 667 |
+
|
| 668 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_token_type_ids=False, return_tensors="pt")
|
| 669 |
+
>>> outputs = model(**inputs)
|
| 670 |
+
|
| 671 |
+
>>> prediction_logits = outputs.logits
|
| 672 |
+
```"""
|
| 673 |
+
if labels is not None:
|
| 674 |
+
use_cache = False
|
| 675 |
+
|
| 676 |
+
outputs: BaseModelOutputWithPastAndCrossAttentions = self.bert(
|
| 677 |
+
input_ids,
|
| 678 |
+
attention_mask=attention_mask,
|
| 679 |
+
position_ids=position_ids,
|
| 680 |
+
inputs_embeds=inputs_embeds,
|
| 681 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 682 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 683 |
+
past_key_values=past_key_values,
|
| 684 |
+
use_cache=use_cache,
|
| 685 |
+
return_dict=True,
|
| 686 |
+
**kwargs,
|
| 687 |
+
)
|
| 688 |
+
|
| 689 |
+
hidden_states = outputs.last_hidden_state
|
| 690 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 691 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 692 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 693 |
+
|
| 694 |
+
loss = None
|
| 695 |
+
if labels is not None:
|
| 696 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 697 |
+
|
| 698 |
+
return CausalLMOutputWithCrossAttentions(
|
| 699 |
+
loss=loss,
|
| 700 |
+
logits=logits,
|
| 701 |
+
past_key_values=outputs.past_key_values,
|
| 702 |
+
hidden_states=outputs.hidden_states,
|
| 703 |
+
attentions=outputs.attentions,
|
| 704 |
+
cross_attentions=outputs.cross_attentions,
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
__all__ = [
|
| 709 |
+
"BertGenerationDecoder",
|
| 710 |
+
"BertGenerationEncoder",
|
| 711 |
+
"BertGenerationPreTrainedModel",
|
| 712 |
+
]
|
lib/python3.11/site-packages/transformers/models/bert_generation/tokenization_bert_generation.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2020, NVIDIA CORPORATION. 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 |
+
"""Tokenization class for model BertGeneration."""
|
| 15 |
+
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
from ...tokenization_utils_sentencepiece import SentencePieceBackend
|
| 19 |
+
from ...utils import logging
|
| 20 |
+
from ...utils.import_utils import requires
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@requires(backends=("sentencepiece",))
|
| 29 |
+
class BertGenerationTokenizer(SentencePieceBackend):
|
| 30 |
+
"""
|
| 31 |
+
Construct a BertGeneration tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
|
| 32 |
+
|
| 33 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 34 |
+
this superclass for more information regarding those methods.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
vocab_file (`str`):
|
| 38 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
| 39 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 40 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 41 |
+
The begin of sequence token.
|
| 42 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 43 |
+
The end of sequence token.
|
| 44 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 45 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 46 |
+
token instead.
|
| 47 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 48 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 49 |
+
sep_token (`str`, *optional*, defaults to `"<::::>"`):
|
| 50 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 51 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 52 |
+
token of a sequence built with special tokens.
|
| 53 |
+
sp_model_kwargs (`dict`, *optional*):
|
| 54 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
| 55 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
| 56 |
+
to set:
|
| 57 |
+
|
| 58 |
+
- `enable_sampling`: Enable subword regularization.
|
| 59 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
| 60 |
+
|
| 61 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
| 62 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
| 63 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
| 64 |
+
using forward-filtering-and-backward-sampling algorithm.
|
| 65 |
+
|
| 66 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
| 67 |
+
BPE-dropout.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 71 |
+
prefix_tokens: list[int] = []
|
| 72 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 73 |
+
is_fast = False
|
| 74 |
+
|
| 75 |
+
def __init__(
|
| 76 |
+
self,
|
| 77 |
+
vocab_file,
|
| 78 |
+
bos_token="<s>",
|
| 79 |
+
eos_token="</s>",
|
| 80 |
+
unk_token="<unk>",
|
| 81 |
+
pad_token="<pad>",
|
| 82 |
+
sep_token="<::::>",
|
| 83 |
+
sp_model_kwargs: dict[str, Any] | None = None,
|
| 84 |
+
**kwargs,
|
| 85 |
+
) -> None:
|
| 86 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 87 |
+
|
| 88 |
+
# Call parent init (which will load sp_model)
|
| 89 |
+
super().__init__(
|
| 90 |
+
vocab_file=vocab_file,
|
| 91 |
+
bos_token=bos_token,
|
| 92 |
+
eos_token=eos_token,
|
| 93 |
+
unk_token=unk_token,
|
| 94 |
+
pad_token=pad_token,
|
| 95 |
+
sep_token=sep_token,
|
| 96 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 97 |
+
special_tokens_pattern="none",
|
| 98 |
+
**kwargs,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
__all__ = ["BertGenerationTokenizer"]
|
lib/python3.11/site-packages/transformers/models/bert_japanese/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 .tokenization_bert_japanese import *
|
| 22 |
+
else:
|
| 23 |
+
import sys
|
| 24 |
+
|
| 25 |
+
_file = globals()["__file__"]
|
| 26 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.11/site-packages/transformers/models/bert_japanese/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (754 Bytes). View file
|
|
|
lib/python3.11/site-packages/transformers/models/bert_japanese/__pycache__/tokenization_bert_japanese.cpython-311.pyc
ADDED
|
Binary file (41.6 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/bert_japanese/tokenization_bert_japanese.py
ADDED
|
@@ -0,0 +1,901 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 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 |
+
"""Tokenization classes."""
|
| 15 |
+
|
| 16 |
+
import collections
|
| 17 |
+
import copy
|
| 18 |
+
import os
|
| 19 |
+
import unicodedata
|
| 20 |
+
from typing import Any
|
| 21 |
+
|
| 22 |
+
from ...tokenization_python import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
|
| 23 |
+
from ...utils import is_sentencepiece_available, is_sudachi_projection_available, logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if is_sentencepiece_available():
|
| 27 |
+
import sentencepiece as spm
|
| 28 |
+
else:
|
| 29 |
+
spm = None
|
| 30 |
+
|
| 31 |
+
logger = logging.get_logger(__name__)
|
| 32 |
+
|
| 33 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "spm_file": "spiece.model"}
|
| 34 |
+
|
| 35 |
+
SPIECE_UNDERLINE = "▁"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def load_vocab(vocab_file):
|
| 39 |
+
"""Loads a vocabulary file into a dictionary."""
|
| 40 |
+
vocab = collections.OrderedDict()
|
| 41 |
+
with open(vocab_file, "r", encoding="utf-8") as reader:
|
| 42 |
+
tokens = reader.readlines()
|
| 43 |
+
for index, token in enumerate(tokens):
|
| 44 |
+
token = token.rstrip("\n")
|
| 45 |
+
vocab[token] = index
|
| 46 |
+
return vocab
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def whitespace_tokenize(text):
|
| 50 |
+
"""Runs basic whitespace cleaning and splitting on a piece of text."""
|
| 51 |
+
text = text.strip()
|
| 52 |
+
if not text:
|
| 53 |
+
return []
|
| 54 |
+
tokens = text.split()
|
| 55 |
+
return tokens
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class BertJapaneseTokenizer(PreTrainedTokenizer):
|
| 59 |
+
r"""
|
| 60 |
+
Construct a BERT tokenizer for Japanese text.
|
| 61 |
+
|
| 62 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer
|
| 63 |
+
to: this superclass for more information regarding those methods.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
vocab_file (`str`):
|
| 67 |
+
Path to a one-wordpiece-per-line vocabulary file.
|
| 68 |
+
spm_file (`str`, *optional*):
|
| 69 |
+
Path to [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm or .model
|
| 70 |
+
extension) that contains the vocabulary.
|
| 71 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 72 |
+
Whether to lower case the input. Only has an effect when do_basic_tokenize=True.
|
| 73 |
+
do_word_tokenize (`bool`, *optional*, defaults to `True`):
|
| 74 |
+
Whether to do word tokenization.
|
| 75 |
+
do_subword_tokenize (`bool`, *optional*, defaults to `True`):
|
| 76 |
+
Whether to do subword tokenization.
|
| 77 |
+
word_tokenizer_type (`str`, *optional*, defaults to `"basic"`):
|
| 78 |
+
Type of word tokenizer. Choose from ["basic", "mecab", "sudachi", "jumanpp"].
|
| 79 |
+
subword_tokenizer_type (`str`, *optional*, defaults to `"wordpiece"`):
|
| 80 |
+
Type of subword tokenizer. Choose from ["wordpiece", "character", "sentencepiece",].
|
| 81 |
+
mecab_kwargs (`dict`, *optional*):
|
| 82 |
+
Dictionary passed to the `MecabTokenizer` constructor.
|
| 83 |
+
sudachi_kwargs (`dict`, *optional*):
|
| 84 |
+
Dictionary passed to the `SudachiTokenizer` constructor.
|
| 85 |
+
jumanpp_kwargs (`dict`, *optional*):
|
| 86 |
+
Dictionary passed to the `JumanppTokenizer` constructor.
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 90 |
+
|
| 91 |
+
def __init__(
|
| 92 |
+
self,
|
| 93 |
+
vocab_file,
|
| 94 |
+
spm_file=None,
|
| 95 |
+
do_lower_case=False,
|
| 96 |
+
do_word_tokenize=True,
|
| 97 |
+
do_subword_tokenize=True,
|
| 98 |
+
word_tokenizer_type="basic",
|
| 99 |
+
subword_tokenizer_type="wordpiece",
|
| 100 |
+
never_split=None,
|
| 101 |
+
unk_token="[UNK]",
|
| 102 |
+
sep_token="[SEP]",
|
| 103 |
+
pad_token="[PAD]",
|
| 104 |
+
cls_token="[CLS]",
|
| 105 |
+
mask_token="[MASK]",
|
| 106 |
+
mecab_kwargs=None,
|
| 107 |
+
sudachi_kwargs=None,
|
| 108 |
+
jumanpp_kwargs=None,
|
| 109 |
+
**kwargs,
|
| 110 |
+
):
|
| 111 |
+
if subword_tokenizer_type == "sentencepiece":
|
| 112 |
+
if not os.path.isfile(spm_file):
|
| 113 |
+
raise ValueError(
|
| 114 |
+
f"Can't find a vocabulary file at path '{spm_file}'. To load the vocabulary from a Google"
|
| 115 |
+
" pretrained model use `tokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
|
| 116 |
+
)
|
| 117 |
+
self.spm_file = spm_file
|
| 118 |
+
else:
|
| 119 |
+
if not os.path.isfile(vocab_file):
|
| 120 |
+
raise ValueError(
|
| 121 |
+
f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google"
|
| 122 |
+
" pretrained model use `tokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
|
| 123 |
+
)
|
| 124 |
+
self.vocab = load_vocab(vocab_file)
|
| 125 |
+
self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
|
| 126 |
+
|
| 127 |
+
self.do_word_tokenize = do_word_tokenize
|
| 128 |
+
self.word_tokenizer_type = word_tokenizer_type
|
| 129 |
+
self.lower_case = do_lower_case
|
| 130 |
+
self.never_split = never_split
|
| 131 |
+
self.mecab_kwargs = copy.deepcopy(mecab_kwargs)
|
| 132 |
+
self.sudachi_kwargs = copy.deepcopy(sudachi_kwargs)
|
| 133 |
+
self.jumanpp_kwargs = copy.deepcopy(jumanpp_kwargs)
|
| 134 |
+
if do_word_tokenize:
|
| 135 |
+
if word_tokenizer_type == "basic":
|
| 136 |
+
self.word_tokenizer = BasicTokenizer(
|
| 137 |
+
do_lower_case=do_lower_case, never_split=never_split, tokenize_chinese_chars=False
|
| 138 |
+
)
|
| 139 |
+
elif word_tokenizer_type == "mecab":
|
| 140 |
+
self.word_tokenizer = MecabTokenizer(
|
| 141 |
+
do_lower_case=do_lower_case, never_split=never_split, **(mecab_kwargs or {})
|
| 142 |
+
)
|
| 143 |
+
elif word_tokenizer_type == "sudachi":
|
| 144 |
+
self.word_tokenizer = SudachiTokenizer(
|
| 145 |
+
do_lower_case=do_lower_case, never_split=never_split, **(sudachi_kwargs or {})
|
| 146 |
+
)
|
| 147 |
+
elif word_tokenizer_type == "jumanpp":
|
| 148 |
+
self.word_tokenizer = JumanppTokenizer(
|
| 149 |
+
do_lower_case=do_lower_case, never_split=never_split, **(jumanpp_kwargs or {})
|
| 150 |
+
)
|
| 151 |
+
else:
|
| 152 |
+
raise ValueError(f"Invalid word_tokenizer_type '{word_tokenizer_type}' is specified.")
|
| 153 |
+
|
| 154 |
+
self.do_subword_tokenize = do_subword_tokenize
|
| 155 |
+
self.subword_tokenizer_type = subword_tokenizer_type
|
| 156 |
+
if do_subword_tokenize:
|
| 157 |
+
if subword_tokenizer_type == "wordpiece":
|
| 158 |
+
self.subword_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
|
| 159 |
+
elif subword_tokenizer_type == "character":
|
| 160 |
+
self.subword_tokenizer = CharacterTokenizer(vocab=self.vocab, unk_token=str(unk_token))
|
| 161 |
+
elif subword_tokenizer_type == "sentencepiece":
|
| 162 |
+
self.subword_tokenizer = SentencepieceTokenizer(vocab=self.spm_file, unk_token=str(unk_token))
|
| 163 |
+
else:
|
| 164 |
+
raise ValueError(f"Invalid subword_tokenizer_type '{subword_tokenizer_type}' is specified.")
|
| 165 |
+
super().__init__(
|
| 166 |
+
spm_file=spm_file,
|
| 167 |
+
unk_token=unk_token,
|
| 168 |
+
sep_token=sep_token,
|
| 169 |
+
pad_token=pad_token,
|
| 170 |
+
cls_token=cls_token,
|
| 171 |
+
mask_token=mask_token,
|
| 172 |
+
do_lower_case=do_lower_case,
|
| 173 |
+
do_word_tokenize=do_word_tokenize,
|
| 174 |
+
do_subword_tokenize=do_subword_tokenize,
|
| 175 |
+
word_tokenizer_type=word_tokenizer_type,
|
| 176 |
+
subword_tokenizer_type=subword_tokenizer_type,
|
| 177 |
+
never_split=never_split,
|
| 178 |
+
mecab_kwargs=mecab_kwargs,
|
| 179 |
+
sudachi_kwargs=sudachi_kwargs,
|
| 180 |
+
jumanpp_kwargs=jumanpp_kwargs,
|
| 181 |
+
token_type_ids_pattern="bert_style",
|
| 182 |
+
token_type_ids_include_special_tokens=True,
|
| 183 |
+
special_tokens_pattern="cls_sep",
|
| 184 |
+
**kwargs,
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
@property
|
| 188 |
+
def do_lower_case(self):
|
| 189 |
+
return self.lower_case
|
| 190 |
+
|
| 191 |
+
def __getstate__(self):
|
| 192 |
+
state = dict(self.__dict__)
|
| 193 |
+
if self.word_tokenizer_type in ["mecab", "sudachi", "jumanpp"]:
|
| 194 |
+
del state["word_tokenizer"]
|
| 195 |
+
return state
|
| 196 |
+
|
| 197 |
+
def __setstate__(self, state):
|
| 198 |
+
self.__dict__ = state
|
| 199 |
+
if self.word_tokenizer_type == "mecab":
|
| 200 |
+
self.word_tokenizer = MecabTokenizer(
|
| 201 |
+
do_lower_case=self.do_lower_case, never_split=self.never_split, **(self.mecab_kwargs or {})
|
| 202 |
+
)
|
| 203 |
+
elif self.word_tokenizer_type == "sudachi":
|
| 204 |
+
self.word_tokenizer = SudachiTokenizer(
|
| 205 |
+
do_lower_case=self.do_lower_case, never_split=self.never_split, **(self.sudachi_kwargs or {})
|
| 206 |
+
)
|
| 207 |
+
elif self.word_tokenizer_type == "jumanpp":
|
| 208 |
+
self.word_tokenizer = JumanppTokenizer(
|
| 209 |
+
do_lower_case=self.do_lower_case, never_split=self.never_split, **(self.jumanpp_kwargs or {})
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
def _tokenize(self, text):
|
| 213 |
+
if self.do_word_tokenize:
|
| 214 |
+
tokens = self.word_tokenizer.tokenize(text, never_split=self.all_special_tokens)
|
| 215 |
+
else:
|
| 216 |
+
tokens = [text]
|
| 217 |
+
|
| 218 |
+
if self.do_subword_tokenize:
|
| 219 |
+
split_tokens = [sub_token for token in tokens for sub_token in self.subword_tokenizer.tokenize(token)]
|
| 220 |
+
else:
|
| 221 |
+
split_tokens = tokens
|
| 222 |
+
|
| 223 |
+
return split_tokens
|
| 224 |
+
|
| 225 |
+
@property
|
| 226 |
+
def vocab_size(self):
|
| 227 |
+
if self.subword_tokenizer_type == "sentencepiece":
|
| 228 |
+
return len(self.subword_tokenizer.sp_model)
|
| 229 |
+
return len(self.vocab)
|
| 230 |
+
|
| 231 |
+
def get_vocab(self):
|
| 232 |
+
if self.subword_tokenizer_type == "sentencepiece":
|
| 233 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
| 234 |
+
vocab.update(self.added_tokens_encoder)
|
| 235 |
+
return vocab
|
| 236 |
+
# base vocab
|
| 237 |
+
vocab = dict(self.vocab)
|
| 238 |
+
# + added_tokens_encoder (only for tokens not in base vocab)
|
| 239 |
+
for token, index in self.added_tokens_encoder.items():
|
| 240 |
+
if token not in self.vocab:
|
| 241 |
+
vocab[token] = index
|
| 242 |
+
return vocab
|
| 243 |
+
|
| 244 |
+
def _convert_token_to_id(self, token):
|
| 245 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 246 |
+
if self.subword_tokenizer_type == "sentencepiece":
|
| 247 |
+
return self.subword_tokenizer.sp_model.PieceToId(token)
|
| 248 |
+
return self.vocab.get(token, self.vocab.get(self.unk_token))
|
| 249 |
+
|
| 250 |
+
def _convert_id_to_token(self, index):
|
| 251 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 252 |
+
if self.subword_tokenizer_type == "sentencepiece":
|
| 253 |
+
return self.subword_tokenizer.sp_model.IdToPiece(index)
|
| 254 |
+
return self.ids_to_tokens.get(index, self.unk_token)
|
| 255 |
+
|
| 256 |
+
def convert_tokens_to_string(self, tokens):
|
| 257 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 258 |
+
if self.subword_tokenizer_type == "sentencepiece":
|
| 259 |
+
return self.subword_tokenizer.sp_model.decode(tokens)
|
| 260 |
+
out_string = " ".join(tokens).replace(" ##", "").strip()
|
| 261 |
+
return out_string
|
| 262 |
+
|
| 263 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
|
| 264 |
+
if os.path.isdir(save_directory):
|
| 265 |
+
if self.subword_tokenizer_type == "sentencepiece":
|
| 266 |
+
vocab_file = os.path.join(
|
| 267 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["spm_file"]
|
| 268 |
+
)
|
| 269 |
+
else:
|
| 270 |
+
vocab_file = os.path.join(
|
| 271 |
+
save_directory,
|
| 272 |
+
(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"],
|
| 273 |
+
)
|
| 274 |
+
else:
|
| 275 |
+
vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
|
| 276 |
+
|
| 277 |
+
if self.subword_tokenizer_type == "sentencepiece":
|
| 278 |
+
with open(vocab_file, "wb") as writer:
|
| 279 |
+
content_spiece_model = self.subword_tokenizer.sp_model.serialized_model_proto()
|
| 280 |
+
writer.write(content_spiece_model)
|
| 281 |
+
else:
|
| 282 |
+
with open(vocab_file, "w", encoding="utf-8") as writer:
|
| 283 |
+
index = 0
|
| 284 |
+
for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
|
| 285 |
+
if index != token_index:
|
| 286 |
+
logger.warning(
|
| 287 |
+
f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
|
| 288 |
+
" Please check that the vocabulary is not corrupted!"
|
| 289 |
+
)
|
| 290 |
+
index = token_index
|
| 291 |
+
writer.write(token + "\n")
|
| 292 |
+
index += 1
|
| 293 |
+
return (vocab_file,)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
class MecabTokenizer:
|
| 297 |
+
"""Runs basic tokenization with MeCab morphological parser."""
|
| 298 |
+
|
| 299 |
+
def __init__(
|
| 300 |
+
self,
|
| 301 |
+
do_lower_case=False,
|
| 302 |
+
never_split=None,
|
| 303 |
+
normalize_text=True,
|
| 304 |
+
mecab_dic: str | None = "unidic_lite",
|
| 305 |
+
mecab_option: str | None = None,
|
| 306 |
+
):
|
| 307 |
+
"""
|
| 308 |
+
Constructs a MecabTokenizer.
|
| 309 |
+
|
| 310 |
+
Args:
|
| 311 |
+
**do_lower_case**: (*optional*) boolean (default True)
|
| 312 |
+
Whether to lowercase the input.
|
| 313 |
+
**never_split**: (*optional*) list of str
|
| 314 |
+
Kept for backward compatibility purposes. Now implemented directly at the base class level (see
|
| 315 |
+
[`PreTrainedTokenizer.tokenize`]) List of tokens not to split.
|
| 316 |
+
**normalize_text**: (*optional*) boolean (default True)
|
| 317 |
+
Whether to apply unicode normalization to text before tokenization.
|
| 318 |
+
**mecab_dic**: (*optional*) string (default "ipadic")
|
| 319 |
+
Name of dictionary to be used for MeCab initialization. If you are using a system-installed dictionary,
|
| 320 |
+
set this option to `None` and modify *mecab_option*.
|
| 321 |
+
**mecab_option**: (*optional*) string
|
| 322 |
+
String passed to MeCab constructor.
|
| 323 |
+
"""
|
| 324 |
+
self.do_lower_case = do_lower_case
|
| 325 |
+
self.never_split = never_split if never_split is not None else []
|
| 326 |
+
self.normalize_text = normalize_text
|
| 327 |
+
|
| 328 |
+
try:
|
| 329 |
+
import fugashi
|
| 330 |
+
except ModuleNotFoundError as error:
|
| 331 |
+
raise error.__class__(
|
| 332 |
+
"You need to install fugashi to use MecabTokenizer. "
|
| 333 |
+
"See https://pypi.org/project/fugashi/ for installation."
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
mecab_option = mecab_option or ""
|
| 337 |
+
|
| 338 |
+
if mecab_dic is not None:
|
| 339 |
+
if mecab_dic == "ipadic":
|
| 340 |
+
try:
|
| 341 |
+
import ipadic
|
| 342 |
+
except ModuleNotFoundError as error:
|
| 343 |
+
raise error.__class__(
|
| 344 |
+
"The ipadic dictionary is not installed. "
|
| 345 |
+
"See https://github.com/polm/ipadic-py for installation."
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
dic_dir = ipadic.DICDIR
|
| 349 |
+
|
| 350 |
+
elif mecab_dic == "unidic_lite":
|
| 351 |
+
try:
|
| 352 |
+
import unidic_lite
|
| 353 |
+
except ModuleNotFoundError as error:
|
| 354 |
+
raise error.__class__(
|
| 355 |
+
"The unidic_lite dictionary is not installed. "
|
| 356 |
+
"See https://github.com/polm/unidic-lite for installation."
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
dic_dir = unidic_lite.DICDIR
|
| 360 |
+
|
| 361 |
+
elif mecab_dic == "unidic":
|
| 362 |
+
try:
|
| 363 |
+
import unidic
|
| 364 |
+
except ModuleNotFoundError as error:
|
| 365 |
+
raise error.__class__(
|
| 366 |
+
"The unidic dictionary is not installed. "
|
| 367 |
+
"See https://github.com/polm/unidic-py for installation."
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
dic_dir = unidic.DICDIR
|
| 371 |
+
if not os.path.isdir(dic_dir):
|
| 372 |
+
raise RuntimeError(
|
| 373 |
+
"The unidic dictionary itself is not found. "
|
| 374 |
+
"See https://github.com/polm/unidic-py for installation."
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
else:
|
| 378 |
+
raise ValueError("Invalid mecab_dic is specified.")
|
| 379 |
+
|
| 380 |
+
mecabrc = os.path.join(dic_dir, "mecabrc")
|
| 381 |
+
mecab_option = f'-d "{dic_dir}" -r "{mecabrc}" ' + mecab_option
|
| 382 |
+
|
| 383 |
+
self.mecab = fugashi.GenericTagger(mecab_option)
|
| 384 |
+
|
| 385 |
+
def tokenize(self, text, never_split=None, **kwargs):
|
| 386 |
+
"""Tokenizes a piece of text."""
|
| 387 |
+
if self.normalize_text:
|
| 388 |
+
text = unicodedata.normalize("NFKC", text)
|
| 389 |
+
|
| 390 |
+
never_split = self.never_split + (never_split if never_split is not None else [])
|
| 391 |
+
tokens = []
|
| 392 |
+
|
| 393 |
+
for word in self.mecab(text):
|
| 394 |
+
token = word.surface
|
| 395 |
+
|
| 396 |
+
if self.do_lower_case and token not in never_split:
|
| 397 |
+
token = token.lower()
|
| 398 |
+
|
| 399 |
+
tokens.append(token)
|
| 400 |
+
|
| 401 |
+
return tokens
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
class SudachiTokenizer:
|
| 405 |
+
"""Runs basic tokenization with Sudachi morphological parser."""
|
| 406 |
+
|
| 407 |
+
def __init__(
|
| 408 |
+
self,
|
| 409 |
+
do_lower_case=False,
|
| 410 |
+
never_split=None,
|
| 411 |
+
normalize_text=True,
|
| 412 |
+
trim_whitespace=False,
|
| 413 |
+
sudachi_split_mode="A",
|
| 414 |
+
sudachi_config_path=None,
|
| 415 |
+
sudachi_resource_dir=None,
|
| 416 |
+
sudachi_dict_type="core",
|
| 417 |
+
sudachi_projection=None,
|
| 418 |
+
):
|
| 419 |
+
"""
|
| 420 |
+
Constructs a SudachiTokenizer.
|
| 421 |
+
|
| 422 |
+
Args:
|
| 423 |
+
**do_lower_case**: (*optional*) boolean (default True)
|
| 424 |
+
Whether to lowercase the input.
|
| 425 |
+
**never_split**: (*optional*) list of str
|
| 426 |
+
Kept for backward compatibility purposes. Now implemented directly at the base class level (see
|
| 427 |
+
[`PreTrainedTokenizer.tokenize`]) List of tokens not to split.
|
| 428 |
+
**normalize_text**: (*optional*) boolean (default True)
|
| 429 |
+
Whether to apply unicode normalization to text before tokenization.
|
| 430 |
+
**trim_whitespace**: (*optional*) boolean (default False)
|
| 431 |
+
Whether to trim all whitespace, tab, newline from tokens.
|
| 432 |
+
**sudachi_split_mode**: (*optional*) string
|
| 433 |
+
Split mode of sudachi, choose from `["A", "B", "C"]`.
|
| 434 |
+
**sudachi_config_path**: (*optional*) string
|
| 435 |
+
**sudachi_resource_dir**: (*optional*) string
|
| 436 |
+
**sudachi_dict_type**: (*optional*) string
|
| 437 |
+
dict type of sudachi, choose from `["small", "core", "full"]`.
|
| 438 |
+
**sudachi_projection**: (*optional*) string
|
| 439 |
+
Word projection mode of sudachi, choose from `["surface", "normalized", "reading", "dictionary", "dictionary_and_surface", "normalized_and_surface", "normalized_nouns"]`.
|
| 440 |
+
"""
|
| 441 |
+
|
| 442 |
+
self.do_lower_case = do_lower_case
|
| 443 |
+
self.never_split = never_split if never_split is not None else []
|
| 444 |
+
self.normalize_text = normalize_text
|
| 445 |
+
self.trim_whitespace = trim_whitespace
|
| 446 |
+
|
| 447 |
+
try:
|
| 448 |
+
from sudachipy import dictionary, tokenizer
|
| 449 |
+
except ImportError:
|
| 450 |
+
raise ImportError(
|
| 451 |
+
"You need to install sudachipy to use SudachiTokenizer. "
|
| 452 |
+
"See https://github.com/WorksApplications/SudachiPy for installation."
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
if sudachi_split_mode == "A":
|
| 456 |
+
self.split_mode = tokenizer.Tokenizer.SplitMode.A
|
| 457 |
+
elif sudachi_split_mode == "B":
|
| 458 |
+
self.split_mode = tokenizer.Tokenizer.SplitMode.B
|
| 459 |
+
elif sudachi_split_mode == "C":
|
| 460 |
+
self.split_mode = tokenizer.Tokenizer.SplitMode.C
|
| 461 |
+
else:
|
| 462 |
+
raise ValueError("Invalid sudachi_split_mode is specified.")
|
| 463 |
+
|
| 464 |
+
self.projection = sudachi_projection
|
| 465 |
+
|
| 466 |
+
sudachi_dictionary = dictionary.Dictionary(
|
| 467 |
+
config_path=sudachi_config_path, resource_dir=sudachi_resource_dir, dict=sudachi_dict_type
|
| 468 |
+
)
|
| 469 |
+
if is_sudachi_projection_available():
|
| 470 |
+
self.sudachi = sudachi_dictionary.create(self.split_mode, projection=self.projection)
|
| 471 |
+
elif self.projection is not None:
|
| 472 |
+
raise ImportError("You need to install sudachipy>=0.6.8 to specify `projection` field in sudachi_kwargs.")
|
| 473 |
+
else:
|
| 474 |
+
self.sudachi = sudachi_dictionary.create(self.split_mode)
|
| 475 |
+
|
| 476 |
+
def tokenize(self, text, never_split=None, **kwargs):
|
| 477 |
+
"""Tokenizes a piece of text."""
|
| 478 |
+
if self.normalize_text:
|
| 479 |
+
text = unicodedata.normalize("NFKC", text)
|
| 480 |
+
|
| 481 |
+
never_split = self.never_split + (never_split if never_split is not None else [])
|
| 482 |
+
tokens = []
|
| 483 |
+
|
| 484 |
+
for word in self.sudachi.tokenize(text):
|
| 485 |
+
token = word.surface()
|
| 486 |
+
|
| 487 |
+
if self.do_lower_case and token not in never_split:
|
| 488 |
+
token = token.lower()
|
| 489 |
+
|
| 490 |
+
if self.trim_whitespace:
|
| 491 |
+
if token.strip() == "":
|
| 492 |
+
continue
|
| 493 |
+
else:
|
| 494 |
+
token = token.strip()
|
| 495 |
+
|
| 496 |
+
tokens.append(token)
|
| 497 |
+
|
| 498 |
+
return tokens
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
class JumanppTokenizer:
|
| 502 |
+
"""Runs basic tokenization with jumanpp morphological parser."""
|
| 503 |
+
|
| 504 |
+
def __init__(
|
| 505 |
+
self,
|
| 506 |
+
do_lower_case=False,
|
| 507 |
+
never_split=None,
|
| 508 |
+
normalize_text=True,
|
| 509 |
+
trim_whitespace=False,
|
| 510 |
+
):
|
| 511 |
+
"""
|
| 512 |
+
Constructs a JumanppTokenizer.
|
| 513 |
+
|
| 514 |
+
Args:
|
| 515 |
+
**do_lower_case**: (*optional*) boolean (default True)
|
| 516 |
+
Whether to lowercase the input.
|
| 517 |
+
**never_split**: (*optional*) list of str
|
| 518 |
+
Kept for backward compatibility purposes. Now implemented directly at the base class level (see
|
| 519 |
+
[`PreTrainedTokenizer.tokenize`]) List of tokens not to split.
|
| 520 |
+
**normalize_text**: (*optional*) boolean (default True)
|
| 521 |
+
Whether to apply unicode normalization to text before tokenization.
|
| 522 |
+
**trim_whitespace**: (*optional*) boolean (default False)
|
| 523 |
+
Whether to trim all whitespace, tab, newline from tokens.
|
| 524 |
+
"""
|
| 525 |
+
|
| 526 |
+
self.do_lower_case = do_lower_case
|
| 527 |
+
self.never_split = never_split if never_split is not None else []
|
| 528 |
+
self.normalize_text = normalize_text
|
| 529 |
+
self.trim_whitespace = trim_whitespace
|
| 530 |
+
|
| 531 |
+
try:
|
| 532 |
+
import rhoknp
|
| 533 |
+
except ImportError:
|
| 534 |
+
raise ImportError(
|
| 535 |
+
"You need to install rhoknp to use JumanppTokenizer. "
|
| 536 |
+
"See https://github.com/ku-nlp/rhoknp for installation."
|
| 537 |
+
)
|
| 538 |
+
|
| 539 |
+
self.juman = rhoknp.Jumanpp()
|
| 540 |
+
|
| 541 |
+
def tokenize(self, text, never_split=None, **kwargs):
|
| 542 |
+
"""Tokenizes a piece of text."""
|
| 543 |
+
if self.normalize_text:
|
| 544 |
+
text = unicodedata.normalize("NFKC", text)
|
| 545 |
+
|
| 546 |
+
text = text.strip()
|
| 547 |
+
|
| 548 |
+
never_split = self.never_split + (never_split if never_split is not None else [])
|
| 549 |
+
tokens = []
|
| 550 |
+
|
| 551 |
+
for mrph in self.juman.apply_to_sentence(text).morphemes:
|
| 552 |
+
token = mrph.text
|
| 553 |
+
|
| 554 |
+
if self.do_lower_case and token not in never_split:
|
| 555 |
+
token = token.lower()
|
| 556 |
+
|
| 557 |
+
if self.trim_whitespace:
|
| 558 |
+
if token.strip() == "":
|
| 559 |
+
continue
|
| 560 |
+
else:
|
| 561 |
+
token = token.strip()
|
| 562 |
+
|
| 563 |
+
tokens.append(token)
|
| 564 |
+
|
| 565 |
+
return tokens
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
class CharacterTokenizer:
|
| 569 |
+
"""Runs Character tokenization."""
|
| 570 |
+
|
| 571 |
+
def __init__(self, vocab, unk_token, normalize_text=True):
|
| 572 |
+
"""
|
| 573 |
+
Constructs a CharacterTokenizer.
|
| 574 |
+
|
| 575 |
+
Args:
|
| 576 |
+
**vocab**:
|
| 577 |
+
Vocabulary object.
|
| 578 |
+
**unk_token**: str
|
| 579 |
+
A special symbol for out-of-vocabulary token.
|
| 580 |
+
**normalize_text**: (`optional`) boolean (default True)
|
| 581 |
+
Whether to apply unicode normalization to text before tokenization.
|
| 582 |
+
"""
|
| 583 |
+
self.vocab = vocab
|
| 584 |
+
self.unk_token = unk_token
|
| 585 |
+
self.normalize_text = normalize_text
|
| 586 |
+
|
| 587 |
+
def tokenize(self, text):
|
| 588 |
+
"""
|
| 589 |
+
Tokenizes a piece of text into characters.
|
| 590 |
+
|
| 591 |
+
For example, `input = "apple""` will return as output `["a", "p", "p", "l", "e"]`.
|
| 592 |
+
|
| 593 |
+
Args:
|
| 594 |
+
text: A single token or whitespace separated tokens.
|
| 595 |
+
This should have already been passed through *BasicTokenizer*.
|
| 596 |
+
|
| 597 |
+
Returns:
|
| 598 |
+
A list of characters.
|
| 599 |
+
"""
|
| 600 |
+
if self.normalize_text:
|
| 601 |
+
text = unicodedata.normalize("NFKC", text)
|
| 602 |
+
|
| 603 |
+
output_tokens = []
|
| 604 |
+
for char in text:
|
| 605 |
+
if char not in self.vocab:
|
| 606 |
+
output_tokens.append(self.unk_token)
|
| 607 |
+
continue
|
| 608 |
+
|
| 609 |
+
output_tokens.append(char)
|
| 610 |
+
|
| 611 |
+
return output_tokens
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
class BasicTokenizer:
|
| 615 |
+
"""
|
| 616 |
+
Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
|
| 617 |
+
|
| 618 |
+
Args:
|
| 619 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 620 |
+
Whether or not to lowercase the input when tokenizing.
|
| 621 |
+
never_split (`Iterable`, *optional*):
|
| 622 |
+
Collection of tokens which will never be split during tokenization. Only has an effect when
|
| 623 |
+
`do_basic_tokenize=True`
|
| 624 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 625 |
+
Whether or not to tokenize Chinese characters.
|
| 626 |
+
|
| 627 |
+
This should likely be deactivated for Japanese (see this
|
| 628 |
+
[issue](https://github.com/huggingface/transformers/issues/328)).
|
| 629 |
+
strip_accents (`bool`, *optional*):
|
| 630 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 631 |
+
value for `lowercase` (as in the original BERT).
|
| 632 |
+
do_split_on_punc (`bool`, *optional*, defaults to `True`):
|
| 633 |
+
In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
|
| 634 |
+
the full context of the words, such as contractions.
|
| 635 |
+
"""
|
| 636 |
+
|
| 637 |
+
def __init__(
|
| 638 |
+
self,
|
| 639 |
+
do_lower_case=True,
|
| 640 |
+
never_split=None,
|
| 641 |
+
tokenize_chinese_chars=True,
|
| 642 |
+
strip_accents=None,
|
| 643 |
+
do_split_on_punc=True,
|
| 644 |
+
):
|
| 645 |
+
if never_split is None:
|
| 646 |
+
never_split = []
|
| 647 |
+
self.do_lower_case = do_lower_case
|
| 648 |
+
self.never_split = set(never_split)
|
| 649 |
+
self.tokenize_chinese_chars = tokenize_chinese_chars
|
| 650 |
+
self.strip_accents = strip_accents
|
| 651 |
+
self.do_split_on_punc = do_split_on_punc
|
| 652 |
+
|
| 653 |
+
def tokenize(self, text, never_split=None):
|
| 654 |
+
"""
|
| 655 |
+
Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
|
| 656 |
+
|
| 657 |
+
Args:
|
| 658 |
+
never_split (`List[str]`, *optional*)
|
| 659 |
+
Kept for backward compatibility purposes. Now implemented directly at the base class level (see
|
| 660 |
+
[`PreTrainedTokenizer.tokenize`]) List of token not to split.
|
| 661 |
+
"""
|
| 662 |
+
# union() returns a new set by concatenating the two sets.
|
| 663 |
+
never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
|
| 664 |
+
text = self._clean_text(text)
|
| 665 |
+
|
| 666 |
+
# This was added on November 1st, 2018 for the multilingual and Chinese
|
| 667 |
+
# models. This is also applied to the English models now, but it doesn't
|
| 668 |
+
# matter since the English models were not trained on any Chinese data
|
| 669 |
+
# and generally don't have any Chinese data in them (there are Chinese
|
| 670 |
+
# characters in the vocabulary because Wikipedia does have some Chinese
|
| 671 |
+
# words in the English Wikipedia.).
|
| 672 |
+
if self.tokenize_chinese_chars:
|
| 673 |
+
text = self._tokenize_chinese_chars(text)
|
| 674 |
+
# prevents treating the same character with different unicode codepoints as different characters
|
| 675 |
+
unicode_normalized_text = unicodedata.normalize("NFC", text)
|
| 676 |
+
orig_tokens = whitespace_tokenize(unicode_normalized_text)
|
| 677 |
+
split_tokens = []
|
| 678 |
+
for token in orig_tokens:
|
| 679 |
+
if token not in never_split:
|
| 680 |
+
if self.do_lower_case:
|
| 681 |
+
token = token.lower()
|
| 682 |
+
if self.strip_accents is not False:
|
| 683 |
+
token = self._run_strip_accents(token)
|
| 684 |
+
elif self.strip_accents:
|
| 685 |
+
token = self._run_strip_accents(token)
|
| 686 |
+
split_tokens.extend(self._run_split_on_punc(token, never_split))
|
| 687 |
+
|
| 688 |
+
output_tokens = whitespace_tokenize(" ".join(split_tokens))
|
| 689 |
+
return output_tokens
|
| 690 |
+
|
| 691 |
+
def _run_strip_accents(self, text):
|
| 692 |
+
"""Strips accents from a piece of text."""
|
| 693 |
+
text = unicodedata.normalize("NFD", text)
|
| 694 |
+
output = []
|
| 695 |
+
for char in text:
|
| 696 |
+
cat = unicodedata.category(char)
|
| 697 |
+
if cat == "Mn":
|
| 698 |
+
continue
|
| 699 |
+
output.append(char)
|
| 700 |
+
return "".join(output)
|
| 701 |
+
|
| 702 |
+
def _run_split_on_punc(self, text, never_split=None):
|
| 703 |
+
"""Splits punctuation on a piece of text."""
|
| 704 |
+
if not self.do_split_on_punc or (never_split is not None and text in never_split):
|
| 705 |
+
return [text]
|
| 706 |
+
chars = list(text)
|
| 707 |
+
i = 0
|
| 708 |
+
start_new_word = True
|
| 709 |
+
output = []
|
| 710 |
+
while i < len(chars):
|
| 711 |
+
char = chars[i]
|
| 712 |
+
if _is_punctuation(char):
|
| 713 |
+
output.append([char])
|
| 714 |
+
start_new_word = True
|
| 715 |
+
else:
|
| 716 |
+
if start_new_word:
|
| 717 |
+
output.append([])
|
| 718 |
+
start_new_word = False
|
| 719 |
+
output[-1].append(char)
|
| 720 |
+
i += 1
|
| 721 |
+
|
| 722 |
+
return ["".join(x) for x in output]
|
| 723 |
+
|
| 724 |
+
def _tokenize_chinese_chars(self, text):
|
| 725 |
+
"""Adds whitespace around any CJK character."""
|
| 726 |
+
output = []
|
| 727 |
+
for char in text:
|
| 728 |
+
cp = ord(char)
|
| 729 |
+
if self._is_chinese_char(cp):
|
| 730 |
+
output.append(" ")
|
| 731 |
+
output.append(char)
|
| 732 |
+
output.append(" ")
|
| 733 |
+
else:
|
| 734 |
+
output.append(char)
|
| 735 |
+
return "".join(output)
|
| 736 |
+
|
| 737 |
+
def _is_chinese_char(self, cp):
|
| 738 |
+
"""Checks whether CP is the codepoint of a CJK character."""
|
| 739 |
+
# This defines a "chinese character" as anything in the CJK Unicode block:
|
| 740 |
+
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
|
| 741 |
+
#
|
| 742 |
+
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
|
| 743 |
+
# despite its name. The modern Korean Hangul alphabet is a different block,
|
| 744 |
+
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
|
| 745 |
+
# space-separated words, so they are not treated specially and handled
|
| 746 |
+
# like the all of the other languages.
|
| 747 |
+
if (
|
| 748 |
+
(cp >= 0x4E00 and cp <= 0x9FFF)
|
| 749 |
+
or (cp >= 0x3400 and cp <= 0x4DBF)
|
| 750 |
+
or (cp >= 0x20000 and cp <= 0x2A6DF)
|
| 751 |
+
or (cp >= 0x2A700 and cp <= 0x2B73F)
|
| 752 |
+
or (cp >= 0x2B740 and cp <= 0x2B81F)
|
| 753 |
+
or (cp >= 0x2B820 and cp <= 0x2CEAF)
|
| 754 |
+
or (cp >= 0xF900 and cp <= 0xFAFF)
|
| 755 |
+
or (cp >= 0x2F800 and cp <= 0x2FA1F)
|
| 756 |
+
):
|
| 757 |
+
return True
|
| 758 |
+
|
| 759 |
+
return False
|
| 760 |
+
|
| 761 |
+
def _clean_text(self, text):
|
| 762 |
+
"""Performs invalid character removal and whitespace cleanup on text."""
|
| 763 |
+
output = []
|
| 764 |
+
for char in text:
|
| 765 |
+
cp = ord(char)
|
| 766 |
+
if cp == 0 or cp == 0xFFFD or _is_control(char):
|
| 767 |
+
continue
|
| 768 |
+
if _is_whitespace(char):
|
| 769 |
+
output.append(" ")
|
| 770 |
+
else:
|
| 771 |
+
output.append(char)
|
| 772 |
+
return "".join(output)
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
class WordpieceTokenizer:
|
| 776 |
+
"""Runs WordPiece tokenization."""
|
| 777 |
+
|
| 778 |
+
def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
|
| 779 |
+
self.vocab = vocab
|
| 780 |
+
self.unk_token = unk_token
|
| 781 |
+
self.max_input_chars_per_word = max_input_chars_per_word
|
| 782 |
+
|
| 783 |
+
def tokenize(self, text):
|
| 784 |
+
"""
|
| 785 |
+
Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
|
| 786 |
+
tokenization using the given vocabulary.
|
| 787 |
+
|
| 788 |
+
For example, `input = "unaffable"` will return as output `["un", "##aff", "##able"]`.
|
| 789 |
+
|
| 790 |
+
Args:
|
| 791 |
+
text: A single token or whitespace separated tokens. This should have
|
| 792 |
+
already been passed through *BasicTokenizer*.
|
| 793 |
+
|
| 794 |
+
Returns:
|
| 795 |
+
A list of wordpiece tokens.
|
| 796 |
+
"""
|
| 797 |
+
|
| 798 |
+
output_tokens = []
|
| 799 |
+
for token in whitespace_tokenize(text):
|
| 800 |
+
chars = list(token)
|
| 801 |
+
if len(chars) > self.max_input_chars_per_word:
|
| 802 |
+
output_tokens.append(self.unk_token)
|
| 803 |
+
continue
|
| 804 |
+
|
| 805 |
+
is_bad = False
|
| 806 |
+
start = 0
|
| 807 |
+
sub_tokens = []
|
| 808 |
+
while start < len(chars):
|
| 809 |
+
end = len(chars)
|
| 810 |
+
cur_substr = None
|
| 811 |
+
while start < end:
|
| 812 |
+
substr = "".join(chars[start:end])
|
| 813 |
+
if start > 0:
|
| 814 |
+
substr = "##" + substr
|
| 815 |
+
if substr in self.vocab:
|
| 816 |
+
cur_substr = substr
|
| 817 |
+
break
|
| 818 |
+
end -= 1
|
| 819 |
+
if cur_substr is None:
|
| 820 |
+
is_bad = True
|
| 821 |
+
break
|
| 822 |
+
sub_tokens.append(cur_substr)
|
| 823 |
+
start = end
|
| 824 |
+
|
| 825 |
+
if is_bad:
|
| 826 |
+
output_tokens.append(self.unk_token)
|
| 827 |
+
else:
|
| 828 |
+
output_tokens.extend(sub_tokens)
|
| 829 |
+
return output_tokens
|
| 830 |
+
|
| 831 |
+
|
| 832 |
+
class SentencepieceTokenizer:
|
| 833 |
+
"""
|
| 834 |
+
Runs sentencepiece tokenization. Based on transformers.models.albert.tokenization_albert.AlbertTokenizer.
|
| 835 |
+
"""
|
| 836 |
+
|
| 837 |
+
def __init__(
|
| 838 |
+
self,
|
| 839 |
+
vocab,
|
| 840 |
+
unk_token,
|
| 841 |
+
do_lower_case=False,
|
| 842 |
+
remove_space=True,
|
| 843 |
+
keep_accents=True,
|
| 844 |
+
sp_model_kwargs: dict[str, Any] | None = None,
|
| 845 |
+
):
|
| 846 |
+
self.vocab = vocab
|
| 847 |
+
self.unk_token = unk_token
|
| 848 |
+
self.do_lower_case = do_lower_case
|
| 849 |
+
self.remove_space = remove_space
|
| 850 |
+
self.keep_accents = keep_accents
|
| 851 |
+
|
| 852 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 853 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 854 |
+
self.sp_model.Load(self.vocab)
|
| 855 |
+
|
| 856 |
+
def preprocess_text(self, inputs):
|
| 857 |
+
if self.remove_space:
|
| 858 |
+
outputs = " ".join(inputs.strip().split())
|
| 859 |
+
else:
|
| 860 |
+
outputs = inputs
|
| 861 |
+
outputs = outputs.replace("``", '"').replace("''", '"')
|
| 862 |
+
|
| 863 |
+
if not self.keep_accents:
|
| 864 |
+
outputs = unicodedata.normalize("NFKD", outputs)
|
| 865 |
+
outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
|
| 866 |
+
if self.do_lower_case:
|
| 867 |
+
outputs = outputs.lower()
|
| 868 |
+
|
| 869 |
+
return outputs
|
| 870 |
+
|
| 871 |
+
def tokenize(self, text):
|
| 872 |
+
"""
|
| 873 |
+
Tokenizes text by sentencepiece. Based on [SentencePiece](https://github.com/google/sentencepiece).
|
| 874 |
+
Tokenization needs the given vocabulary.
|
| 875 |
+
|
| 876 |
+
Args:
|
| 877 |
+
text: A string needs to be tokenized.
|
| 878 |
+
|
| 879 |
+
Returns:
|
| 880 |
+
A list of sentencepiece tokens.
|
| 881 |
+
"""
|
| 882 |
+
text = self.preprocess_text(text)
|
| 883 |
+
pieces = self.sp_model.encode(text, out_type=str)
|
| 884 |
+
new_pieces = []
|
| 885 |
+
for piece in pieces:
|
| 886 |
+
if len(piece) > 1 and piece[-1] == "," and piece[-2].isdigit():
|
| 887 |
+
cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
|
| 888 |
+
if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
|
| 889 |
+
if len(cur_pieces[0]) == 1:
|
| 890 |
+
cur_pieces = cur_pieces[1:]
|
| 891 |
+
else:
|
| 892 |
+
cur_pieces[0] = cur_pieces[0][1:]
|
| 893 |
+
cur_pieces.append(piece[-1])
|
| 894 |
+
new_pieces.extend(cur_pieces)
|
| 895 |
+
else:
|
| 896 |
+
new_pieces.append(piece)
|
| 897 |
+
|
| 898 |
+
return new_pieces
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
__all__ = ["BertJapaneseTokenizer", "CharacterTokenizer", "MecabTokenizer"]
|
lib/python3.11/site-packages/transformers/models/bertweet/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 .tokenization_bertweet import *
|
| 22 |
+
else:
|
| 23 |
+
import sys
|
| 24 |
+
|
| 25 |
+
_file = globals()["__file__"]
|
| 26 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.11/site-packages/transformers/models/bertweet/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (744 Bytes). View file
|
|
|
lib/python3.11/site-packages/transformers/models/bertweet/__pycache__/tokenization_bertweet.cpython-311.pyc
ADDED
|
Binary file (28.1 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/bertweet/tokenization_bertweet.py
ADDED
|
@@ -0,0 +1,698 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2020, VinAI Research and the HuggingFace Inc. team.
|
| 2 |
+
# Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization classes for BERTweet"""
|
| 16 |
+
|
| 17 |
+
import html
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
|
| 21 |
+
import regex
|
| 22 |
+
|
| 23 |
+
from ...tokenization_python import PreTrainedTokenizer
|
| 24 |
+
from ...utils import logging
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
VOCAB_FILES_NAMES = {
|
| 30 |
+
"vocab_file": "vocab.txt",
|
| 31 |
+
"merges_file": "bpe.codes",
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def get_pairs(word):
|
| 36 |
+
"""
|
| 37 |
+
Return set of symbol pairs in a word.
|
| 38 |
+
|
| 39 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
| 40 |
+
"""
|
| 41 |
+
pairs = set()
|
| 42 |
+
prev_char = word[0]
|
| 43 |
+
for char in word[1:]:
|
| 44 |
+
pairs.add((prev_char, char))
|
| 45 |
+
prev_char = char
|
| 46 |
+
|
| 47 |
+
pairs = set(pairs)
|
| 48 |
+
return pairs
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class BertweetTokenizer(PreTrainedTokenizer):
|
| 52 |
+
"""
|
| 53 |
+
Constructs a BERTweet tokenizer, using Byte-Pair-Encoding.
|
| 54 |
+
|
| 55 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 56 |
+
this superclass for more information regarding those methods.
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
vocab_file (`str`):
|
| 60 |
+
Path to the vocabulary file.
|
| 61 |
+
merges_file (`str`):
|
| 62 |
+
Path to the merges file.
|
| 63 |
+
normalization (`bool`, *optional*, defaults to `False`):
|
| 64 |
+
Whether or not to apply a normalization preprocess.
|
| 65 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 66 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 67 |
+
|
| 68 |
+
<Tip>
|
| 69 |
+
|
| 70 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 71 |
+
sequence. The token used is the `cls_token`.
|
| 72 |
+
|
| 73 |
+
</Tip>
|
| 74 |
+
|
| 75 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 76 |
+
The end of sequence token.
|
| 77 |
+
|
| 78 |
+
<Tip>
|
| 79 |
+
|
| 80 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 81 |
+
The token used is the `sep_token`.
|
| 82 |
+
|
| 83 |
+
</Tip>
|
| 84 |
+
|
| 85 |
+
sep_token (`str`, *optional*, defaults to `"</s>"`):
|
| 86 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 87 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 88 |
+
token of a sequence built with special tokens.
|
| 89 |
+
cls_token (`str`, *optional*, defaults to `"<s>"`):
|
| 90 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 91 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 92 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 93 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 94 |
+
token instead.
|
| 95 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 96 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 97 |
+
mask_token (`str`, *optional*, defaults to `"<mask>"`):
|
| 98 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 99 |
+
modeling. This is the token which the model will try to predict.
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 103 |
+
|
| 104 |
+
def __init__(
|
| 105 |
+
self,
|
| 106 |
+
vocab_file,
|
| 107 |
+
merges_file,
|
| 108 |
+
normalization=False,
|
| 109 |
+
bos_token="<s>",
|
| 110 |
+
eos_token="</s>",
|
| 111 |
+
sep_token="</s>",
|
| 112 |
+
cls_token="<s>",
|
| 113 |
+
unk_token="<unk>",
|
| 114 |
+
pad_token="<pad>",
|
| 115 |
+
mask_token="<mask>",
|
| 116 |
+
**kwargs,
|
| 117 |
+
):
|
| 118 |
+
try:
|
| 119 |
+
from emoji import demojize
|
| 120 |
+
|
| 121 |
+
self.demojizer = demojize
|
| 122 |
+
except ImportError:
|
| 123 |
+
logger.warning(
|
| 124 |
+
"emoji is not installed, thus not converting emoticons or emojis into text. Install emoji: pip3"
|
| 125 |
+
" install emoji==0.6.0"
|
| 126 |
+
)
|
| 127 |
+
self.demojizer = None
|
| 128 |
+
|
| 129 |
+
self.vocab_file = vocab_file
|
| 130 |
+
self.merges_file = merges_file
|
| 131 |
+
|
| 132 |
+
self.encoder = {}
|
| 133 |
+
self.encoder[str(bos_token)] = 0
|
| 134 |
+
self.encoder[str(pad_token)] = 1
|
| 135 |
+
self.encoder[str(eos_token)] = 2
|
| 136 |
+
self.encoder[str(unk_token)] = 3
|
| 137 |
+
|
| 138 |
+
self.add_from_file(vocab_file)
|
| 139 |
+
|
| 140 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 141 |
+
|
| 142 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
| 143 |
+
merges = merges_handle.read().split("\n")[:-1]
|
| 144 |
+
merges = [tuple(merge.split()[:-1]) for merge in merges]
|
| 145 |
+
self.bpe_ranks = dict(zip(merges, range(len(merges))))
|
| 146 |
+
self.cache = {}
|
| 147 |
+
|
| 148 |
+
self.normalization = normalization
|
| 149 |
+
self.tweetPreprocessor = TweetTokenizer()
|
| 150 |
+
self.special_puncts = {"’": "'", "…": "..."}
|
| 151 |
+
|
| 152 |
+
super().__init__(
|
| 153 |
+
normalization=normalization,
|
| 154 |
+
bos_token=bos_token,
|
| 155 |
+
eos_token=eos_token,
|
| 156 |
+
sep_token=sep_token,
|
| 157 |
+
cls_token=cls_token,
|
| 158 |
+
unk_token=unk_token,
|
| 159 |
+
pad_token=pad_token,
|
| 160 |
+
mask_token=mask_token,
|
| 161 |
+
# Configure patterns instead of overriding methods
|
| 162 |
+
token_type_ids_pattern="all_zeros", # BERTweet doesn't use token type IDs
|
| 163 |
+
token_type_ids_include_special_tokens=True,
|
| 164 |
+
special_tokens_pattern="cls_double_sep", # <s> X </s></s> Y </s>
|
| 165 |
+
**kwargs,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
@property
|
| 169 |
+
def vocab_size(self):
|
| 170 |
+
return len(self.encoder)
|
| 171 |
+
|
| 172 |
+
def get_vocab(self):
|
| 173 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
| 174 |
+
|
| 175 |
+
def bpe(self, token):
|
| 176 |
+
if token in self.cache:
|
| 177 |
+
return self.cache[token]
|
| 178 |
+
word = tuple(token)
|
| 179 |
+
word = tuple(list(word[:-1]) + [word[-1] + "</w>"])
|
| 180 |
+
pairs = get_pairs(word)
|
| 181 |
+
|
| 182 |
+
if not pairs:
|
| 183 |
+
return token
|
| 184 |
+
|
| 185 |
+
while True:
|
| 186 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
| 187 |
+
if bigram not in self.bpe_ranks:
|
| 188 |
+
break
|
| 189 |
+
first, second = bigram
|
| 190 |
+
new_word = []
|
| 191 |
+
i = 0
|
| 192 |
+
while i < len(word):
|
| 193 |
+
try:
|
| 194 |
+
j = word.index(first, i)
|
| 195 |
+
except ValueError:
|
| 196 |
+
new_word.extend(word[i:])
|
| 197 |
+
break
|
| 198 |
+
else:
|
| 199 |
+
new_word.extend(word[i:j])
|
| 200 |
+
i = j
|
| 201 |
+
|
| 202 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
| 203 |
+
new_word.append(first + second)
|
| 204 |
+
i += 2
|
| 205 |
+
else:
|
| 206 |
+
new_word.append(word[i])
|
| 207 |
+
i += 1
|
| 208 |
+
new_word = tuple(new_word)
|
| 209 |
+
word = new_word
|
| 210 |
+
if len(word) == 1:
|
| 211 |
+
break
|
| 212 |
+
else:
|
| 213 |
+
pairs = get_pairs(word)
|
| 214 |
+
word = "@@ ".join(word)
|
| 215 |
+
word = word[:-4]
|
| 216 |
+
self.cache[token] = word
|
| 217 |
+
return word
|
| 218 |
+
|
| 219 |
+
def _tokenize(self, text):
|
| 220 |
+
"""Tokenize a string."""
|
| 221 |
+
if self.normalization: # Perform Tweet normalization before performing BPE
|
| 222 |
+
text = self.normalizeTweet(text)
|
| 223 |
+
|
| 224 |
+
split_tokens = []
|
| 225 |
+
words = re.findall(r"\S+\n?", text)
|
| 226 |
+
for token in words:
|
| 227 |
+
split_tokens.extend(list(self.bpe(token).split(" ")))
|
| 228 |
+
return split_tokens
|
| 229 |
+
|
| 230 |
+
def normalizeTweet(self, tweet):
|
| 231 |
+
"""
|
| 232 |
+
Normalize a raw Tweet
|
| 233 |
+
"""
|
| 234 |
+
for punct in self.special_puncts:
|
| 235 |
+
tweet = tweet.replace(punct, self.special_puncts[punct])
|
| 236 |
+
|
| 237 |
+
tokens = self.tweetPreprocessor.tokenize(tweet)
|
| 238 |
+
normTweet = " ".join([self.normalizeToken(token) for token in tokens])
|
| 239 |
+
|
| 240 |
+
normTweet = (
|
| 241 |
+
normTweet.replace("cannot ", "can not ")
|
| 242 |
+
.replace("n't ", " n't ")
|
| 243 |
+
.replace("n 't ", " n't ")
|
| 244 |
+
.replace("ca n't", "can't")
|
| 245 |
+
.replace("ai n't", "ain't")
|
| 246 |
+
)
|
| 247 |
+
normTweet = (
|
| 248 |
+
normTweet.replace("'m ", " 'm ")
|
| 249 |
+
.replace("'re ", " 're ")
|
| 250 |
+
.replace("'s ", " 's ")
|
| 251 |
+
.replace("'ll ", " 'll ")
|
| 252 |
+
.replace("'d ", " 'd ")
|
| 253 |
+
.replace("'ve ", " 've ")
|
| 254 |
+
)
|
| 255 |
+
normTweet = (
|
| 256 |
+
normTweet.replace(" p . m .", " p.m.")
|
| 257 |
+
.replace(" p . m ", " p.m ")
|
| 258 |
+
.replace(" a . m .", " a.m.")
|
| 259 |
+
.replace(" a . m ", " a.m ")
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
return " ".join(normTweet.split())
|
| 263 |
+
|
| 264 |
+
def normalizeToken(self, token):
|
| 265 |
+
"""
|
| 266 |
+
Normalize tokens in a Tweet
|
| 267 |
+
"""
|
| 268 |
+
lowercased_token = token.lower()
|
| 269 |
+
if token.startswith("@"):
|
| 270 |
+
return "@USER"
|
| 271 |
+
elif lowercased_token.startswith("http") or lowercased_token.startswith("www"):
|
| 272 |
+
return "HTTPURL"
|
| 273 |
+
elif len(token) == 1:
|
| 274 |
+
if token in self.special_puncts:
|
| 275 |
+
return self.special_puncts[token]
|
| 276 |
+
if self.demojizer is not None:
|
| 277 |
+
return self.demojizer(token)
|
| 278 |
+
else:
|
| 279 |
+
return token
|
| 280 |
+
else:
|
| 281 |
+
return token
|
| 282 |
+
|
| 283 |
+
def _convert_token_to_id(self, token):
|
| 284 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 285 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
| 286 |
+
|
| 287 |
+
def _convert_id_to_token(self, index):
|
| 288 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 289 |
+
return self.decoder.get(index, self.unk_token)
|
| 290 |
+
|
| 291 |
+
def convert_tokens_to_string(self, tokens):
|
| 292 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 293 |
+
out_string = " ".join(tokens).replace("@@ ", "").strip()
|
| 294 |
+
return out_string
|
| 295 |
+
|
| 296 |
+
# def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
|
| 297 |
+
# filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
|
| 298 |
+
# tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
|
| 299 |
+
# tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
|
| 300 |
+
# return ''.join(tokens_generated_so_far)
|
| 301 |
+
|
| 302 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str, ...]:
|
| 303 |
+
"""
|
| 304 |
+
Save the vocabulary and merges files to a directory.
|
| 305 |
+
"""
|
| 306 |
+
if not os.path.isdir(save_directory):
|
| 307 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 308 |
+
return ()
|
| 309 |
+
|
| 310 |
+
vocab_files_names = getattr(self, "vocab_files_names", {})
|
| 311 |
+
prefix = f"{filename_prefix}-" if filename_prefix else ""
|
| 312 |
+
|
| 313 |
+
# Save vocabulary in the format expected by add_from_file: <token> <id>
|
| 314 |
+
# Exclude special tokens (IDs 0-3) as they are added in __init__ before add_from_file
|
| 315 |
+
vocab_file = os.path.join(save_directory, prefix + vocab_files_names.get("vocab_file", "vocab.txt"))
|
| 316 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
| 317 |
+
for token, token_id in sorted(self.encoder.items(), key=lambda kv: kv[1]):
|
| 318 |
+
# Only save tokens with ID >= 4, as IDs 0-3 are reserved for special tokens
|
| 319 |
+
if token_id >= 4:
|
| 320 |
+
f.write(f"{token} {token_id}\n")
|
| 321 |
+
|
| 322 |
+
# Save BPE merges
|
| 323 |
+
merge_file = os.path.join(save_directory, prefix + vocab_files_names.get("merges_file", "bpe.codes"))
|
| 324 |
+
with open(merge_file, "w", encoding="utf-8") as writer:
|
| 325 |
+
writer.writelines(
|
| 326 |
+
" ".join(bpe_tokens) + "\n"
|
| 327 |
+
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1])
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
return (vocab_file, merge_file)
|
| 331 |
+
|
| 332 |
+
def add_from_file(self, f):
|
| 333 |
+
"""
|
| 334 |
+
Loads a pre-existing dictionary from a text file and adds its symbols to this instance.
|
| 335 |
+
"""
|
| 336 |
+
if isinstance(f, str):
|
| 337 |
+
try:
|
| 338 |
+
with open(f, "r", encoding="utf-8") as fd:
|
| 339 |
+
self.add_from_file(fd)
|
| 340 |
+
except FileNotFoundError as fnfe:
|
| 341 |
+
raise fnfe
|
| 342 |
+
except UnicodeError:
|
| 343 |
+
raise Exception(f"Incorrect encoding detected in {f}, please rebuild the dataset")
|
| 344 |
+
return
|
| 345 |
+
|
| 346 |
+
lines = f.readlines()
|
| 347 |
+
for lineTmp in lines:
|
| 348 |
+
line = lineTmp.strip()
|
| 349 |
+
idx = line.rfind(" ")
|
| 350 |
+
if idx == -1:
|
| 351 |
+
raise ValueError("Incorrect dictionary format, expected '<token> <cnt>'")
|
| 352 |
+
word = line[:idx]
|
| 353 |
+
self.encoder[word] = len(self.encoder)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
# Natural Language Toolkit: Twitter Tokenizer
|
| 357 |
+
#
|
| 358 |
+
# Copyright (C) 2001-2020 NLTK Project
|
| 359 |
+
# Author: Christopher Potts <cgpotts@stanford.edu>
|
| 360 |
+
# Ewan Klein <ewan@inf.ed.ac.uk> (modifications)
|
| 361 |
+
# Pierpaolo Pantone <> (modifications)
|
| 362 |
+
# URL: http://nltk.org/
|
| 363 |
+
# For license information, see LICENSE.TXT
|
| 364 |
+
#
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
"""
|
| 368 |
+
Twitter-aware tokenizer, designed to be flexible and easy to adapt to new domains and tasks. The basic logic is this:
|
| 369 |
+
|
| 370 |
+
1. The tuple regex_strings defines a list of regular expression strings.
|
| 371 |
+
|
| 372 |
+
2. The regex_strings strings are put, in order, into a compiled regular expression object called word_re.
|
| 373 |
+
|
| 374 |
+
3. The tokenization is done by word_re.findall(s), where s is the user-supplied string, inside the tokenize() method of
|
| 375 |
+
the class Tokenizer.
|
| 376 |
+
|
| 377 |
+
4. When instantiating Tokenizer objects, there is a single option: preserve_case. By default, it is set to True. If it
|
| 378 |
+
is set to False, then the tokenizer will lowercase everything except for emoticons.
|
| 379 |
+
|
| 380 |
+
"""
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
######################################################################
|
| 384 |
+
#
|
| 385 |
+
# import regex # https://github.com/nltk/nltk/issues/2409
|
| 386 |
+
# import html
|
| 387 |
+
#
|
| 388 |
+
######################################################################
|
| 389 |
+
# The following strings are components in the regular expression
|
| 390 |
+
# that is used for tokenizing. It's important that phone_number
|
| 391 |
+
# appears first in the final regex (since it can contain whitespace).
|
| 392 |
+
# It also could matter that tags comes after emoticons, due to the
|
| 393 |
+
# possibility of having text like
|
| 394 |
+
#
|
| 395 |
+
# <:| and some text >:)
|
| 396 |
+
#
|
| 397 |
+
# Most importantly, the final element should always be last, since it
|
| 398 |
+
# does a last ditch whitespace-based tokenization of whatever is left.
|
| 399 |
+
|
| 400 |
+
# ToDo: Update with http://en.wikipedia.org/wiki/List_of_emoticons ?
|
| 401 |
+
|
| 402 |
+
# This particular element is used in a couple ways, so we define it
|
| 403 |
+
# with a name:
|
| 404 |
+
# docstyle-ignore
|
| 405 |
+
EMOTICONS = r"""
|
| 406 |
+
(?:
|
| 407 |
+
[<>]?
|
| 408 |
+
[:;=8] # eyes
|
| 409 |
+
[\-o\*\']? # optional nose
|
| 410 |
+
[\)\]\(\[dDpP/\:\}\{@\|\\] # mouth
|
| 411 |
+
|
|
| 412 |
+
[\)\]\(\[dDpP/\:\}\{@\|\\] # mouth
|
| 413 |
+
[\-o\*\']? # optional nose
|
| 414 |
+
[:;=8] # eyes
|
| 415 |
+
[<>]?
|
| 416 |
+
|
|
| 417 |
+
<3 # heart
|
| 418 |
+
)"""
|
| 419 |
+
|
| 420 |
+
# URL pattern due to John Gruber, modified by Tom Winzig. See
|
| 421 |
+
# https://gist.github.com/winzig/8894715
|
| 422 |
+
# docstyle-ignore
|
| 423 |
+
URLS = r""" # Capture 1: entire matched URL
|
| 424 |
+
(?:
|
| 425 |
+
https?: # URL protocol and colon
|
| 426 |
+
(?:
|
| 427 |
+
/{1,3} # 1-3 slashes
|
| 428 |
+
| # or
|
| 429 |
+
[a-z0-9%] # Single letter or digit or '%'
|
| 430 |
+
# (Trying not to match e.g. "URI::Escape")
|
| 431 |
+
)
|
| 432 |
+
| # or
|
| 433 |
+
# looks like domain name followed by a slash:
|
| 434 |
+
[a-z0-9.\-]+[.]
|
| 435 |
+
(?:[a-z]{2,13})
|
| 436 |
+
/
|
| 437 |
+
)
|
| 438 |
+
(?: # One or more:
|
| 439 |
+
[^\s()<>{}\[\]]+ # Run of non-space, non-()<>{}[]
|
| 440 |
+
| # or
|
| 441 |
+
\([^\s()]*?\([^\s()]+\)[^\s()]*?\) # balanced parens, one level deep: (...(...)...)
|
| 442 |
+
|
|
| 443 |
+
\([^\s]+?\) # balanced parens, non-recursive: (...)
|
| 444 |
+
)+
|
| 445 |
+
(?: # End with:
|
| 446 |
+
\([^\s()]*?\([^\s()]+\)[^\s()]*?\) # balanced parens, one level deep: (...(...)...)
|
| 447 |
+
|
|
| 448 |
+
\([^\s]+?\) # balanced parens, non-recursive: (...)
|
| 449 |
+
| # or
|
| 450 |
+
[^\s`!()\[\]{};:'".,<>?«»“”‘’] # not a space or one of these punct chars
|
| 451 |
+
)
|
| 452 |
+
| # OR, the following to match naked domains:
|
| 453 |
+
(?:
|
| 454 |
+
(?<!@) # not preceded by a @, avoid matching foo@_gmail.com_
|
| 455 |
+
[a-z0-9]+
|
| 456 |
+
(?:[.\-][a-z0-9]+)*
|
| 457 |
+
[.]
|
| 458 |
+
(?:[a-z]{2,13})
|
| 459 |
+
\b
|
| 460 |
+
/?
|
| 461 |
+
(?!@) # not succeeded by a @,
|
| 462 |
+
# avoid matching "foo.na" in "foo.na@example.com"
|
| 463 |
+
)
|
| 464 |
+
"""
|
| 465 |
+
|
| 466 |
+
# docstyle-ignore
|
| 467 |
+
# The components of the tokenizer:
|
| 468 |
+
REGEXPS = (
|
| 469 |
+
URLS,
|
| 470 |
+
# Phone numbers:
|
| 471 |
+
r"""
|
| 472 |
+
(?:
|
| 473 |
+
(?: # (international)
|
| 474 |
+
\+?[01]
|
| 475 |
+
[ *\-.\)]*
|
| 476 |
+
)?
|
| 477 |
+
(?: # (area code)
|
| 478 |
+
[\(]?
|
| 479 |
+
\d{3}
|
| 480 |
+
[ *\-.\)]*
|
| 481 |
+
)?
|
| 482 |
+
\d{3} # exchange
|
| 483 |
+
[ *\-.\)]*
|
| 484 |
+
\d{4} # base
|
| 485 |
+
)""",
|
| 486 |
+
# ASCII Emoticons
|
| 487 |
+
EMOTICONS,
|
| 488 |
+
# HTML tags:
|
| 489 |
+
r"""<[^>\s]+>""",
|
| 490 |
+
# ASCII Arrows
|
| 491 |
+
r"""[\-]+>|<[\-]+""",
|
| 492 |
+
# Twitter username:
|
| 493 |
+
r"""(?:@[\w_]+)""",
|
| 494 |
+
# Twitter hashtags:
|
| 495 |
+
r"""(?:\#+[\w_]+[\w\'_\-]*[\w_]+)""",
|
| 496 |
+
# email addresses
|
| 497 |
+
r"""[\w.+-]+@[\w-]+\.(?:[\w-]\.?)+[\w-]""",
|
| 498 |
+
# docstyle-ignore
|
| 499 |
+
# Remaining word types:
|
| 500 |
+
r"""
|
| 501 |
+
(?:[^\W\d_](?:[^\W\d_]|['\-_])+[^\W\d_]) # Words with apostrophes or dashes.
|
| 502 |
+
|
|
| 503 |
+
(?:[+\-]?\d+[,/.:-]\d+[+\-]?) # Numbers, including fractions, decimals.
|
| 504 |
+
|
|
| 505 |
+
(?:[\w_]+) # Words without apostrophes or dashes.
|
| 506 |
+
|
|
| 507 |
+
(?:\.(?:\s*\.){1,}) # Ellipsis dots.
|
| 508 |
+
|
|
| 509 |
+
(?:\S) # Everything else that isn't whitespace.
|
| 510 |
+
""",
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
######################################################################
|
| 514 |
+
# This is the core tokenizing regex:
|
| 515 |
+
|
| 516 |
+
WORD_RE = regex.compile(r"""(%s)""" % "|".join(REGEXPS), regex.VERBOSE | regex.I | regex.UNICODE)
|
| 517 |
+
|
| 518 |
+
# WORD_RE performs poorly on these patterns:
|
| 519 |
+
HANG_RE = regex.compile(r"([^a-zA-Z0-9])\1{3,}")
|
| 520 |
+
|
| 521 |
+
# The emoticon string gets its own regex so that we can preserve case for
|
| 522 |
+
# them as needed:
|
| 523 |
+
EMOTICON_RE = regex.compile(EMOTICONS, regex.VERBOSE | regex.I | regex.UNICODE)
|
| 524 |
+
|
| 525 |
+
# These are for regularizing HTML entities to Unicode:
|
| 526 |
+
ENT_RE = regex.compile(r"&(#?(x?))([^&;\s]+);")
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
######################################################################
|
| 530 |
+
# Functions for converting html entities
|
| 531 |
+
######################################################################
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def _str_to_unicode(text, encoding=None, errors="strict"):
|
| 535 |
+
if encoding is None:
|
| 536 |
+
encoding = "utf-8"
|
| 537 |
+
if isinstance(text, bytes):
|
| 538 |
+
return text.decode(encoding, errors)
|
| 539 |
+
return text
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def _replace_html_entities(text, keep=(), remove_illegal=True, encoding="utf-8"):
|
| 543 |
+
"""
|
| 544 |
+
Remove entities from text by converting them to their corresponding unicode character.
|
| 545 |
+
|
| 546 |
+
Args:
|
| 547 |
+
text:
|
| 548 |
+
A unicode string or a byte string encoded in the given *encoding* (which defaults to 'utf-8').
|
| 549 |
+
keep (list):
|
| 550 |
+
List of entity names which should not be replaced. This supports both numeric entities (`&#nnnn;` and
|
| 551 |
+
`&#hhhh;`) and named entities (such as ` ` or `>`).
|
| 552 |
+
remove_illegal (bool):
|
| 553 |
+
If `True`, entities that can't be converted are removed. Otherwise, entities that can't be converted are
|
| 554 |
+
kept "as is".
|
| 555 |
+
Returns: A unicode string with the entities removed.
|
| 556 |
+
|
| 557 |
+
See https://github.com/scrapy/w3lib/blob/master/w3lib/html.py
|
| 558 |
+
|
| 559 |
+
Examples:
|
| 560 |
+
|
| 561 |
+
```python
|
| 562 |
+
>>> from nltk.tokenize.casual import _replace_html_entities
|
| 563 |
+
|
| 564 |
+
>>> _replace_html_entities(b"Price: £100")
|
| 565 |
+
'Price: \\xa3100'
|
| 566 |
+
|
| 567 |
+
>>> print(_replace_html_entities(b"Price: £100"))
|
| 568 |
+
Price: £100
|
| 569 |
+
```"""
|
| 570 |
+
|
| 571 |
+
def _convert_entity(match):
|
| 572 |
+
entity_body = match.group(3)
|
| 573 |
+
if match.group(1):
|
| 574 |
+
try:
|
| 575 |
+
if match.group(2):
|
| 576 |
+
number = int(entity_body, 16)
|
| 577 |
+
else:
|
| 578 |
+
number = int(entity_body, 10)
|
| 579 |
+
# Numeric character references in the 80-9F range are typically
|
| 580 |
+
# interpreted by browsers as representing the characters mapped
|
| 581 |
+
# to bytes 80-9F in the Windows-1252 encoding. For more info
|
| 582 |
+
# see: https://en.wikipedia.org/wiki/ISO/IEC_8859-1#Similar_character_sets
|
| 583 |
+
if 0x80 <= number <= 0x9F:
|
| 584 |
+
return bytes((number,)).decode("cp1252")
|
| 585 |
+
except ValueError:
|
| 586 |
+
number = None
|
| 587 |
+
else:
|
| 588 |
+
if entity_body in keep:
|
| 589 |
+
return match.group(0)
|
| 590 |
+
else:
|
| 591 |
+
number = html.entities.name2codepoint.get(entity_body)
|
| 592 |
+
if number is not None:
|
| 593 |
+
try:
|
| 594 |
+
return chr(number)
|
| 595 |
+
except (ValueError, OverflowError):
|
| 596 |
+
pass
|
| 597 |
+
|
| 598 |
+
return "" if remove_illegal else match.group(0)
|
| 599 |
+
|
| 600 |
+
return ENT_RE.sub(_convert_entity, _str_to_unicode(text, encoding))
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
######################################################################
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
class TweetTokenizer:
|
| 607 |
+
r"""
|
| 608 |
+
Examples:
|
| 609 |
+
|
| 610 |
+
```python
|
| 611 |
+
>>> # Tokenizer for tweets.
|
| 612 |
+
>>> from nltk.tokenize import TweetTokenizer
|
| 613 |
+
|
| 614 |
+
>>> tknzr = TweetTokenizer()
|
| 615 |
+
>>> s0 = "This is a cooool #dummysmiley: :-) :-P <3 and some arrows < > -> <--"
|
| 616 |
+
>>> tknzr.tokenize(s0)
|
| 617 |
+
['This', 'is', 'a', 'cooool', '#dummysmiley', ':', ':-)', ':-P', '<3', 'and', 'some', 'arrows', '<', '>', '->', '<--']
|
| 618 |
+
|
| 619 |
+
>>> # Examples using *strip_handles* and *reduce_len parameters*:
|
| 620 |
+
>>> tknzr = TweetTokenizer(strip_handles=True, reduce_len=True)
|
| 621 |
+
>>> s1 = "@remy: This is waaaaayyyy too much for you!!!!!!"
|
| 622 |
+
>>> tknzr.tokenize(s1)
|
| 623 |
+
[':', 'This', 'is', 'waaayyy', 'too', 'much', 'for', 'you', '!', '!', '!']
|
| 624 |
+
```"""
|
| 625 |
+
|
| 626 |
+
def __init__(self, preserve_case=True, reduce_len=False, strip_handles=False):
|
| 627 |
+
self.preserve_case = preserve_case
|
| 628 |
+
self.reduce_len = reduce_len
|
| 629 |
+
self.strip_handles = strip_handles
|
| 630 |
+
|
| 631 |
+
def tokenize(self, text):
|
| 632 |
+
"""
|
| 633 |
+
Args:
|
| 634 |
+
text: str
|
| 635 |
+
|
| 636 |
+
Returns: list(str) A tokenized list of strings; concatenating this list returns the original string if
|
| 637 |
+
`preserve_case=False`
|
| 638 |
+
"""
|
| 639 |
+
# Fix HTML character entities:
|
| 640 |
+
text = _replace_html_entities(text)
|
| 641 |
+
# Remove username handles
|
| 642 |
+
if self.strip_handles:
|
| 643 |
+
text = remove_handles(text)
|
| 644 |
+
# Normalize word lengthening
|
| 645 |
+
if self.reduce_len:
|
| 646 |
+
text = reduce_lengthening(text)
|
| 647 |
+
# Shorten problematic sequences of characters
|
| 648 |
+
safe_text = HANG_RE.sub(r"\1\1\1", text)
|
| 649 |
+
# Tokenize:
|
| 650 |
+
words = WORD_RE.findall(safe_text)
|
| 651 |
+
# Possibly alter the case, but avoid changing emoticons like :D into :d:
|
| 652 |
+
if not self.preserve_case:
|
| 653 |
+
words = [x if EMOTICON_RE.search(x) else x.lower() for x in words]
|
| 654 |
+
return words
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
######################################################################
|
| 658 |
+
# Normalization Functions
|
| 659 |
+
######################################################################
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
def reduce_lengthening(text):
|
| 663 |
+
"""
|
| 664 |
+
Replace repeated character sequences of length 3 or greater with sequences of length 3.
|
| 665 |
+
"""
|
| 666 |
+
pattern = regex.compile(r"(.)\1{2,}")
|
| 667 |
+
return pattern.sub(r"\1\1\1", text)
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
def remove_handles(text):
|
| 671 |
+
"""
|
| 672 |
+
Remove Twitter username handles from text.
|
| 673 |
+
"""
|
| 674 |
+
pattern = regex.compile(
|
| 675 |
+
r"(?<![A-Za-z0-9_!@#\$%&*])@(([A-Za-z0-9_]){20}(?!@))|(?<![A-Za-z0-9_!@#\$%&*])@(([A-Za-z0-9_]){1,19})(?![A-Za-z0-9_]*@)"
|
| 676 |
+
)
|
| 677 |
+
# Substitute handles with ' ' to ensure that text on either side of removed handles are tokenized correctly
|
| 678 |
+
return pattern.sub(" ", text)
|
| 679 |
+
|
| 680 |
+
|
| 681 |
+
######################################################################
|
| 682 |
+
# Tokenization Function
|
| 683 |
+
######################################################################
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
def casual_tokenize(text, preserve_case=True, reduce_len=False, strip_handles=False):
|
| 687 |
+
"""
|
| 688 |
+
Convenience function for wrapping the tokenizer.
|
| 689 |
+
"""
|
| 690 |
+
return TweetTokenizer(preserve_case=preserve_case, reduce_len=reduce_len, strip_handles=strip_handles).tokenize(
|
| 691 |
+
text
|
| 692 |
+
)
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
###############################################################################
|
| 696 |
+
|
| 697 |
+
|
| 698 |
+
__all__ = ["BertweetTokenizer"]
|
lib/python3.11/site-packages/transformers/models/big_bird/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_big_bird import *
|
| 22 |
+
from .modeling_big_bird import *
|
| 23 |
+
from .tokenization_big_bird import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.11/site-packages/transformers/models/big_bird/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (827 Bytes). View file
|
|
|
lib/python3.11/site-packages/transformers/models/big_bird/__pycache__/configuration_big_bird.cpython-311.pyc
ADDED
|
Binary file (3.86 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/big_bird/__pycache__/tokenization_big_bird.cpython-311.pyc
ADDED
|
Binary file (8.06 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/big_bird/configuration_big_bird.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 Google Research and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""BigBird model configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...utils import auto_docstring
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@auto_docstring(checkpoint="google/bigbird-roberta-base")
|
| 23 |
+
@strict
|
| 24 |
+
class BigBirdConfig(PreTrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
attention_type (`str`, *optional*, defaults to `"block_sparse"`):
|
| 27 |
+
Whether to use block sparse attention (with n complexity) as introduced in paper or original attention
|
| 28 |
+
layer (with n^2 complexity). Possible values are `"original_full"` and `"block_sparse"`.
|
| 29 |
+
use_bias (`bool`, *optional*, defaults to `True`):
|
| 30 |
+
Whether to use bias in query, key, value.
|
| 31 |
+
rescale_embeddings (`bool`, *optional*, defaults to `False`):
|
| 32 |
+
Whether to rescale embeddings with (hidden_size ** 0.5).
|
| 33 |
+
block_size (`int`, *optional*, defaults to 64):
|
| 34 |
+
Size of each block. Useful only when `attention_type == "block_sparse"`.
|
| 35 |
+
num_random_blocks (`int`, *optional*, defaults to 3):
|
| 36 |
+
Each query is going to attend these many number of random blocks. Useful only when `attention_type ==
|
| 37 |
+
"block_sparse"`.
|
| 38 |
+
|
| 39 |
+
Example:
|
| 40 |
+
|
| 41 |
+
```python
|
| 42 |
+
>>> from transformers import BigBirdConfig, BigBirdModel
|
| 43 |
+
|
| 44 |
+
>>> # Initializing a BigBird google/bigbird-roberta-base style configuration
|
| 45 |
+
>>> configuration = BigBirdConfig()
|
| 46 |
+
|
| 47 |
+
>>> # Initializing a model (with random weights) from the google/bigbird-roberta-base style configuration
|
| 48 |
+
>>> model = BigBirdModel(configuration)
|
| 49 |
+
|
| 50 |
+
>>> # Accessing the model configuration
|
| 51 |
+
>>> configuration = model.config
|
| 52 |
+
```"""
|
| 53 |
+
|
| 54 |
+
model_type = "big_bird"
|
| 55 |
+
|
| 56 |
+
vocab_size: int = 50358
|
| 57 |
+
hidden_size: int = 768
|
| 58 |
+
num_hidden_layers: int = 12
|
| 59 |
+
num_attention_heads: int = 12
|
| 60 |
+
intermediate_size: int = 3072
|
| 61 |
+
hidden_act: str = "gelu_new"
|
| 62 |
+
hidden_dropout_prob: float | int = 0.1
|
| 63 |
+
attention_probs_dropout_prob: float | int = 0.1
|
| 64 |
+
max_position_embeddings: int = 4096
|
| 65 |
+
type_vocab_size: int = 2
|
| 66 |
+
initializer_range: float = 0.02
|
| 67 |
+
layer_norm_eps: float = 1e-12
|
| 68 |
+
use_cache: bool = True
|
| 69 |
+
pad_token_id: int | None = 0
|
| 70 |
+
bos_token_id: int | None = 1
|
| 71 |
+
eos_token_id: int | list[int] | None = 2
|
| 72 |
+
sep_token_id: int | None = 66
|
| 73 |
+
attention_type: str = "block_sparse"
|
| 74 |
+
use_bias: bool = True
|
| 75 |
+
rescale_embeddings: bool = False
|
| 76 |
+
block_size: int = 64
|
| 77 |
+
num_random_blocks: int = 3
|
| 78 |
+
classifier_dropout: float | int | None = None
|
| 79 |
+
is_decoder: bool = False
|
| 80 |
+
add_cross_attention: bool = False
|
| 81 |
+
tie_word_embeddings: bool = True
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
__all__ = ["BigBirdConfig"]
|
lib/python3.11/site-packages/transformers/models/big_bird/modeling_big_bird.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
lib/python3.11/site-packages/transformers/models/big_bird/tokenization_big_bird.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 Google AI, Google Brain and the HuggingFace Inc. team.
|
| 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 |
+
"""Tokenization classes for Big Bird model."""
|
| 15 |
+
|
| 16 |
+
from tokenizers import Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors
|
| 17 |
+
from tokenizers.models import Unigram
|
| 18 |
+
|
| 19 |
+
from ...tokenization_python import AddedToken
|
| 20 |
+
from ...tokenization_utils_tokenizers import TokenizersBackend
|
| 21 |
+
from ...utils import logging
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
SPIECE_UNDERLINE = "▁"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class BigBirdTokenizer(TokenizersBackend):
|
| 32 |
+
"""
|
| 33 |
+
Construct a "fast" BigBird tokenizer (backed by HuggingFace's *tokenizers* library). Based on
|
| 34 |
+
[Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models). This
|
| 35 |
+
tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should refer to
|
| 36 |
+
this superclass for more information regarding those methods
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
vocab (`str`, `dict` or `list`, *optional*):
|
| 40 |
+
Custom vocabulary dictionary. If not provided, vocabulary is loaded from vocab_file.
|
| 41 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 42 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 43 |
+
token instead.
|
| 44 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 45 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 46 |
+
|
| 47 |
+
<Tip>
|
| 48 |
+
|
| 49 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 50 |
+
sequence. The token used is the `cls_token`.
|
| 51 |
+
|
| 52 |
+
</Tip>
|
| 53 |
+
|
| 54 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 55 |
+
The end of sequence token. .. note:: When building a sequence using special tokens, this is not the token
|
| 56 |
+
that is used for the end of sequence. The token used is the `sep_token`.
|
| 57 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 58 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 59 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 60 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 61 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 62 |
+
token of a sequence built with special tokens.
|
| 63 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 64 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 65 |
+
modeling. This is the token which the model will try to predict.
|
| 66 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 67 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 68 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 69 |
+
add_prefix_space (`bool`, *optional*, defaults to `True`):
|
| 70 |
+
Whether or not to add an initial space to the input. This allows to treat the leading word just as any
|
| 71 |
+
other word.
|
| 72 |
+
vocab_file (`str`, *optional*):
|
| 73 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
| 74 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 75 |
+
tokenizer_file (`str`, *optional*):
|
| 76 |
+
Path to a tokenizers JSON file containing the serialization of a tokenizer.
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 80 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 81 |
+
prefix_tokens: list[int] = []
|
| 82 |
+
model = Unigram
|
| 83 |
+
|
| 84 |
+
def __init__(
|
| 85 |
+
self,
|
| 86 |
+
vocab: str | dict | list | None = None,
|
| 87 |
+
unk_token="<unk>",
|
| 88 |
+
bos_token="<s>",
|
| 89 |
+
eos_token="</s>",
|
| 90 |
+
pad_token="<pad>",
|
| 91 |
+
sep_token="[SEP]",
|
| 92 |
+
mask_token="[MASK]",
|
| 93 |
+
cls_token="[CLS]",
|
| 94 |
+
add_prefix_space=True,
|
| 95 |
+
**kwargs,
|
| 96 |
+
):
|
| 97 |
+
bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
|
| 98 |
+
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
|
| 99 |
+
unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
|
| 100 |
+
pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
|
| 101 |
+
cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
|
| 102 |
+
sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
|
| 103 |
+
mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
|
| 104 |
+
|
| 105 |
+
self.add_prefix_space = add_prefix_space
|
| 106 |
+
|
| 107 |
+
# Convert vocab to list of (token, score) tuples
|
| 108 |
+
if vocab is None:
|
| 109 |
+
vocab = [(str(pad_token), 0.0), (str(eos_token), 0.0), (str(bos_token), 0.0), (str(unk_token), 0.0)]
|
| 110 |
+
unk_id = 3
|
| 111 |
+
elif isinstance(vocab, list):
|
| 112 |
+
# vocab.insert(100, (str(unk_token), 0.0)) # Ensure unk_token is in vocab at index 100
|
| 113 |
+
unk_id = vocab.index((str(unk_token), 0.0)) if (str(unk_token), 0.0) in vocab else 100
|
| 114 |
+
|
| 115 |
+
self._tokenizer = Tokenizer(Unigram(vocab, unk_id=unk_id, byte_fallback=False))
|
| 116 |
+
self._tokenizer.normalizer = normalizers.Sequence(
|
| 117 |
+
[normalizers.Strip(left=False, right=False), normalizers.Replace(Regex(r" {2,}"), SPIECE_UNDERLINE)]
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
prepend_scheme = "always" if add_prefix_space else "never"
|
| 121 |
+
self._tokenizer.pre_tokenizer = pre_tokenizers.Metaspace(
|
| 122 |
+
replacement="▁", prepend_scheme=prepend_scheme, split=True
|
| 123 |
+
)
|
| 124 |
+
self._tokenizer.decoder = decoders.Metaspace(replacement="▁", prepend_scheme=prepend_scheme, split=True)
|
| 125 |
+
|
| 126 |
+
super().__init__(
|
| 127 |
+
bos_token=bos_token,
|
| 128 |
+
eos_token=eos_token,
|
| 129 |
+
unk_token=unk_token,
|
| 130 |
+
pad_token=pad_token,
|
| 131 |
+
mask_token=mask_token,
|
| 132 |
+
cls_token=cls_token,
|
| 133 |
+
sep_token=sep_token,
|
| 134 |
+
add_prefix_space=add_prefix_space,
|
| 135 |
+
**kwargs,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
# Ensure cls_token and sep_token are in vocab
|
| 139 |
+
cls_token_str = str(cls_token)
|
| 140 |
+
sep_token_str = str(sep_token)
|
| 141 |
+
cls_token_id = self.cls_token_id
|
| 142 |
+
sep_token_id = self.sep_token_id
|
| 143 |
+
|
| 144 |
+
self._tokenizer.post_processor = processors.TemplateProcessing(
|
| 145 |
+
single=f"{cls_token_str}:0 $A:0 {sep_token_str}:0",
|
| 146 |
+
pair=f"{cls_token_str}:0 $A:0 {sep_token_str}:0 $B:1 {sep_token_str}:1",
|
| 147 |
+
special_tokens=[(cls_token_str, cls_token_id), (sep_token_str, sep_token_id)],
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
__all__ = ["BigBirdTokenizer"]
|
lib/python3.11/site-packages/transformers/models/bigbird_pegasus/__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_bigbird_pegasus import *
|
| 22 |
+
from .modeling_bigbird_pegasus 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__)
|
lib/python3.11/site-packages/transformers/models/bigbird_pegasus/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (805 Bytes). View file
|
|
|
lib/python3.11/site-packages/transformers/models/bigbird_pegasus/__pycache__/configuration_bigbird_pegasus.cpython-311.pyc
ADDED
|
Binary file (4.21 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/bigbird_pegasus/configuration_bigbird_pegasus.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright Google Research and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""BigBirdPegasus model configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...utils import auto_docstring
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@auto_docstring(checkpoint="google/bigbird-pegasus-large-arxiv")
|
| 23 |
+
@strict
|
| 24 |
+
class BigBirdPegasusConfig(PreTrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
attention_type (`str`, *optional*, defaults to `"block_sparse"`):
|
| 27 |
+
Whether to use block sparse attention (with n complexity) as introduced in paper or original attention
|
| 28 |
+
layer (with n^2 complexity). Possible values are `"original_full"` and `"block_sparse"`.
|
| 29 |
+
block_size (`int`, *optional*, defaults to 64):
|
| 30 |
+
Size of each block. Useful only when `attention_type == "block_sparse"`.
|
| 31 |
+
num_random_blocks (`int`, *optional*, defaults to 3):
|
| 32 |
+
Each query is going to attend these many number of random blocks. Useful only when `attention_type ==
|
| 33 |
+
"block_sparse"`.
|
| 34 |
+
use_bias (`bool`, *optional*, defaults to `True`):
|
| 35 |
+
Whether to use bias in query, key, value.
|
| 36 |
+
|
| 37 |
+
Example:
|
| 38 |
+
|
| 39 |
+
```python
|
| 40 |
+
>>> from transformers import BigBirdPegasusConfig, BigBirdPegasusModel
|
| 41 |
+
|
| 42 |
+
>>> # Initializing a BigBirdPegasus bigbird-pegasus-base style configuration
|
| 43 |
+
>>> configuration = BigBirdPegasusConfig()
|
| 44 |
+
|
| 45 |
+
>>> # Initializing a model (with random weights) from the bigbird-pegasus-base style configuration
|
| 46 |
+
>>> model = BigBirdPegasusModel(configuration)
|
| 47 |
+
|
| 48 |
+
>>> # Accessing the model configuration
|
| 49 |
+
>>> configuration = model.config
|
| 50 |
+
```"""
|
| 51 |
+
|
| 52 |
+
model_type = "bigbird_pegasus"
|
| 53 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 54 |
+
attribute_map = {
|
| 55 |
+
"num_attention_heads": "encoder_attention_heads",
|
| 56 |
+
"hidden_size": "d_model",
|
| 57 |
+
"attention_probs_dropout_prob": "attention_dropout",
|
| 58 |
+
"num_hidden_layers": "encoder_layers",
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
vocab_size: int = 96103
|
| 62 |
+
max_position_embeddings: int = 4096
|
| 63 |
+
encoder_layers: int = 16
|
| 64 |
+
encoder_ffn_dim: int = 4096
|
| 65 |
+
encoder_attention_heads: int = 16
|
| 66 |
+
decoder_layers: int = 16
|
| 67 |
+
decoder_ffn_dim: int = 4096
|
| 68 |
+
decoder_attention_heads: int = 16
|
| 69 |
+
encoder_layerdrop: float | int = 0.0
|
| 70 |
+
decoder_layerdrop: float | int = 0.0
|
| 71 |
+
use_cache: bool = True
|
| 72 |
+
is_encoder_decoder: bool = True
|
| 73 |
+
activation_function: str = "gelu_new"
|
| 74 |
+
d_model: int = 1024
|
| 75 |
+
dropout: float | int = 0.1
|
| 76 |
+
attention_dropout: float | int = 0.0
|
| 77 |
+
activation_dropout: float | int = 0.0
|
| 78 |
+
init_std: float = 0.02
|
| 79 |
+
decoder_start_token_id: int = 2
|
| 80 |
+
classifier_dropout: float | int = 0.0
|
| 81 |
+
scale_embedding: bool = True
|
| 82 |
+
pad_token_id: int | None = 0
|
| 83 |
+
bos_token_id: int | None = 2
|
| 84 |
+
eos_token_id: int | list[int] | None = 1
|
| 85 |
+
attention_type: str = "block_sparse" # only for encoder
|
| 86 |
+
block_size: int = 64
|
| 87 |
+
num_random_blocks: int = 3
|
| 88 |
+
use_bias: bool = False
|
| 89 |
+
is_decoder: bool = False
|
| 90 |
+
tie_word_embeddings: bool = True
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
__all__ = ["BigBirdPegasusConfig"]
|
lib/python3.11/site-packages/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
lib/python3.11/site-packages/transformers/models/biogpt/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_biogpt import *
|
| 22 |
+
from .modeling_biogpt import *
|
| 23 |
+
from .tokenization_biogpt import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.11/site-packages/transformers/models/biogpt/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (819 Bytes). View file
|
|
|
lib/python3.11/site-packages/transformers/models/biogpt/__pycache__/configuration_biogpt.cpython-311.pyc
ADDED
|
Binary file (2.56 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/biogpt/__pycache__/modeling_biogpt.cpython-311.pyc
ADDED
|
Binary file (32 kB). View file
|
|
|