Stage Harbor release files 36501-37000
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov2/modeling_flax_dinov2.py +801 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov2_with_registers/__init__.py +27 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov2_with_registers/configuration_dinov2_with_registers.py +159 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov2_with_registers/convert_dinov2_with_registers_to_hf.py +291 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py +832 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov2_with_registers/modular_dinov2_with_registers.py +488 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_convnext/__init__.py +27 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_convnext/configuration_dinov3_convnext.py +103 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_convnext/convert_dinov3_convnext_to_hf.py +234 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_convnext/modeling_dinov3_convnext.py +261 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_vit/__init__.py +28 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_vit/configuration_dinov3_vit.py +166 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_vit/convert_dinov3_vit_to_hf.py +337 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_vit/image_processing_dinov3_vit_fast.py +104 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_vit/modeling_dinov3_vit.py +538 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_vit/modular_dinov3_vit.py +429 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/distilbert/__init__.py +31 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/distilbert/configuration_distilbert.py +141 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/distilbert/modeling_distilbert.py +1299 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/distilbert/modeling_flax_distilbert.py +906 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/distilbert/modeling_tf_distilbert.py +1146 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/distilbert/tokenization_distilbert.py +492 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/distilbert/tokenization_distilbert_fast.py +149 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dit/__init__.py +0 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dit/convert_dit_unilm_to_pytorch.py +230 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/doge/__init__.py +28 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/doge/configuration_doge.py +241 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/doge/convert_doge_weights_to_hf.py +126 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/doge/modeling_doge.py +818 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/doge/modular_doge.py +800 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/donut/__init__.py +31 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/donut/configuration_donut_swin.py +135 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/donut/convert_donut_to_pytorch.py +234 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/donut/feature_extraction_donut.py +38 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/donut/image_processing_donut.py +477 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/donut/image_processing_donut_fast.py +265 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/donut/modeling_donut_swin.py +1032 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/donut/processing_donut.py +224 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dots1/__init__.py +27 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dots1/configuration_dots1.py +211 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dots1/modeling_dots1.py +618 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dots1/modular_dots1.py +111 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dpr/__init__.py +30 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dpr/configuration_dpr.py +131 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dpr/convert_dpr_original_checkpoint_to_pytorch.py +145 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dpr/modeling_dpr.py +592 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dpr/modeling_tf_dpr.py +799 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dpr/tokenization_dpr.py +321 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dpr/tokenization_dpr_fast.py +321 -0
- tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dpt/__init__.py +30 -0
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov2/modeling_flax_dinov2.py
ADDED
|
@@ -0,0 +1,801 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 Meta AI and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Flax DINOv2 model."""
|
| 16 |
+
|
| 17 |
+
import collections.abc
|
| 18 |
+
import math
|
| 19 |
+
from typing import Optional
|
| 20 |
+
|
| 21 |
+
import flax.linen as nn
|
| 22 |
+
import jax
|
| 23 |
+
import jax.numpy as jnp
|
| 24 |
+
from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
|
| 25 |
+
from flax.linen.attention import dot_product_attention_weights
|
| 26 |
+
from flax.traverse_util import flatten_dict, unflatten_dict
|
| 27 |
+
|
| 28 |
+
from ...modeling_flax_outputs import FlaxBaseModelOutput, FlaxBaseModelOutputWithPooling, FlaxSequenceClassifierOutput
|
| 29 |
+
from ...modeling_flax_utils import (
|
| 30 |
+
ACT2FN,
|
| 31 |
+
FlaxPreTrainedModel,
|
| 32 |
+
append_replace_return_docstrings,
|
| 33 |
+
overwrite_call_docstring,
|
| 34 |
+
)
|
| 35 |
+
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward
|
| 36 |
+
from .configuration_dinov2 import Dinov2Config
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
DINOV2_START_DOCSTRING = r"""
|
| 40 |
+
|
| 41 |
+
This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 42 |
+
library implements for all its model (such as downloading, saving and converting weights from PyTorch models)
|
| 43 |
+
|
| 44 |
+
This model is also a
|
| 45 |
+
[flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html) subclass. Use it as
|
| 46 |
+
a regular Flax linen Module and refer to the Flax documentation for all matter related to general usage and
|
| 47 |
+
behavior.
|
| 48 |
+
|
| 49 |
+
Finally, this model supports inherent JAX features such as:
|
| 50 |
+
|
| 51 |
+
- [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
|
| 52 |
+
- [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
|
| 53 |
+
- [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
|
| 54 |
+
- [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
|
| 55 |
+
|
| 56 |
+
Parameters:
|
| 57 |
+
config ([`Dinov2Config`]): Model configuration class with all the parameters of the model.
|
| 58 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 59 |
+
configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 60 |
+
dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
|
| 61 |
+
The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
|
| 62 |
+
`jax.numpy.bfloat16` (on TPUs).
|
| 63 |
+
|
| 64 |
+
This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
|
| 65 |
+
specified all the computation will be performed with the given `dtype`.
|
| 66 |
+
|
| 67 |
+
**Note that this only specifies the dtype of the computation and does not influence the dtype of model
|
| 68 |
+
parameters.**
|
| 69 |
+
|
| 70 |
+
If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
|
| 71 |
+
[`~FlaxPreTrainedModel.to_bf16`].
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
DINOV2_INPUTS_DOCSTRING = r"""
|
| 75 |
+
Args:
|
| 76 |
+
pixel_values (`numpy.ndarray` of shape `(batch_size, num_channels, height, width)`):
|
| 77 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`Dinov2ImageProcessor.__call__`]
|
| 78 |
+
for details.
|
| 79 |
+
|
| 80 |
+
output_attentions (`bool`, *optional*):
|
| 81 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 82 |
+
tensors for more detail.
|
| 83 |
+
output_hidden_states (`bool`, *optional*):
|
| 84 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 85 |
+
more detail.
|
| 86 |
+
return_dict (`bool`, *optional*):
|
| 87 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class FlaxDinov2PatchEmbeddings(nn.Module):
|
| 92 |
+
config: Dinov2Config
|
| 93 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 94 |
+
|
| 95 |
+
def setup(self):
|
| 96 |
+
image_size = self.config.image_size
|
| 97 |
+
patch_size = self.config.patch_size
|
| 98 |
+
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
|
| 99 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 100 |
+
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 101 |
+
|
| 102 |
+
self.num_patches = num_patches
|
| 103 |
+
self.num_channels = self.config.num_channels
|
| 104 |
+
self.projection = nn.Conv(
|
| 105 |
+
self.config.hidden_size,
|
| 106 |
+
kernel_size=patch_size,
|
| 107 |
+
strides=patch_size,
|
| 108 |
+
padding="VALID",
|
| 109 |
+
dtype=self.dtype,
|
| 110 |
+
kernel_init=jax.nn.initializers.variance_scaling(
|
| 111 |
+
self.config.initializer_range**2, "fan_in", "truncated_normal"
|
| 112 |
+
),
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
# Copied from transformers.models.vit.modeling_flax_vit.FlaxViTPatchEmbeddings.__call__
|
| 116 |
+
def __call__(self, pixel_values):
|
| 117 |
+
num_channels = pixel_values.shape[-1]
|
| 118 |
+
if num_channels != self.num_channels:
|
| 119 |
+
raise ValueError(
|
| 120 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 121 |
+
)
|
| 122 |
+
embeddings = self.projection(pixel_values)
|
| 123 |
+
batch_size, _, _, channels = embeddings.shape
|
| 124 |
+
return jnp.reshape(embeddings, (batch_size, -1, channels))
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class FlaxDinov2Embeddings(nn.Module):
|
| 128 |
+
"""Construct the CLS token, position and patch embeddings."""
|
| 129 |
+
|
| 130 |
+
config: Dinov2Config
|
| 131 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 132 |
+
|
| 133 |
+
def setup(self):
|
| 134 |
+
self.cls_token = self.param(
|
| 135 |
+
"cls_token",
|
| 136 |
+
jax.nn.initializers.variance_scaling(self.config.initializer_range**2, "fan_in", "truncated_normal"),
|
| 137 |
+
(1, 1, self.config.hidden_size),
|
| 138 |
+
)
|
| 139 |
+
if self.config.use_mask_token:
|
| 140 |
+
self.mask_token = self.param(
|
| 141 |
+
"mask_token",
|
| 142 |
+
jax.nn.initializers.variance_scaling(self.config.initializer_range**2, "fan_in", "truncated_normal"),
|
| 143 |
+
(1, self.config.hidden_size),
|
| 144 |
+
)
|
| 145 |
+
self.patch_embeddings = FlaxDinov2PatchEmbeddings(self.config, dtype=self.dtype)
|
| 146 |
+
num_patches = self.patch_embeddings.num_patches
|
| 147 |
+
self.position_embeddings = self.param(
|
| 148 |
+
"position_embeddings",
|
| 149 |
+
jax.nn.initializers.variance_scaling(self.config.initializer_range**2, "fan_in", "truncated_normal"),
|
| 150 |
+
(1, num_patches + 1, self.config.hidden_size),
|
| 151 |
+
)
|
| 152 |
+
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
|
| 153 |
+
|
| 154 |
+
def interpolate_pos_encoding(self, config, hidden_states, height, width, position_embeddings):
|
| 155 |
+
num_patches = hidden_states.shape[1] - 1
|
| 156 |
+
num_positions = position_embeddings.shape[1] - 1
|
| 157 |
+
if num_patches == num_positions and height == width:
|
| 158 |
+
return position_embeddings
|
| 159 |
+
class_pos_embed = position_embeddings[:, 0]
|
| 160 |
+
patch_pos_embed = position_embeddings[:, 1:]
|
| 161 |
+
dim = hidden_states.shape[-1]
|
| 162 |
+
|
| 163 |
+
h = height // config.patch_size
|
| 164 |
+
w = width // config.patch_size
|
| 165 |
+
height, width = h + 0.1, w + 0.1
|
| 166 |
+
|
| 167 |
+
patch_pos_embed = patch_pos_embed.reshape(
|
| 168 |
+
(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim)
|
| 169 |
+
)
|
| 170 |
+
patch_pos_embed = jnp.transpose(patch_pos_embed, (0, 3, 1, 2))
|
| 171 |
+
target_dtype = patch_pos_embed.dtype
|
| 172 |
+
new_height_ratio = jnp.float32(height / math.sqrt(num_positions))
|
| 173 |
+
new_width_ratio = jnp.float32(width / math.sqrt(num_positions))
|
| 174 |
+
|
| 175 |
+
scale = jnp.array([new_height_ratio, new_width_ratio], dtype=jnp.float32)
|
| 176 |
+
translation = jnp.array([0.0, 0.0], dtype=jnp.float32)
|
| 177 |
+
|
| 178 |
+
patch_pos_embed = jax.image.scale_and_translate(
|
| 179 |
+
patch_pos_embed.astype(jnp.float32),
|
| 180 |
+
shape=(patch_pos_embed.shape[0], patch_pos_embed.shape[1], h, w),
|
| 181 |
+
spatial_dims=(2, 3),
|
| 182 |
+
scale=scale,
|
| 183 |
+
translation=translation,
|
| 184 |
+
method="bicubic",
|
| 185 |
+
antialias=False,
|
| 186 |
+
)
|
| 187 |
+
patch_pos_embed = patch_pos_embed.astype(target_dtype)
|
| 188 |
+
patch_pos_embed = jnp.transpose(patch_pos_embed, (0, 2, 3, 1)).reshape((position_embeddings.shape[0], -1, dim))
|
| 189 |
+
patch_pos_embed_expanded = jnp.tile(patch_pos_embed, (hidden_states.shape[0], 1, 1))
|
| 190 |
+
class_pos_embed_expanded = jnp.tile(class_pos_embed, (hidden_states.shape[0], 1, 1))
|
| 191 |
+
|
| 192 |
+
return jnp.concatenate((class_pos_embed_expanded, patch_pos_embed_expanded), axis=1)
|
| 193 |
+
|
| 194 |
+
def __call__(self, pixel_values, deterministic=True):
|
| 195 |
+
batch_size = pixel_values.shape[0]
|
| 196 |
+
target_dtype = self.patch_embeddings.projection.dtype
|
| 197 |
+
height, width = pixel_values.shape[1], pixel_values.shape[2]
|
| 198 |
+
|
| 199 |
+
embeddings = self.patch_embeddings(pixel_values.astype(target_dtype))
|
| 200 |
+
|
| 201 |
+
cls_tokens = jnp.broadcast_to(self.cls_token, (batch_size, 1, self.config.hidden_size))
|
| 202 |
+
embeddings = jnp.concatenate((cls_tokens, embeddings), axis=1)
|
| 203 |
+
|
| 204 |
+
embeddings = embeddings + self.interpolate_pos_encoding(
|
| 205 |
+
self.config, embeddings, height, width, self.position_embeddings
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
embeddings = self.dropout(embeddings, deterministic=deterministic)
|
| 209 |
+
return embeddings
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
# Copied from transformers.models.vit.modeling_flax_vit.FlaxViTSelfAttention with ViT->Dinov2
|
| 213 |
+
class FlaxDinov2SelfAttention(nn.Module):
|
| 214 |
+
config: Dinov2Config
|
| 215 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 216 |
+
|
| 217 |
+
def setup(self):
|
| 218 |
+
if self.config.hidden_size % self.config.num_attention_heads != 0:
|
| 219 |
+
raise ValueError(
|
| 220 |
+
"`config.hidden_size`: {self.config.hidden_size} has to be a multiple of `config.num_attention_heads`:"
|
| 221 |
+
" {self.config.num_attention_heads}"
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
self.query = nn.Dense(
|
| 225 |
+
self.config.hidden_size,
|
| 226 |
+
dtype=self.dtype,
|
| 227 |
+
kernel_init=jax.nn.initializers.variance_scaling(
|
| 228 |
+
self.config.initializer_range**2, mode="fan_in", distribution="truncated_normal"
|
| 229 |
+
),
|
| 230 |
+
use_bias=self.config.qkv_bias,
|
| 231 |
+
)
|
| 232 |
+
self.key = nn.Dense(
|
| 233 |
+
self.config.hidden_size,
|
| 234 |
+
dtype=self.dtype,
|
| 235 |
+
kernel_init=jax.nn.initializers.variance_scaling(
|
| 236 |
+
self.config.initializer_range**2, mode="fan_in", distribution="truncated_normal"
|
| 237 |
+
),
|
| 238 |
+
use_bias=self.config.qkv_bias,
|
| 239 |
+
)
|
| 240 |
+
self.value = nn.Dense(
|
| 241 |
+
self.config.hidden_size,
|
| 242 |
+
dtype=self.dtype,
|
| 243 |
+
kernel_init=jax.nn.initializers.variance_scaling(
|
| 244 |
+
self.config.initializer_range**2, mode="fan_in", distribution="truncated_normal"
|
| 245 |
+
),
|
| 246 |
+
use_bias=self.config.qkv_bias,
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
def __call__(self, hidden_states, deterministic: bool = True, output_attentions: bool = False):
|
| 250 |
+
head_dim = self.config.hidden_size // self.config.num_attention_heads
|
| 251 |
+
|
| 252 |
+
query_states = self.query(hidden_states).reshape(
|
| 253 |
+
hidden_states.shape[:2] + (self.config.num_attention_heads, head_dim)
|
| 254 |
+
)
|
| 255 |
+
value_states = self.value(hidden_states).reshape(
|
| 256 |
+
hidden_states.shape[:2] + (self.config.num_attention_heads, head_dim)
|
| 257 |
+
)
|
| 258 |
+
key_states = self.key(hidden_states).reshape(
|
| 259 |
+
hidden_states.shape[:2] + (self.config.num_attention_heads, head_dim)
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
dropout_rng = None
|
| 263 |
+
if not deterministic and self.config.attention_probs_dropout_prob > 0.0:
|
| 264 |
+
dropout_rng = self.make_rng("dropout")
|
| 265 |
+
|
| 266 |
+
attn_weights = dot_product_attention_weights(
|
| 267 |
+
query_states,
|
| 268 |
+
key_states,
|
| 269 |
+
dropout_rng=dropout_rng,
|
| 270 |
+
dropout_rate=self.config.attention_probs_dropout_prob,
|
| 271 |
+
broadcast_dropout=True,
|
| 272 |
+
deterministic=deterministic,
|
| 273 |
+
dtype=self.dtype,
|
| 274 |
+
precision=None,
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
|
| 278 |
+
attn_output = attn_output.reshape(attn_output.shape[:2] + (-1,))
|
| 279 |
+
|
| 280 |
+
outputs = (attn_output, attn_weights) if output_attentions else (attn_output,)
|
| 281 |
+
return outputs
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
# Copied from transformers.models.vit.modeling_flax_vit.FlaxViTSelfOutput with ViT->Dinov2
|
| 285 |
+
class FlaxDinov2SelfOutput(nn.Module):
|
| 286 |
+
config: Dinov2Config
|
| 287 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 288 |
+
|
| 289 |
+
def setup(self):
|
| 290 |
+
self.dense = nn.Dense(
|
| 291 |
+
self.config.hidden_size,
|
| 292 |
+
kernel_init=jax.nn.initializers.variance_scaling(
|
| 293 |
+
self.config.initializer_range**2, "fan_in", "truncated_normal"
|
| 294 |
+
),
|
| 295 |
+
dtype=self.dtype,
|
| 296 |
+
)
|
| 297 |
+
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
|
| 298 |
+
|
| 299 |
+
def __call__(self, hidden_states, input_tensor, deterministic: bool = True):
|
| 300 |
+
hidden_states = self.dense(hidden_states)
|
| 301 |
+
hidden_states = self.dropout(hidden_states, deterministic=deterministic)
|
| 302 |
+
return hidden_states
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
# Copied from transformers.models.vit.modeling_flax_vit.FlaxViTAttention with ViT->Dinov2
|
| 306 |
+
class FlaxDinov2Attention(nn.Module):
|
| 307 |
+
config: Dinov2Config
|
| 308 |
+
dtype: jnp.dtype = jnp.float32
|
| 309 |
+
|
| 310 |
+
def setup(self):
|
| 311 |
+
self.attention = FlaxDinov2SelfAttention(self.config, dtype=self.dtype)
|
| 312 |
+
self.output = FlaxDinov2SelfOutput(self.config, dtype=self.dtype)
|
| 313 |
+
|
| 314 |
+
def __call__(self, hidden_states, deterministic=True, output_attentions: bool = False):
|
| 315 |
+
attn_outputs = self.attention(hidden_states, deterministic=deterministic, output_attentions=output_attentions)
|
| 316 |
+
attn_output = attn_outputs[0]
|
| 317 |
+
hidden_states = self.output(attn_output, hidden_states, deterministic=deterministic)
|
| 318 |
+
|
| 319 |
+
outputs = (hidden_states,)
|
| 320 |
+
|
| 321 |
+
if output_attentions:
|
| 322 |
+
outputs += (attn_outputs[1],)
|
| 323 |
+
|
| 324 |
+
return outputs
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def ones_with_scale(key, shape, scale, dtype=jnp.float32):
|
| 328 |
+
return jnp.ones(shape, dtype) * scale
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
class FlaxDinov2LayerScale(nn.Module):
|
| 332 |
+
config: Dinov2Config
|
| 333 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 334 |
+
|
| 335 |
+
def setup(self):
|
| 336 |
+
self.lambda1 = self.config.layerscale_value * self.param(
|
| 337 |
+
"lambda1",
|
| 338 |
+
jax.nn.initializers.ones,
|
| 339 |
+
(self.config.hidden_size,),
|
| 340 |
+
)
|
| 341 |
+
self.lambda1 = self.lambda1 * self.config.layerscale_value
|
| 342 |
+
|
| 343 |
+
def __call__(self, hidden_states):
|
| 344 |
+
return self.lambda1 * hidden_states
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
# Copied from transformers.models.beit.modeling_flax_beit.FlaxBeitDropPath with Beit -> Dinov2
|
| 348 |
+
class FlaxDinov2DropPath(nn.Module):
|
| 349 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 350 |
+
|
| 351 |
+
rate: float
|
| 352 |
+
|
| 353 |
+
@nn.module.compact
|
| 354 |
+
def __call__(self, inputs, deterministic: Optional[bool] = True):
|
| 355 |
+
if self.rate == 0.0:
|
| 356 |
+
return inputs
|
| 357 |
+
keep_prob = 1.0 - self.rate
|
| 358 |
+
if deterministic:
|
| 359 |
+
return inputs
|
| 360 |
+
else:
|
| 361 |
+
shape = (inputs.shape[0],) + (1,) * (inputs.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 362 |
+
rng = self.make_rng("droppath")
|
| 363 |
+
random_tensor = keep_prob + jax.random.uniform(rng, shape=shape, dtype=inputs.dtype)
|
| 364 |
+
binary_tensor = jnp.floor(random_tensor)
|
| 365 |
+
output = inputs / keep_prob * binary_tensor
|
| 366 |
+
return output
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
class FlaxDinov2MLP(nn.Module):
|
| 370 |
+
config: Dinov2Config
|
| 371 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 372 |
+
|
| 373 |
+
def setup(self):
|
| 374 |
+
self.fc1 = nn.Dense(
|
| 375 |
+
self.config.hidden_size * self.config.mlp_ratio,
|
| 376 |
+
kernel_init=jax.nn.initializers.variance_scaling(
|
| 377 |
+
self.config.initializer_range**2, "fan_in", "truncated_normal"
|
| 378 |
+
),
|
| 379 |
+
dtype=self.dtype,
|
| 380 |
+
)
|
| 381 |
+
self.fc2 = nn.Dense(
|
| 382 |
+
self.config.hidden_size,
|
| 383 |
+
kernel_init=jax.nn.initializers.variance_scaling(
|
| 384 |
+
self.config.initializer_range**2, "fan_in", "truncated_normal"
|
| 385 |
+
),
|
| 386 |
+
dtype=self.dtype,
|
| 387 |
+
)
|
| 388 |
+
if isinstance(self.config.hidden_act, str):
|
| 389 |
+
self.act = ACT2FN[self.config.hidden_act]
|
| 390 |
+
else:
|
| 391 |
+
self.act = self.config.hidden_act
|
| 392 |
+
|
| 393 |
+
def __call__(self, hidden_states):
|
| 394 |
+
hidden_states = self.fc1(hidden_states)
|
| 395 |
+
hidden_states = self.act(hidden_states)
|
| 396 |
+
hidden_states = self.fc2(hidden_states)
|
| 397 |
+
return hidden_states
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
class FlaxDinov2SwiGLUFFN(nn.Module):
|
| 401 |
+
config: Dinov2Config
|
| 402 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 403 |
+
|
| 404 |
+
def setup(self):
|
| 405 |
+
hidden_features = int(self.config.hidden_size * self.config.mlp_ratio)
|
| 406 |
+
hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
|
| 407 |
+
|
| 408 |
+
self.weights_in = nn.Dense(
|
| 409 |
+
2 * hidden_features,
|
| 410 |
+
kernel_init=jax.nn.initializers.variance_scaling(
|
| 411 |
+
self.config.initializer_range**2, "fan_in", "truncated_normal"
|
| 412 |
+
),
|
| 413 |
+
dtype=self.dtype,
|
| 414 |
+
)
|
| 415 |
+
self.weights_out = nn.Dense(
|
| 416 |
+
self.config.hidden_size,
|
| 417 |
+
kernel_init=jax.nn.initializers.variance_scaling(
|
| 418 |
+
self.config.initializer_range**2, "fan_in", "truncated_normal"
|
| 419 |
+
),
|
| 420 |
+
dtype=self.dtype,
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
def __call__(self, hidden_states):
|
| 424 |
+
hidden_states = self.weights_in(hidden_states)
|
| 425 |
+
x1, x2 = jnp.split(hidden_states, 2, axis=-1)
|
| 426 |
+
hidden = nn.silu(x1) * x2
|
| 427 |
+
return self.weights_out(hidden)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
class FlaxDinov2Layer(nn.Module):
|
| 431 |
+
config: Dinov2Config
|
| 432 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 433 |
+
|
| 434 |
+
def setup(self):
|
| 435 |
+
self.norm1 = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 436 |
+
self.attention = FlaxDinov2Attention(self.config, dtype=self.dtype)
|
| 437 |
+
self.layer_scale1 = FlaxDinov2LayerScale(self.config, dtype=self.dtype)
|
| 438 |
+
self.drop_path = FlaxDinov2DropPath(self.config.drop_path_rate)
|
| 439 |
+
self.norm2 = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 440 |
+
|
| 441 |
+
if self.config.use_swiglu_ffn:
|
| 442 |
+
self.mlp = FlaxDinov2SwiGLUFFN(self.config, dtype=self.dtype)
|
| 443 |
+
else:
|
| 444 |
+
self.mlp = FlaxDinov2MLP(self.config, dtype=self.dtype)
|
| 445 |
+
|
| 446 |
+
self.layer_scale2 = FlaxDinov2LayerScale(self.config, dtype=self.dtype)
|
| 447 |
+
|
| 448 |
+
def __call__(self, hidden_states, deterministic: bool = True, output_attentions: bool = False):
|
| 449 |
+
self_attention_outputs = self.attention(
|
| 450 |
+
self.norm1(hidden_states), # in Dinov2, layernorm is applied before self-attention
|
| 451 |
+
deterministic=deterministic,
|
| 452 |
+
output_attentions=output_attentions,
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
attention_output = self_attention_outputs[0]
|
| 456 |
+
|
| 457 |
+
attention_output = self.layer_scale1(attention_output)
|
| 458 |
+
|
| 459 |
+
outputs = self_attention_outputs[1:]
|
| 460 |
+
|
| 461 |
+
# first residual connection
|
| 462 |
+
hidden_states = self.drop_path(attention_output) + hidden_states
|
| 463 |
+
|
| 464 |
+
# in Dinov2, layernorm is also applied after self-attention
|
| 465 |
+
layer_output = self.norm2(hidden_states)
|
| 466 |
+
layer_output = self.mlp(layer_output)
|
| 467 |
+
layer_output = self.layer_scale2(layer_output)
|
| 468 |
+
|
| 469 |
+
# second residual connection
|
| 470 |
+
layer_output = self.drop_path(layer_output) + hidden_states
|
| 471 |
+
|
| 472 |
+
outputs = (layer_output,) + outputs
|
| 473 |
+
|
| 474 |
+
return outputs
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
# Copied from transformers.models.vit.modeling_flax_vit.FlaxViTLayerCollection with ViT->Dinov2
|
| 478 |
+
class FlaxDinov2LayerCollection(nn.Module):
|
| 479 |
+
config: Dinov2Config
|
| 480 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 481 |
+
|
| 482 |
+
def setup(self):
|
| 483 |
+
self.layers = [
|
| 484 |
+
FlaxDinov2Layer(self.config, name=str(i), dtype=self.dtype) for i in range(self.config.num_hidden_layers)
|
| 485 |
+
]
|
| 486 |
+
|
| 487 |
+
def __call__(
|
| 488 |
+
self,
|
| 489 |
+
hidden_states,
|
| 490 |
+
deterministic: bool = True,
|
| 491 |
+
output_attentions: bool = False,
|
| 492 |
+
output_hidden_states: bool = False,
|
| 493 |
+
return_dict: bool = True,
|
| 494 |
+
):
|
| 495 |
+
all_attentions = () if output_attentions else None
|
| 496 |
+
all_hidden_states = () if output_hidden_states else None
|
| 497 |
+
|
| 498 |
+
for i, layer in enumerate(self.layers):
|
| 499 |
+
if output_hidden_states:
|
| 500 |
+
all_hidden_states += (hidden_states,)
|
| 501 |
+
|
| 502 |
+
layer_outputs = layer(hidden_states, deterministic=deterministic, output_attentions=output_attentions)
|
| 503 |
+
|
| 504 |
+
hidden_states = layer_outputs[0]
|
| 505 |
+
|
| 506 |
+
if output_attentions:
|
| 507 |
+
all_attentions += (layer_outputs[1],)
|
| 508 |
+
|
| 509 |
+
if output_hidden_states:
|
| 510 |
+
all_hidden_states += (hidden_states,)
|
| 511 |
+
|
| 512 |
+
outputs = (hidden_states,)
|
| 513 |
+
if not return_dict:
|
| 514 |
+
return tuple(v for v in outputs if v is not None)
|
| 515 |
+
|
| 516 |
+
return FlaxBaseModelOutput(
|
| 517 |
+
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
# Copied from transformers.models.vit.modeling_flax_vit.FlaxViTEncoder with ViT->Dinov2
|
| 522 |
+
class FlaxDinov2Encoder(nn.Module):
|
| 523 |
+
config: Dinov2Config
|
| 524 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 525 |
+
|
| 526 |
+
def setup(self):
|
| 527 |
+
self.layer = FlaxDinov2LayerCollection(self.config, dtype=self.dtype)
|
| 528 |
+
|
| 529 |
+
def __call__(
|
| 530 |
+
self,
|
| 531 |
+
hidden_states,
|
| 532 |
+
deterministic: bool = True,
|
| 533 |
+
output_attentions: bool = False,
|
| 534 |
+
output_hidden_states: bool = False,
|
| 535 |
+
return_dict: bool = True,
|
| 536 |
+
):
|
| 537 |
+
return self.layer(
|
| 538 |
+
hidden_states,
|
| 539 |
+
deterministic=deterministic,
|
| 540 |
+
output_attentions=output_attentions,
|
| 541 |
+
output_hidden_states=output_hidden_states,
|
| 542 |
+
return_dict=return_dict,
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
class FlaxDinov2PreTrainedModel(FlaxPreTrainedModel):
|
| 547 |
+
"""
|
| 548 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 549 |
+
models.
|
| 550 |
+
"""
|
| 551 |
+
|
| 552 |
+
config_class = Dinov2Config
|
| 553 |
+
base_model_prefix = "dinov2"
|
| 554 |
+
main_input_name = "pixel_values"
|
| 555 |
+
module_class: nn.Module = None
|
| 556 |
+
|
| 557 |
+
def __init__(
|
| 558 |
+
self,
|
| 559 |
+
config: Dinov2Config,
|
| 560 |
+
input_shape=None,
|
| 561 |
+
seed: int = 0,
|
| 562 |
+
dtype: jnp.dtype = jnp.float32,
|
| 563 |
+
_do_init: bool = True,
|
| 564 |
+
**kwargs,
|
| 565 |
+
):
|
| 566 |
+
module = self.module_class(config=config, dtype=dtype, **kwargs)
|
| 567 |
+
if input_shape is None:
|
| 568 |
+
input_shape = (1, config.image_size, config.image_size, config.num_channels)
|
| 569 |
+
super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
|
| 570 |
+
|
| 571 |
+
def init_weights(self, rng: jax.random.PRNGKey, input_shape: tuple, params: FrozenDict = None) -> FrozenDict:
|
| 572 |
+
# init input tensors
|
| 573 |
+
pixel_values = jnp.zeros(input_shape, dtype=self.dtype)
|
| 574 |
+
|
| 575 |
+
params_rng, dropout_rng = jax.random.split(rng)
|
| 576 |
+
dropout_rng, droppath_rng = jax.random.split(dropout_rng)
|
| 577 |
+
rngs = {"params": params_rng, "dropout": dropout_rng, "droppath": droppath_rng}
|
| 578 |
+
|
| 579 |
+
random_params = self.module.init(rngs, pixel_values, return_dict=False)["params"]
|
| 580 |
+
|
| 581 |
+
if params is not None:
|
| 582 |
+
random_params = flatten_dict(unfreeze(random_params))
|
| 583 |
+
params = flatten_dict(unfreeze(params))
|
| 584 |
+
for missing_key in self._missing_keys:
|
| 585 |
+
params[missing_key] = random_params[missing_key]
|
| 586 |
+
self._missing_keys = set()
|
| 587 |
+
return freeze(unflatten_dict(params))
|
| 588 |
+
else:
|
| 589 |
+
return random_params
|
| 590 |
+
|
| 591 |
+
@add_start_docstrings_to_model_forward(DINOV2_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 592 |
+
def __call__(
|
| 593 |
+
self,
|
| 594 |
+
pixel_values,
|
| 595 |
+
params: Optional[dict] = None,
|
| 596 |
+
dropout_rng: jax.random.PRNGKey = None,
|
| 597 |
+
train: bool = False,
|
| 598 |
+
output_attentions: Optional[bool] = None,
|
| 599 |
+
output_hidden_states: Optional[bool] = None,
|
| 600 |
+
return_dict: Optional[bool] = None,
|
| 601 |
+
):
|
| 602 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 603 |
+
output_hidden_states = (
|
| 604 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 605 |
+
)
|
| 606 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 607 |
+
|
| 608 |
+
pixel_values = jnp.transpose(pixel_values, (0, 2, 3, 1))
|
| 609 |
+
# Handle any PRNG if needed
|
| 610 |
+
rngs = {}
|
| 611 |
+
if dropout_rng is not None:
|
| 612 |
+
dropout_rng, droppath_rng = jax.random.split(dropout_rng)
|
| 613 |
+
rngs["dropout"] = dropout_rng
|
| 614 |
+
rngs["droppath"] = droppath_rng
|
| 615 |
+
|
| 616 |
+
return self.module.apply(
|
| 617 |
+
{"params": params or self.params},
|
| 618 |
+
jnp.array(pixel_values, dtype=jnp.float32),
|
| 619 |
+
not train,
|
| 620 |
+
output_attentions,
|
| 621 |
+
output_hidden_states,
|
| 622 |
+
return_dict,
|
| 623 |
+
rngs=rngs,
|
| 624 |
+
)
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
class FlaxDinov2Module(nn.Module):
|
| 628 |
+
config: Dinov2Config
|
| 629 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 630 |
+
|
| 631 |
+
def setup(self):
|
| 632 |
+
self.embeddings = FlaxDinov2Embeddings(self.config, dtype=self.dtype)
|
| 633 |
+
self.encoder = FlaxDinov2Encoder(self.config, dtype=self.dtype)
|
| 634 |
+
self.layernorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 635 |
+
|
| 636 |
+
def __call__(
|
| 637 |
+
self,
|
| 638 |
+
pixel_values,
|
| 639 |
+
deterministic: bool = True,
|
| 640 |
+
output_attentions: bool = False,
|
| 641 |
+
output_hidden_states: bool = False,
|
| 642 |
+
return_dict: bool = True,
|
| 643 |
+
):
|
| 644 |
+
hidden_states = self.embeddings(pixel_values, deterministic=deterministic)
|
| 645 |
+
|
| 646 |
+
encoder_outputs = self.encoder(
|
| 647 |
+
hidden_states,
|
| 648 |
+
deterministic=deterministic,
|
| 649 |
+
output_attentions=output_attentions,
|
| 650 |
+
output_hidden_states=output_hidden_states,
|
| 651 |
+
return_dict=return_dict,
|
| 652 |
+
)
|
| 653 |
+
|
| 654 |
+
sequence_output = encoder_outputs[0]
|
| 655 |
+
sequence_output = self.layernorm(sequence_output)
|
| 656 |
+
pooled_output = sequence_output[:, 0, :]
|
| 657 |
+
|
| 658 |
+
if not return_dict:
|
| 659 |
+
head_outputs = (sequence_output, pooled_output)
|
| 660 |
+
return head_outputs + encoder_outputs[1:]
|
| 661 |
+
|
| 662 |
+
return FlaxBaseModelOutputWithPooling(
|
| 663 |
+
last_hidden_state=sequence_output,
|
| 664 |
+
pooler_output=pooled_output,
|
| 665 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 666 |
+
attentions=encoder_outputs.attentions,
|
| 667 |
+
)
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
@add_start_docstrings(
|
| 671 |
+
"The bare Dinov2 Model transformer outputting raw hidden-states without any specific head on top.",
|
| 672 |
+
DINOV2_START_DOCSTRING,
|
| 673 |
+
)
|
| 674 |
+
class FlaxDinov2Model(FlaxDinov2PreTrainedModel):
|
| 675 |
+
module_class = FlaxDinov2Module
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
FLAX_VISION_MODEL_DOCSTRING = """
|
| 679 |
+
Returns:
|
| 680 |
+
|
| 681 |
+
Examples:
|
| 682 |
+
|
| 683 |
+
```python
|
| 684 |
+
>>> from transformers import AutoImageProcessor, FlaxDinov2Model
|
| 685 |
+
>>> from PIL import Image
|
| 686 |
+
>>> import requests
|
| 687 |
+
|
| 688 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 689 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 690 |
+
|
| 691 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/dinov2-base")
|
| 692 |
+
>>> model = FlaxDinov2Model.from_pretrained("facebook/dinov2-base")
|
| 693 |
+
|
| 694 |
+
>>> inputs = image_processor(images=image, return_tensors="np")
|
| 695 |
+
>>> outputs = model(**inputs)
|
| 696 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 697 |
+
```
|
| 698 |
+
"""
|
| 699 |
+
|
| 700 |
+
overwrite_call_docstring(FlaxDinov2Model, FLAX_VISION_MODEL_DOCSTRING)
|
| 701 |
+
append_replace_return_docstrings(
|
| 702 |
+
FlaxDinov2Model, output_type=FlaxBaseModelOutputWithPooling, config_class=Dinov2Config
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
class FlaxDinov2ForImageClassificationModule(nn.Module):
|
| 707 |
+
config: Dinov2Config
|
| 708 |
+
dtype: jnp.dtype = jnp.float32
|
| 709 |
+
|
| 710 |
+
def setup(self):
|
| 711 |
+
self.dinov2 = FlaxDinov2Module(config=self.config, dtype=self.dtype)
|
| 712 |
+
self.classifier = nn.Dense(
|
| 713 |
+
self.config.num_labels,
|
| 714 |
+
dtype=self.dtype,
|
| 715 |
+
kernel_init=jax.nn.initializers.variance_scaling(
|
| 716 |
+
self.config.initializer_range**2, "fan_in", "truncated_normal"
|
| 717 |
+
),
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
def __call__(
|
| 721 |
+
self,
|
| 722 |
+
pixel_values=None,
|
| 723 |
+
deterministic: bool = True,
|
| 724 |
+
output_attentions=None,
|
| 725 |
+
output_hidden_states=None,
|
| 726 |
+
return_dict=None,
|
| 727 |
+
):
|
| 728 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 729 |
+
|
| 730 |
+
outputs = self.dinov2(
|
| 731 |
+
pixel_values,
|
| 732 |
+
deterministic=deterministic,
|
| 733 |
+
output_attentions=output_attentions,
|
| 734 |
+
output_hidden_states=output_hidden_states,
|
| 735 |
+
return_dict=return_dict,
|
| 736 |
+
)
|
| 737 |
+
|
| 738 |
+
hidden_states = outputs[0]
|
| 739 |
+
|
| 740 |
+
cls_token = hidden_states[:, 0]
|
| 741 |
+
patch_tokens = hidden_states[:, 1:]
|
| 742 |
+
linear_input = jnp.concatenate([cls_token, patch_tokens.mean(axis=1)], axis=-1)
|
| 743 |
+
|
| 744 |
+
logits = self.classifier(linear_input)
|
| 745 |
+
|
| 746 |
+
if not return_dict:
|
| 747 |
+
output = (logits,) + outputs[2:]
|
| 748 |
+
return output
|
| 749 |
+
|
| 750 |
+
return FlaxSequenceClassifierOutput(
|
| 751 |
+
logits=logits,
|
| 752 |
+
hidden_states=outputs.hidden_states,
|
| 753 |
+
attentions=outputs.attentions,
|
| 754 |
+
)
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
@add_start_docstrings(
|
| 758 |
+
"""
|
| 759 |
+
Dinov2 Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
|
| 760 |
+
the [CLS] token) e.g. for ImageNet.
|
| 761 |
+
""",
|
| 762 |
+
DINOV2_START_DOCSTRING,
|
| 763 |
+
)
|
| 764 |
+
class FlaxDinov2ForImageClassification(FlaxDinov2PreTrainedModel):
|
| 765 |
+
module_class = FlaxDinov2ForImageClassificationModule
|
| 766 |
+
|
| 767 |
+
|
| 768 |
+
FLAX_VISION_CLASSIFICATION_DOCSTRING = """
|
| 769 |
+
Returns:
|
| 770 |
+
|
| 771 |
+
Example:
|
| 772 |
+
|
| 773 |
+
```python
|
| 774 |
+
>>> from transformers import AutoImageProcessor, FlaxDinov2ForImageClassification
|
| 775 |
+
>>> from PIL import Image
|
| 776 |
+
>>> import jax
|
| 777 |
+
>>> import requests
|
| 778 |
+
|
| 779 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 780 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 781 |
+
|
| 782 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/dinov2-base-imagenet1k-1-layer")
|
| 783 |
+
>>> model = FlaxDinov2ForImageClassification.from_pretrained("facebook/dinov2-base-imagenet1k-1-layer", from_pt=True)
|
| 784 |
+
|
| 785 |
+
>>> inputs = image_processor(images=image, return_tensors="np")
|
| 786 |
+
>>> outputs = model(**inputs)
|
| 787 |
+
>>> logits = outputs.logits
|
| 788 |
+
|
| 789 |
+
>>> # model predicts one of the 1000 ImageNet classes
|
| 790 |
+
>>> predicted_class_idx = jax.numpy.argmax(logits, axis=-1)
|
| 791 |
+
>>> print("Predicted class:", model.config.id2label[predicted_class_idx.item()])
|
| 792 |
+
```
|
| 793 |
+
"""
|
| 794 |
+
|
| 795 |
+
overwrite_call_docstring(FlaxDinov2ForImageClassification, FLAX_VISION_CLASSIFICATION_DOCSTRING)
|
| 796 |
+
append_replace_return_docstrings(
|
| 797 |
+
FlaxDinov2ForImageClassification, output_type=FlaxSequenceClassifierOutput, config_class=Dinov2Config
|
| 798 |
+
)
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
__all__ = ["FlaxDinov2ForImageClassification", "FlaxDinov2Model", "FlaxDinov2PreTrainedModel"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov2_with_registers/__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_dinov2_with_registers import *
|
| 22 |
+
from .modeling_dinov2_with_registers import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov2_with_registers/configuration_dinov2_with_registers.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
# This file was automatically generated from src/transformers/models/dinov2_with_registers/modular_dinov2_with_registers.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_dinov2_with_registers.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2024 Meta Inc. and the HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
#
|
| 11 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 12 |
+
# you may not use this file except in compliance with the License.
|
| 13 |
+
# You may obtain a copy of the License at
|
| 14 |
+
#
|
| 15 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 16 |
+
#
|
| 17 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 18 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 19 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 20 |
+
# See the License for the specific language governing permissions and
|
| 21 |
+
# limitations under the License.
|
| 22 |
+
|
| 23 |
+
from ...configuration_utils import PretrainedConfig
|
| 24 |
+
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class Dinov2WithRegistersConfig(BackboneConfigMixin, PretrainedConfig):
|
| 28 |
+
r"""
|
| 29 |
+
This is the configuration class to store the configuration of a [`Dinov2WithRegistersModel`]. It is used to instantiate an
|
| 30 |
+
Dinov2WithRegisters model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 31 |
+
with the defaults will yield a similar configuration to that of the DINOv2 with Registers
|
| 32 |
+
[facebook/dinov2-with-registers-base](https://huggingface.co/facebook/dinov2-with-registers-base) architecture.
|
| 33 |
+
|
| 34 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 35 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 39 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 40 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 41 |
+
Number of hidden layers in the Transformer encoder.
|
| 42 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 43 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 44 |
+
mlp_ratio (`int`, *optional*, defaults to 4):
|
| 45 |
+
Ratio of the hidden size of the MLPs relative to the `hidden_size`.
|
| 46 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 47 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 48 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 49 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 50 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 51 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 52 |
+
The dropout ratio for the attention probabilities.
|
| 53 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 54 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 55 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 56 |
+
The epsilon used by the layer normalization layers.
|
| 57 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 58 |
+
The size (resolution) of each image.
|
| 59 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 60 |
+
The size (resolution) of each patch.
|
| 61 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 62 |
+
The number of input channels.
|
| 63 |
+
qkv_bias (`bool`, *optional*, defaults to `True`):
|
| 64 |
+
Whether to add a bias to the queries, keys and values.
|
| 65 |
+
layerscale_value (`float`, *optional*, defaults to 1.0):
|
| 66 |
+
Initial value to use for layer scale.
|
| 67 |
+
drop_path_rate (`float`, *optional*, defaults to 0.0):
|
| 68 |
+
Stochastic depth rate per sample (when applied in the main path of residual layers).
|
| 69 |
+
use_swiglu_ffn (`bool`, *optional*, defaults to `False`):
|
| 70 |
+
Whether to use the SwiGLU feedforward neural network.
|
| 71 |
+
num_register_tokens (`int`, *optional*, defaults to 4):
|
| 72 |
+
Number of register tokens to use.
|
| 73 |
+
out_features (`list[str]`, *optional*):
|
| 74 |
+
If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
|
| 75 |
+
(depending on how many stages the model has). If unset and `out_indices` is set, will default to the
|
| 76 |
+
corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
|
| 77 |
+
same order as defined in the `stage_names` attribute.
|
| 78 |
+
out_indices (`list[int]`, *optional*):
|
| 79 |
+
If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
|
| 80 |
+
many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
|
| 81 |
+
If unset and `out_features` is unset, will default to the last stage. Must be in the
|
| 82 |
+
same order as defined in the `stage_names` attribute.
|
| 83 |
+
apply_layernorm (`bool`, *optional*, defaults to `True`):
|
| 84 |
+
Whether to apply layer normalization to the feature maps in case the model is used as backbone.
|
| 85 |
+
reshape_hidden_states (`bool`, *optional*, defaults to `True`):
|
| 86 |
+
Whether to reshape the feature maps to 4D tensors of shape `(batch_size, hidden_size, height, width)` in
|
| 87 |
+
case the model is used as backbone. If `False`, the feature maps will be 3D tensors of shape `(batch_size,
|
| 88 |
+
seq_len, hidden_size)`.
|
| 89 |
+
|
| 90 |
+
Example:
|
| 91 |
+
|
| 92 |
+
```python
|
| 93 |
+
>>> from transformers import Dinov2WithRegistersConfig, Dinov2WithRegistersModel
|
| 94 |
+
|
| 95 |
+
>>> # Initializing a Dinov2WithRegisters base style configuration
|
| 96 |
+
>>> configuration = Dinov2WithRegistersConfig()
|
| 97 |
+
|
| 98 |
+
>>> # Initializing a model (with random weights) from the base style configuration
|
| 99 |
+
>>> model = Dinov2WithRegistersModel(configuration)
|
| 100 |
+
|
| 101 |
+
>>> # Accessing the model configuration
|
| 102 |
+
>>> configuration = model.config
|
| 103 |
+
```"""
|
| 104 |
+
|
| 105 |
+
model_type = "dinov2_with_registers"
|
| 106 |
+
|
| 107 |
+
def __init__(
|
| 108 |
+
self,
|
| 109 |
+
hidden_size=768,
|
| 110 |
+
num_hidden_layers=12,
|
| 111 |
+
num_attention_heads=12,
|
| 112 |
+
mlp_ratio=4,
|
| 113 |
+
hidden_act="gelu",
|
| 114 |
+
hidden_dropout_prob=0.0,
|
| 115 |
+
attention_probs_dropout_prob=0.0,
|
| 116 |
+
initializer_range=0.02,
|
| 117 |
+
layer_norm_eps=1e-6,
|
| 118 |
+
image_size=224,
|
| 119 |
+
patch_size=16,
|
| 120 |
+
num_channels=3,
|
| 121 |
+
qkv_bias=True,
|
| 122 |
+
layerscale_value=1.0,
|
| 123 |
+
drop_path_rate=0.0,
|
| 124 |
+
use_swiglu_ffn=False,
|
| 125 |
+
num_register_tokens=4,
|
| 126 |
+
out_features=None,
|
| 127 |
+
out_indices=None,
|
| 128 |
+
apply_layernorm=True,
|
| 129 |
+
reshape_hidden_states=True,
|
| 130 |
+
**kwargs,
|
| 131 |
+
):
|
| 132 |
+
super().__init__(**kwargs)
|
| 133 |
+
|
| 134 |
+
self.hidden_size = hidden_size
|
| 135 |
+
self.num_hidden_layers = num_hidden_layers
|
| 136 |
+
self.num_attention_heads = num_attention_heads
|
| 137 |
+
self.mlp_ratio = mlp_ratio
|
| 138 |
+
self.hidden_act = hidden_act
|
| 139 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 140 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 141 |
+
self.initializer_range = initializer_range
|
| 142 |
+
self.layer_norm_eps = layer_norm_eps
|
| 143 |
+
self.image_size = image_size
|
| 144 |
+
self.patch_size = patch_size
|
| 145 |
+
self.num_channels = num_channels
|
| 146 |
+
self.qkv_bias = qkv_bias
|
| 147 |
+
self.layerscale_value = layerscale_value
|
| 148 |
+
self.drop_path_rate = drop_path_rate
|
| 149 |
+
self.use_swiglu_ffn = use_swiglu_ffn
|
| 150 |
+
self.num_register_tokens = num_register_tokens
|
| 151 |
+
self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, num_hidden_layers + 1)]
|
| 152 |
+
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
|
| 153 |
+
out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
|
| 154 |
+
)
|
| 155 |
+
self.apply_layernorm = apply_layernorm
|
| 156 |
+
self.reshape_hidden_states = reshape_hidden_states
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
__all__ = ["Dinov2WithRegistersConfig"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov2_with_registers/convert_dinov2_with_registers_to_hf.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert DINOv2 with Registers checkpoints from the original repository.
|
| 16 |
+
|
| 17 |
+
URL: https://github.com/facebookresearch/dinov2/tree/main
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import json
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
import requests
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
from huggingface_hub import hf_hub_download
|
| 28 |
+
from PIL import Image
|
| 29 |
+
from torchvision import transforms
|
| 30 |
+
|
| 31 |
+
from transformers import (
|
| 32 |
+
BitImageProcessor,
|
| 33 |
+
Dinov2WithRegistersConfig,
|
| 34 |
+
Dinov2WithRegistersForImageClassification,
|
| 35 |
+
Dinov2WithRegistersModel,
|
| 36 |
+
)
|
| 37 |
+
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling
|
| 38 |
+
from transformers.utils import logging
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
logging.set_verbosity_info()
|
| 42 |
+
logger = logging.get_logger(__name__)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def get_dinov2_with_registers_config(model_name, image_classifier=False):
|
| 46 |
+
config = Dinov2WithRegistersConfig(image_size=518, patch_size=14)
|
| 47 |
+
|
| 48 |
+
# size of the architecture
|
| 49 |
+
if "vits" in model_name:
|
| 50 |
+
config.hidden_size = 384
|
| 51 |
+
config.num_attention_heads = 6
|
| 52 |
+
elif "vitb" in model_name:
|
| 53 |
+
pass
|
| 54 |
+
elif "vitl" in model_name:
|
| 55 |
+
config.hidden_size = 1024
|
| 56 |
+
config.num_hidden_layers = 24
|
| 57 |
+
config.num_attention_heads = 16
|
| 58 |
+
elif "vitg" in model_name:
|
| 59 |
+
config.use_swiglu_ffn = True
|
| 60 |
+
config.hidden_size = 1536
|
| 61 |
+
config.num_hidden_layers = 40
|
| 62 |
+
config.num_attention_heads = 24
|
| 63 |
+
else:
|
| 64 |
+
raise ValueError("Model not supported")
|
| 65 |
+
|
| 66 |
+
if image_classifier:
|
| 67 |
+
repo_id = "huggingface/label-files"
|
| 68 |
+
filename = "imagenet-1k-id2label.json"
|
| 69 |
+
config.num_labels = 1000
|
| 70 |
+
config.id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
|
| 71 |
+
config.id2label = {int(k): v for k, v in config.id2label.items()}
|
| 72 |
+
|
| 73 |
+
return config
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def create_rename_keys(config):
|
| 77 |
+
rename_keys = []
|
| 78 |
+
# fmt: off
|
| 79 |
+
|
| 80 |
+
# patch embedding layer
|
| 81 |
+
rename_keys.append(("cls_token", "embeddings.cls_token"))
|
| 82 |
+
rename_keys.append(("mask_token", "embeddings.mask_token"))
|
| 83 |
+
rename_keys.append(("pos_embed", "embeddings.position_embeddings"))
|
| 84 |
+
rename_keys.append(("register_tokens", "embeddings.register_tokens"))
|
| 85 |
+
rename_keys.append(("patch_embed.proj.weight", "embeddings.patch_embeddings.projection.weight"))
|
| 86 |
+
rename_keys.append(("patch_embed.proj.bias", "embeddings.patch_embeddings.projection.bias"))
|
| 87 |
+
|
| 88 |
+
for i in range(config.num_hidden_layers):
|
| 89 |
+
# layernorms
|
| 90 |
+
rename_keys.append((f"blocks.{i}.norm1.weight", f"encoder.layer.{i}.norm1.weight"))
|
| 91 |
+
rename_keys.append((f"blocks.{i}.norm1.bias", f"encoder.layer.{i}.norm1.bias"))
|
| 92 |
+
rename_keys.append((f"blocks.{i}.norm2.weight", f"encoder.layer.{i}.norm2.weight"))
|
| 93 |
+
rename_keys.append((f"blocks.{i}.norm2.bias", f"encoder.layer.{i}.norm2.bias"))
|
| 94 |
+
# MLP
|
| 95 |
+
if config.use_swiglu_ffn:
|
| 96 |
+
rename_keys.append((f"blocks.{i}.mlp.w12.weight", f"encoder.layer.{i}.mlp.w12.weight"))
|
| 97 |
+
rename_keys.append((f"blocks.{i}.mlp.w12.bias", f"encoder.layer.{i}.mlp.w12.bias"))
|
| 98 |
+
rename_keys.append((f"blocks.{i}.mlp.w3.weight", f"encoder.layer.{i}.mlp.w3.weight"))
|
| 99 |
+
rename_keys.append((f"blocks.{i}.mlp.w3.bias", f"encoder.layer.{i}.mlp.w3.bias"))
|
| 100 |
+
else:
|
| 101 |
+
rename_keys.append((f"blocks.{i}.mlp.fc1.weight", f"encoder.layer.{i}.mlp.fc1.weight"))
|
| 102 |
+
rename_keys.append((f"blocks.{i}.mlp.fc1.bias", f"encoder.layer.{i}.mlp.fc1.bias"))
|
| 103 |
+
rename_keys.append((f"blocks.{i}.mlp.fc2.weight", f"encoder.layer.{i}.mlp.fc2.weight"))
|
| 104 |
+
rename_keys.append((f"blocks.{i}.mlp.fc2.bias", f"encoder.layer.{i}.mlp.fc2.bias"))
|
| 105 |
+
# layerscale
|
| 106 |
+
rename_keys.append((f"blocks.{i}.ls1.gamma", f"encoder.layer.{i}.layer_scale1.lambda1"))
|
| 107 |
+
rename_keys.append((f"blocks.{i}.ls2.gamma", f"encoder.layer.{i}.layer_scale2.lambda1"))
|
| 108 |
+
# attention projection layer
|
| 109 |
+
rename_keys.append((f"blocks.{i}.attn.proj.weight", f"encoder.layer.{i}.attention.output.dense.weight"))
|
| 110 |
+
rename_keys.append((f"blocks.{i}.attn.proj.bias", f"encoder.layer.{i}.attention.output.dense.bias"))
|
| 111 |
+
|
| 112 |
+
# final layernorm
|
| 113 |
+
rename_keys.append(("norm.weight", "layernorm.weight"))
|
| 114 |
+
rename_keys.append(("norm.bias", "layernorm.bias"))
|
| 115 |
+
|
| 116 |
+
# fmt: on
|
| 117 |
+
return rename_keys
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def rename_key(dct, old, new):
|
| 121 |
+
val = dct.pop(old)
|
| 122 |
+
dct[new] = val
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# we split up the matrix of each encoder layer into queries, keys and values
|
| 126 |
+
def read_in_q_k_v(state_dict, config):
|
| 127 |
+
for i in range(config.num_hidden_layers):
|
| 128 |
+
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
|
| 129 |
+
in_proj_weight = state_dict.pop(f"blocks.{i}.attn.qkv.weight")
|
| 130 |
+
in_proj_bias = state_dict.pop(f"blocks.{i}.attn.qkv.bias")
|
| 131 |
+
# next, add query, keys and values (in that order) to the state dict
|
| 132 |
+
state_dict[f"encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[: config.hidden_size, :]
|
| 133 |
+
state_dict[f"encoder.layer.{i}.attention.attention.query.bias"] = in_proj_bias[: config.hidden_size]
|
| 134 |
+
state_dict[f"encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[
|
| 135 |
+
config.hidden_size : config.hidden_size * 2, :
|
| 136 |
+
]
|
| 137 |
+
state_dict[f"encoder.layer.{i}.attention.attention.key.bias"] = in_proj_bias[
|
| 138 |
+
config.hidden_size : config.hidden_size * 2
|
| 139 |
+
]
|
| 140 |
+
state_dict[f"encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[-config.hidden_size :, :]
|
| 141 |
+
state_dict[f"encoder.layer.{i}.attention.attention.value.bias"] = in_proj_bias[-config.hidden_size :]
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# We will verify our results on an image of cute cats
|
| 145 |
+
def prepare_img():
|
| 146 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 147 |
+
image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
|
| 148 |
+
return image
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@torch.no_grad()
|
| 152 |
+
def convert_dinov2_with_registers_checkpoint(model_name, pytorch_dump_folder_path, push_to_hub=False):
|
| 153 |
+
"""
|
| 154 |
+
Copy/paste/tweak model's weights to our Dinov2WithRegisters structure.
|
| 155 |
+
"""
|
| 156 |
+
|
| 157 |
+
# define default Dinov2WithRegisters configuration
|
| 158 |
+
image_classifier = "1layer" in model_name
|
| 159 |
+
config = get_dinov2_with_registers_config(model_name, image_classifier=image_classifier)
|
| 160 |
+
|
| 161 |
+
# load original model from torch hub
|
| 162 |
+
original_model = torch.hub.load("facebookresearch/dinov2", model_name.replace("_1layer", ""))
|
| 163 |
+
original_model.eval()
|
| 164 |
+
|
| 165 |
+
# load state_dict of original model, remove and rename some keys
|
| 166 |
+
state_dict = original_model.state_dict()
|
| 167 |
+
rename_keys = create_rename_keys(config)
|
| 168 |
+
for src, dest in rename_keys:
|
| 169 |
+
rename_key(state_dict, src, dest)
|
| 170 |
+
read_in_q_k_v(state_dict, config)
|
| 171 |
+
|
| 172 |
+
for key, val in state_dict.copy().items():
|
| 173 |
+
val = state_dict.pop(key)
|
| 174 |
+
if "w12" in key:
|
| 175 |
+
key = key.replace("w12", "weights_in")
|
| 176 |
+
if "w3" in key:
|
| 177 |
+
key = key.replace("w3", "weights_out")
|
| 178 |
+
state_dict[key] = val
|
| 179 |
+
|
| 180 |
+
# load HuggingFace model
|
| 181 |
+
if image_classifier:
|
| 182 |
+
model = Dinov2WithRegistersForImageClassification(config).eval()
|
| 183 |
+
model.dinov2_with_registers.load_state_dict(state_dict)
|
| 184 |
+
model_name_to_classifier_dict_url = {
|
| 185 |
+
"dinov2_vits14_reg_1layer": "https://dl.fbaipublicfiles.com/dinov2/dinov2_vits14/dinov2_vits14_reg4_linear_head.pth",
|
| 186 |
+
"dinov2_vitb14_reg_1layer": "https://dl.fbaipublicfiles.com/dinov2/dinov2_vitb14/dinov2_vitb14_reg4_linear_head.pth",
|
| 187 |
+
"dinov2_vitl14_reg_1layer": "https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_reg4_linear_head.pth",
|
| 188 |
+
"dinov2_vitg14_reg_1layer": "https://dl.fbaipublicfiles.com/dinov2/dinov2_vitg14/dinov2_vitg14_reg4_linear_head.pth",
|
| 189 |
+
}
|
| 190 |
+
url = model_name_to_classifier_dict_url[model_name]
|
| 191 |
+
classifier_state_dict = torch.hub.load_state_dict_from_url(url, map_location="cpu")
|
| 192 |
+
model.classifier.weight = nn.Parameter(classifier_state_dict["weight"])
|
| 193 |
+
model.classifier.bias = nn.Parameter(classifier_state_dict["bias"])
|
| 194 |
+
else:
|
| 195 |
+
model = Dinov2WithRegistersModel(config).eval()
|
| 196 |
+
model.load_state_dict(state_dict)
|
| 197 |
+
|
| 198 |
+
# load image
|
| 199 |
+
image = prepare_img()
|
| 200 |
+
|
| 201 |
+
# preprocess image
|
| 202 |
+
transformations = transforms.Compose(
|
| 203 |
+
[
|
| 204 |
+
transforms.Resize(256, interpolation=transforms.InterpolationMode.BICUBIC),
|
| 205 |
+
transforms.CenterCrop(224),
|
| 206 |
+
transforms.ToTensor(),
|
| 207 |
+
transforms.Normalize(
|
| 208 |
+
mean=IMAGENET_DEFAULT_MEAN, # these are RGB mean+std values
|
| 209 |
+
std=IMAGENET_DEFAULT_STD, # across a large photo dataset.
|
| 210 |
+
),
|
| 211 |
+
]
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
original_pixel_values = transformations(image).unsqueeze(0) # insert batch dimension
|
| 215 |
+
|
| 216 |
+
processor = BitImageProcessor(
|
| 217 |
+
size={"shortest_edge": 256},
|
| 218 |
+
resample=PILImageResampling.BICUBIC,
|
| 219 |
+
image_mean=IMAGENET_DEFAULT_MEAN,
|
| 220 |
+
image_std=IMAGENET_DEFAULT_STD,
|
| 221 |
+
)
|
| 222 |
+
pixel_values = processor(image, return_tensors="pt").pixel_values
|
| 223 |
+
|
| 224 |
+
assert torch.allclose(original_pixel_values, pixel_values)
|
| 225 |
+
|
| 226 |
+
with torch.no_grad():
|
| 227 |
+
outputs = model(pixel_values, output_hidden_states=True)
|
| 228 |
+
original_outputs = original_model(pixel_values)
|
| 229 |
+
|
| 230 |
+
# assert values
|
| 231 |
+
if image_classifier:
|
| 232 |
+
print("Predicted class:")
|
| 233 |
+
class_idx = outputs.logits.argmax(-1).item()
|
| 234 |
+
print(model.config.id2label[class_idx])
|
| 235 |
+
else:
|
| 236 |
+
assert outputs.last_hidden_state[:, 0].shape == original_outputs.shape
|
| 237 |
+
assert torch.allclose(outputs.last_hidden_state[:, 0], original_outputs, atol=1e-3)
|
| 238 |
+
print("Looks ok!")
|
| 239 |
+
|
| 240 |
+
if pytorch_dump_folder_path is not None:
|
| 241 |
+
Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
|
| 242 |
+
print(f"Saving model {model_name} to {pytorch_dump_folder_path}")
|
| 243 |
+
model.save_pretrained(pytorch_dump_folder_path)
|
| 244 |
+
print(f"Saving image processor to {pytorch_dump_folder_path}")
|
| 245 |
+
processor.save_pretrained(pytorch_dump_folder_path)
|
| 246 |
+
|
| 247 |
+
if push_to_hub:
|
| 248 |
+
model_name_to_hf_name = {
|
| 249 |
+
"dinov2_vits14_reg": "dinov2-with-registers-small",
|
| 250 |
+
"dinov2_vitb14_reg": "dinov2-with-registers-base",
|
| 251 |
+
"dinov2_vitl14_reg": "dinov2-with-registers-large",
|
| 252 |
+
"dinov2_vitg14_reg": "dinov2-with-registers-giant",
|
| 253 |
+
"dinov2_vits14_reg_1layer": "dinov2-with-registers-small-imagenet1k-1-layer",
|
| 254 |
+
"dinov2_vitb14_reg_1layer": "dinov2-with-registers-base-imagenet1k-1-layer",
|
| 255 |
+
"dinov2_vitl14_reg_1layer": "dinov2-with-registers-large-imagenet1k-1-layer",
|
| 256 |
+
"dinov2_vitg14_reg_1layer": "dinov2-with-registers-giant-imagenet1k-1-layer",
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
name = model_name_to_hf_name[model_name]
|
| 260 |
+
model.push_to_hub(f"nielsr/{name}")
|
| 261 |
+
processor.push_to_hub(f"nielsr/{name}")
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
if __name__ == "__main__":
|
| 265 |
+
parser = argparse.ArgumentParser()
|
| 266 |
+
# Required parameters
|
| 267 |
+
parser.add_argument(
|
| 268 |
+
"--model_name",
|
| 269 |
+
default="dinov2_vits14_reg",
|
| 270 |
+
type=str,
|
| 271 |
+
choices=[
|
| 272 |
+
"dinov2_vits14_reg",
|
| 273 |
+
"dinov2_vitb14_reg",
|
| 274 |
+
"dinov2_vitl14_reg",
|
| 275 |
+
"dinov2_vitg14_reg",
|
| 276 |
+
"dinov2_vits14_reg_1layer",
|
| 277 |
+
"dinov2_vitb14_reg_1layer",
|
| 278 |
+
"dinov2_vitl14_reg_1layer",
|
| 279 |
+
"dinov2_vitg14_reg_1layer",
|
| 280 |
+
],
|
| 281 |
+
help="Name of the model you'd like to convert.",
|
| 282 |
+
)
|
| 283 |
+
parser.add_argument(
|
| 284 |
+
"--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
|
| 285 |
+
)
|
| 286 |
+
parser.add_argument(
|
| 287 |
+
"--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
args = parser.parse_args()
|
| 291 |
+
convert_dinov2_with_registers_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py
ADDED
|
@@ -0,0 +1,832 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/dinov2_with_registers/modular_dinov2_with_registers.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_dinov2_with_registers.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2024 Meta Inc. and the HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
#
|
| 11 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 12 |
+
# you may not use this file except in compliance with the License.
|
| 13 |
+
# You may obtain a copy of the License at
|
| 14 |
+
#
|
| 15 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 16 |
+
#
|
| 17 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 18 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 19 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 20 |
+
# See the License for the specific language governing permissions and
|
| 21 |
+
# limitations under the License.
|
| 22 |
+
|
| 23 |
+
import collections.abc
|
| 24 |
+
from typing import Callable, Optional, Union
|
| 25 |
+
|
| 26 |
+
import torch
|
| 27 |
+
from torch import nn
|
| 28 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 29 |
+
|
| 30 |
+
from ...activations import ACT2FN
|
| 31 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 32 |
+
from ...modeling_outputs import BackboneOutput, BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
|
| 33 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 34 |
+
from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
|
| 35 |
+
from ...utils import auto_docstring, logging, torch_int
|
| 36 |
+
from ...utils.backbone_utils import BackboneMixin
|
| 37 |
+
from .configuration_dinov2_with_registers import Dinov2WithRegistersConfig
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
logger = logging.get_logger(__name__)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class Dinov2WithRegistersPatchEmbeddings(nn.Module):
|
| 44 |
+
"""
|
| 45 |
+
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
| 46 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
| 47 |
+
Transformer.
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
def __init__(self, config):
|
| 51 |
+
super().__init__()
|
| 52 |
+
image_size, patch_size = config.image_size, config.patch_size
|
| 53 |
+
num_channels, hidden_size = config.num_channels, config.hidden_size
|
| 54 |
+
|
| 55 |
+
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
|
| 56 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 57 |
+
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 58 |
+
self.image_size = image_size
|
| 59 |
+
self.patch_size = patch_size
|
| 60 |
+
self.num_channels = num_channels
|
| 61 |
+
self.num_patches = num_patches
|
| 62 |
+
|
| 63 |
+
self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
|
| 64 |
+
|
| 65 |
+
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
|
| 66 |
+
num_channels = pixel_values.shape[1]
|
| 67 |
+
if num_channels != self.num_channels:
|
| 68 |
+
raise ValueError(
|
| 69 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 70 |
+
f" Expected {self.num_channels} but got {num_channels}."
|
| 71 |
+
)
|
| 72 |
+
embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
|
| 73 |
+
return embeddings
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class Dinov2WithRegistersEmbeddings(nn.Module):
|
| 77 |
+
"""
|
| 78 |
+
Construct the CLS token, mask token, register tokens, position and patch embeddings.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
def __init__(self, config: Dinov2WithRegistersConfig) -> None:
|
| 82 |
+
super().__init__()
|
| 83 |
+
|
| 84 |
+
self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
| 85 |
+
self.mask_token = nn.Parameter(torch.zeros(1, config.hidden_size))
|
| 86 |
+
self.register_tokens = nn.Parameter(torch.zeros(1, config.num_register_tokens, config.hidden_size))
|
| 87 |
+
self.patch_embeddings = Dinov2WithRegistersPatchEmbeddings(config)
|
| 88 |
+
num_patches = self.patch_embeddings.num_patches
|
| 89 |
+
self.position_embeddings = nn.Parameter(torch.randn(1, num_patches + 1, config.hidden_size))
|
| 90 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 91 |
+
self.patch_size = config.patch_size
|
| 92 |
+
self.config = config
|
| 93 |
+
|
| 94 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 95 |
+
"""
|
| 96 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
|
| 97 |
+
resolution images. This implementation supports torch.jit tracing while maintaining backwards compatibility
|
| 98 |
+
with the original implementation.
|
| 99 |
+
|
| 100 |
+
Adapted from:
|
| 101 |
+
- https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
|
| 102 |
+
- https://github.com/facebookresearch/dinov2/blob/main/dinov2/models/vision_transformer.py
|
| 103 |
+
"""
|
| 104 |
+
num_patches = embeddings.shape[1] - 1
|
| 105 |
+
num_positions = self.position_embeddings.shape[1] - 1
|
| 106 |
+
|
| 107 |
+
# Skip interpolation for matching dimensions (unless tracing)
|
| 108 |
+
if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
|
| 109 |
+
return self.position_embeddings
|
| 110 |
+
|
| 111 |
+
# Handle class token and patch embeddings separately
|
| 112 |
+
class_pos_embed = self.position_embeddings[:, 0]
|
| 113 |
+
patch_pos_embed = self.position_embeddings[:, 1:]
|
| 114 |
+
dim = embeddings.shape[-1]
|
| 115 |
+
|
| 116 |
+
# Calculate new dimensions
|
| 117 |
+
height = height // self.config.patch_size
|
| 118 |
+
width = width // self.config.patch_size
|
| 119 |
+
|
| 120 |
+
# Reshape for interpolation
|
| 121 |
+
sqrt_num_positions = torch_int(num_positions**0.5)
|
| 122 |
+
patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
|
| 123 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 124 |
+
|
| 125 |
+
# Store original dtype for restoration after interpolation
|
| 126 |
+
target_dtype = patch_pos_embed.dtype
|
| 127 |
+
|
| 128 |
+
# Interpolate at float32 precision
|
| 129 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 130 |
+
patch_pos_embed.to(dtype=torch.float32),
|
| 131 |
+
size=(torch_int(height), torch_int(width)), # Explicit size instead of scale_factor
|
| 132 |
+
mode="bicubic",
|
| 133 |
+
align_corners=False,
|
| 134 |
+
antialias=True,
|
| 135 |
+
).to(dtype=target_dtype)
|
| 136 |
+
|
| 137 |
+
# Validate output dimensions if not tracing
|
| 138 |
+
if not torch.jit.is_tracing():
|
| 139 |
+
if int(height) != patch_pos_embed.shape[-2] or int(width) != patch_pos_embed.shape[-1]:
|
| 140 |
+
raise ValueError("Width or height does not match with the interpolated position embeddings")
|
| 141 |
+
|
| 142 |
+
# Reshape back to original format
|
| 143 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 144 |
+
|
| 145 |
+
# Combine class and patch embeddings
|
| 146 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
|
| 147 |
+
|
| 148 |
+
def forward(self, pixel_values: torch.Tensor, bool_masked_pos: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 149 |
+
batch_size, _, height, width = pixel_values.shape
|
| 150 |
+
target_dtype = self.patch_embeddings.projection.weight.dtype
|
| 151 |
+
embeddings = self.patch_embeddings(pixel_values.to(dtype=target_dtype))
|
| 152 |
+
|
| 153 |
+
if bool_masked_pos is not None:
|
| 154 |
+
embeddings = torch.where(
|
| 155 |
+
bool_masked_pos.unsqueeze(-1), self.mask_token.to(embeddings.dtype).unsqueeze(0), embeddings
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
# add the [CLS] token to the embedded patch tokens
|
| 159 |
+
cls_tokens = self.cls_token.expand(batch_size, -1, -1)
|
| 160 |
+
embeddings = torch.cat((cls_tokens, embeddings), dim=1)
|
| 161 |
+
|
| 162 |
+
# add positional encoding to each token
|
| 163 |
+
embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
|
| 164 |
+
|
| 165 |
+
# add register tokens
|
| 166 |
+
embeddings = torch.cat(
|
| 167 |
+
(embeddings[:, :1], self.register_tokens.expand(embeddings.shape[0], -1, -1), embeddings[:, 1:]), dim=1
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
embeddings = self.dropout(embeddings)
|
| 171 |
+
|
| 172 |
+
return embeddings
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def eager_attention_forward(
|
| 176 |
+
module: nn.Module,
|
| 177 |
+
query: torch.Tensor,
|
| 178 |
+
key: torch.Tensor,
|
| 179 |
+
value: torch.Tensor,
|
| 180 |
+
attention_mask: Optional[torch.Tensor],
|
| 181 |
+
scaling: float,
|
| 182 |
+
dropout: float = 0.0,
|
| 183 |
+
**kwargs,
|
| 184 |
+
):
|
| 185 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 186 |
+
attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
|
| 187 |
+
|
| 188 |
+
# Normalize the attention scores to probabilities.
|
| 189 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 190 |
+
|
| 191 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 192 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 193 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 194 |
+
|
| 195 |
+
# Mask heads if we want to
|
| 196 |
+
if attention_mask is not None:
|
| 197 |
+
attn_weights = attn_weights * attention_mask
|
| 198 |
+
|
| 199 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 200 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 201 |
+
|
| 202 |
+
return attn_output, attn_weights
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class Dinov2WithRegistersSelfAttention(nn.Module):
|
| 206 |
+
def __init__(self, config: Dinov2WithRegistersConfig) -> None:
|
| 207 |
+
super().__init__()
|
| 208 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 209 |
+
raise ValueError(
|
| 210 |
+
f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
|
| 211 |
+
f"heads {config.num_attention_heads}."
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
self.config = config
|
| 215 |
+
self.num_attention_heads = config.num_attention_heads
|
| 216 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 217 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 218 |
+
self.dropout_prob = config.attention_probs_dropout_prob
|
| 219 |
+
self.scaling = self.attention_head_size**-0.5
|
| 220 |
+
self.is_causal = False
|
| 221 |
+
|
| 222 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 223 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 224 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 225 |
+
|
| 226 |
+
def forward(
|
| 227 |
+
self,
|
| 228 |
+
hidden_states,
|
| 229 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 230 |
+
output_attentions: bool = False,
|
| 231 |
+
) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
|
| 232 |
+
batch_size, seq_length, _ = hidden_states.shape
|
| 233 |
+
key_layer = (
|
| 234 |
+
self.key(hidden_states)
|
| 235 |
+
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
|
| 236 |
+
.transpose(1, 2)
|
| 237 |
+
)
|
| 238 |
+
value_layer = (
|
| 239 |
+
self.value(hidden_states)
|
| 240 |
+
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
|
| 241 |
+
.transpose(1, 2)
|
| 242 |
+
)
|
| 243 |
+
query_layer = (
|
| 244 |
+
self.query(hidden_states)
|
| 245 |
+
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
|
| 246 |
+
.transpose(1, 2)
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
attention_interface: Callable = eager_attention_forward
|
| 250 |
+
if self.config._attn_implementation != "eager":
|
| 251 |
+
if self.config._attn_implementation == "sdpa" and output_attentions:
|
| 252 |
+
logger.warning_once(
|
| 253 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
| 254 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 255 |
+
)
|
| 256 |
+
else:
|
| 257 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 258 |
+
|
| 259 |
+
context_layer, attention_probs = attention_interface(
|
| 260 |
+
self,
|
| 261 |
+
query_layer,
|
| 262 |
+
key_layer,
|
| 263 |
+
value_layer,
|
| 264 |
+
head_mask,
|
| 265 |
+
is_causal=self.is_causal,
|
| 266 |
+
scaling=self.scaling,
|
| 267 |
+
dropout=0.0 if not self.training else self.dropout_prob,
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 271 |
+
context_layer = context_layer.reshape(new_context_layer_shape)
|
| 272 |
+
|
| 273 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 274 |
+
|
| 275 |
+
return outputs
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
class Dinov2WithRegistersSelfOutput(nn.Module):
|
| 279 |
+
"""
|
| 280 |
+
The residual connection is defined in Dinov2WithRegistersLayer instead of here (as is the case with other models), due to the
|
| 281 |
+
layernorm applied before each block.
|
| 282 |
+
"""
|
| 283 |
+
|
| 284 |
+
def __init__(self, config: Dinov2WithRegistersConfig) -> None:
|
| 285 |
+
super().__init__()
|
| 286 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 287 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 288 |
+
|
| 289 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 290 |
+
hidden_states = self.dense(hidden_states)
|
| 291 |
+
hidden_states = self.dropout(hidden_states)
|
| 292 |
+
|
| 293 |
+
return hidden_states
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
class Dinov2WithRegistersAttention(nn.Module):
|
| 297 |
+
def __init__(self, config: Dinov2WithRegistersConfig) -> None:
|
| 298 |
+
super().__init__()
|
| 299 |
+
self.attention = Dinov2WithRegistersSelfAttention(config)
|
| 300 |
+
self.output = Dinov2WithRegistersSelfOutput(config)
|
| 301 |
+
self.pruned_heads = set()
|
| 302 |
+
|
| 303 |
+
def prune_heads(self, heads: set[int]) -> None:
|
| 304 |
+
if len(heads) == 0:
|
| 305 |
+
return
|
| 306 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 307 |
+
heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
# Prune linear layers
|
| 311 |
+
self.attention.query = prune_linear_layer(self.attention.query, index)
|
| 312 |
+
self.attention.key = prune_linear_layer(self.attention.key, index)
|
| 313 |
+
self.attention.value = prune_linear_layer(self.attention.value, index)
|
| 314 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 315 |
+
|
| 316 |
+
# Update hyper params and store pruned heads
|
| 317 |
+
self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
|
| 318 |
+
self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
|
| 319 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 320 |
+
|
| 321 |
+
def forward(
|
| 322 |
+
self,
|
| 323 |
+
hidden_states: torch.Tensor,
|
| 324 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 325 |
+
output_attentions: bool = False,
|
| 326 |
+
) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
|
| 327 |
+
self_outputs = self.attention(hidden_states, head_mask, output_attentions)
|
| 328 |
+
|
| 329 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 330 |
+
|
| 331 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 332 |
+
return outputs
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
class Dinov2WithRegistersLayerScale(nn.Module):
|
| 336 |
+
def __init__(self, config) -> None:
|
| 337 |
+
super().__init__()
|
| 338 |
+
self.lambda1 = nn.Parameter(config.layerscale_value * torch.ones(config.hidden_size))
|
| 339 |
+
|
| 340 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 341 |
+
return hidden_state * self.lambda1
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
|
| 345 |
+
"""
|
| 346 |
+
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 347 |
+
|
| 348 |
+
Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
|
| 349 |
+
however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
|
| 350 |
+
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
|
| 351 |
+
layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
|
| 352 |
+
argument.
|
| 353 |
+
"""
|
| 354 |
+
if drop_prob == 0.0 or not training:
|
| 355 |
+
return input
|
| 356 |
+
keep_prob = 1 - drop_prob
|
| 357 |
+
shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 358 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
|
| 359 |
+
random_tensor.floor_() # binarize
|
| 360 |
+
output = input.div(keep_prob) * random_tensor
|
| 361 |
+
return output
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
class Dinov2WithRegistersDropPath(nn.Module):
|
| 365 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 366 |
+
|
| 367 |
+
def __init__(self, drop_prob: Optional[float] = None) -> None:
|
| 368 |
+
super().__init__()
|
| 369 |
+
self.drop_prob = drop_prob
|
| 370 |
+
|
| 371 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 372 |
+
return drop_path(hidden_states, self.drop_prob, self.training)
|
| 373 |
+
|
| 374 |
+
def extra_repr(self) -> str:
|
| 375 |
+
return f"p={self.drop_prob}"
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
class Dinov2WithRegistersMLP(nn.Module):
|
| 379 |
+
def __init__(self, config) -> None:
|
| 380 |
+
super().__init__()
|
| 381 |
+
in_features = out_features = config.hidden_size
|
| 382 |
+
hidden_features = int(config.hidden_size * config.mlp_ratio)
|
| 383 |
+
self.fc1 = nn.Linear(in_features, hidden_features, bias=True)
|
| 384 |
+
if isinstance(config.hidden_act, str):
|
| 385 |
+
self.activation = ACT2FN[config.hidden_act]
|
| 386 |
+
else:
|
| 387 |
+
self.activation = config.hidden_act
|
| 388 |
+
self.fc2 = nn.Linear(hidden_features, out_features, bias=True)
|
| 389 |
+
|
| 390 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 391 |
+
hidden_state = self.fc1(hidden_state)
|
| 392 |
+
hidden_state = self.activation(hidden_state)
|
| 393 |
+
hidden_state = self.fc2(hidden_state)
|
| 394 |
+
return hidden_state
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
class Dinov2WithRegistersSwiGLUFFN(nn.Module):
|
| 398 |
+
def __init__(self, config) -> None:
|
| 399 |
+
super().__init__()
|
| 400 |
+
in_features = out_features = config.hidden_size
|
| 401 |
+
hidden_features = int(config.hidden_size * config.mlp_ratio)
|
| 402 |
+
hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
|
| 403 |
+
|
| 404 |
+
self.weights_in = nn.Linear(in_features, 2 * hidden_features, bias=True)
|
| 405 |
+
self.weights_out = nn.Linear(hidden_features, out_features, bias=True)
|
| 406 |
+
|
| 407 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 408 |
+
hidden_state = self.weights_in(hidden_state)
|
| 409 |
+
x1, x2 = hidden_state.chunk(2, dim=-1)
|
| 410 |
+
hidden = nn.functional.silu(x1) * x2
|
| 411 |
+
return self.weights_out(hidden)
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
class Dinov2WithRegistersLayer(GradientCheckpointingLayer):
|
| 415 |
+
"""This corresponds to the Block class in the original implementation."""
|
| 416 |
+
|
| 417 |
+
def __init__(self, config: Dinov2WithRegistersConfig) -> None:
|
| 418 |
+
super().__init__()
|
| 419 |
+
|
| 420 |
+
self.norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 421 |
+
self.attention = Dinov2WithRegistersAttention(config)
|
| 422 |
+
self.layer_scale1 = Dinov2WithRegistersLayerScale(config)
|
| 423 |
+
self.drop_path = (
|
| 424 |
+
Dinov2WithRegistersDropPath(config.drop_path_rate) if config.drop_path_rate > 0.0 else nn.Identity()
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
self.norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 428 |
+
|
| 429 |
+
if config.use_swiglu_ffn:
|
| 430 |
+
self.mlp = Dinov2WithRegistersSwiGLUFFN(config)
|
| 431 |
+
else:
|
| 432 |
+
self.mlp = Dinov2WithRegistersMLP(config)
|
| 433 |
+
self.layer_scale2 = Dinov2WithRegistersLayerScale(config)
|
| 434 |
+
|
| 435 |
+
def forward(
|
| 436 |
+
self,
|
| 437 |
+
hidden_states: torch.Tensor,
|
| 438 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 439 |
+
output_attentions: bool = False,
|
| 440 |
+
) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
|
| 441 |
+
self_attention_outputs = self.attention(
|
| 442 |
+
self.norm1(hidden_states), # in Dinov2WithRegisters, layernorm is applied before self-attention
|
| 443 |
+
head_mask,
|
| 444 |
+
output_attentions=output_attentions,
|
| 445 |
+
)
|
| 446 |
+
attention_output = self_attention_outputs[0]
|
| 447 |
+
|
| 448 |
+
attention_output = self.layer_scale1(attention_output)
|
| 449 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 450 |
+
|
| 451 |
+
# first residual connection
|
| 452 |
+
hidden_states = self.drop_path(attention_output) + hidden_states
|
| 453 |
+
|
| 454 |
+
# in Dinov2WithRegisters, layernorm is also applied after self-attention
|
| 455 |
+
layer_output = self.norm2(hidden_states)
|
| 456 |
+
layer_output = self.mlp(layer_output)
|
| 457 |
+
layer_output = self.layer_scale2(layer_output)
|
| 458 |
+
|
| 459 |
+
# second residual connection
|
| 460 |
+
layer_output = self.drop_path(layer_output) + hidden_states
|
| 461 |
+
|
| 462 |
+
outputs = (layer_output,) + outputs
|
| 463 |
+
|
| 464 |
+
return outputs
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class Dinov2WithRegistersEncoder(nn.Module):
|
| 468 |
+
def __init__(self, config: Dinov2WithRegistersConfig) -> None:
|
| 469 |
+
super().__init__()
|
| 470 |
+
self.config = config
|
| 471 |
+
self.layer = nn.ModuleList([Dinov2WithRegistersLayer(config) for _ in range(config.num_hidden_layers)])
|
| 472 |
+
self.gradient_checkpointing = False
|
| 473 |
+
|
| 474 |
+
def forward(
|
| 475 |
+
self,
|
| 476 |
+
hidden_states: torch.Tensor,
|
| 477 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 478 |
+
output_attentions: bool = False,
|
| 479 |
+
output_hidden_states: bool = False,
|
| 480 |
+
return_dict: bool = True,
|
| 481 |
+
) -> Union[tuple, BaseModelOutput]:
|
| 482 |
+
all_hidden_states = () if output_hidden_states else None
|
| 483 |
+
all_self_attentions = () if output_attentions else None
|
| 484 |
+
|
| 485 |
+
for i, layer_module in enumerate(self.layer):
|
| 486 |
+
if output_hidden_states:
|
| 487 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 488 |
+
|
| 489 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 490 |
+
|
| 491 |
+
layer_outputs = layer_module(hidden_states, layer_head_mask, output_attentions)
|
| 492 |
+
|
| 493 |
+
hidden_states = layer_outputs[0]
|
| 494 |
+
|
| 495 |
+
if output_attentions:
|
| 496 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 497 |
+
|
| 498 |
+
if output_hidden_states:
|
| 499 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 500 |
+
|
| 501 |
+
if not return_dict:
|
| 502 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
|
| 503 |
+
return BaseModelOutput(
|
| 504 |
+
last_hidden_state=hidden_states,
|
| 505 |
+
hidden_states=all_hidden_states,
|
| 506 |
+
attentions=all_self_attentions,
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
@auto_docstring
|
| 511 |
+
class Dinov2WithRegistersPreTrainedModel(PreTrainedModel):
|
| 512 |
+
config: Dinov2WithRegistersConfig
|
| 513 |
+
base_model_prefix = "dinov2_with_registers"
|
| 514 |
+
main_input_name = "pixel_values"
|
| 515 |
+
supports_gradient_checkpointing = True
|
| 516 |
+
_no_split_modules = ["Dinov2WithRegistersLayer"]
|
| 517 |
+
_supports_sdpa = True
|
| 518 |
+
_supports_flash_attn = True
|
| 519 |
+
_supports_flex_attn = True
|
| 520 |
+
_supports_attention_backend = True
|
| 521 |
+
|
| 522 |
+
def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
|
| 523 |
+
"""Initialize the weights"""
|
| 524 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 525 |
+
# Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
|
| 526 |
+
# `trunc_normal_cpu` not implemented in `half` issues
|
| 527 |
+
module.weight.data = nn.init.trunc_normal_(
|
| 528 |
+
module.weight.data.to(torch.float32), mean=0.0, std=self.config.initializer_range
|
| 529 |
+
).to(module.weight.dtype)
|
| 530 |
+
if module.bias is not None:
|
| 531 |
+
module.bias.data.zero_()
|
| 532 |
+
elif isinstance(module, nn.LayerNorm):
|
| 533 |
+
module.bias.data.zero_()
|
| 534 |
+
module.weight.data.fill_(1.0)
|
| 535 |
+
elif isinstance(module, Dinov2WithRegistersEmbeddings):
|
| 536 |
+
module.position_embeddings.data = nn.init.trunc_normal_(
|
| 537 |
+
module.position_embeddings.data.to(torch.float32),
|
| 538 |
+
mean=0.0,
|
| 539 |
+
std=self.config.initializer_range,
|
| 540 |
+
).to(module.position_embeddings.dtype)
|
| 541 |
+
|
| 542 |
+
module.cls_token.data = nn.init.trunc_normal_(
|
| 543 |
+
module.cls_token.data.to(torch.float32),
|
| 544 |
+
mean=0.0,
|
| 545 |
+
std=self.config.initializer_range,
|
| 546 |
+
).to(module.cls_token.dtype)
|
| 547 |
+
|
| 548 |
+
module.mask_token.data.zero_()
|
| 549 |
+
module.register_tokens.data.zero_()
|
| 550 |
+
elif isinstance(module, Dinov2WithRegistersLayerScale): # noqa: F821
|
| 551 |
+
module.lambda1.data.fill_(self.config.layerscale_value)
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
@auto_docstring
|
| 555 |
+
class Dinov2WithRegistersModel(Dinov2WithRegistersPreTrainedModel):
|
| 556 |
+
def __init__(self, config: Dinov2WithRegistersConfig):
|
| 557 |
+
super().__init__(config)
|
| 558 |
+
self.config = config
|
| 559 |
+
|
| 560 |
+
self.embeddings = Dinov2WithRegistersEmbeddings(config)
|
| 561 |
+
self.encoder = Dinov2WithRegistersEncoder(config)
|
| 562 |
+
|
| 563 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 564 |
+
|
| 565 |
+
# Initialize weights and apply final processing
|
| 566 |
+
self.post_init()
|
| 567 |
+
|
| 568 |
+
def get_input_embeddings(self) -> Dinov2WithRegistersPatchEmbeddings:
|
| 569 |
+
return self.embeddings.patch_embeddings
|
| 570 |
+
|
| 571 |
+
def _prune_heads(self, heads_to_prune: dict[int, list[int]]) -> None:
|
| 572 |
+
"""
|
| 573 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 574 |
+
class PreTrainedModel
|
| 575 |
+
"""
|
| 576 |
+
for layer, heads in heads_to_prune.items():
|
| 577 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 578 |
+
|
| 579 |
+
@auto_docstring
|
| 580 |
+
def forward(
|
| 581 |
+
self,
|
| 582 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 583 |
+
bool_masked_pos: Optional[torch.Tensor] = None,
|
| 584 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 585 |
+
output_attentions: Optional[bool] = None,
|
| 586 |
+
output_hidden_states: Optional[bool] = None,
|
| 587 |
+
return_dict: Optional[bool] = None,
|
| 588 |
+
) -> Union[tuple, BaseModelOutputWithPooling]:
|
| 589 |
+
r"""
|
| 590 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
|
| 591 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0). Only relevant for
|
| 592 |
+
pre-training.
|
| 593 |
+
"""
|
| 594 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 595 |
+
output_hidden_states = (
|
| 596 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 597 |
+
)
|
| 598 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 599 |
+
|
| 600 |
+
if pixel_values is None:
|
| 601 |
+
raise ValueError("You have to specify pixel_values")
|
| 602 |
+
|
| 603 |
+
# Prepare head mask if needed
|
| 604 |
+
# 1.0 in head_mask indicate we keep the head
|
| 605 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 606 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 607 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 608 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 609 |
+
|
| 610 |
+
embedding_output = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
|
| 611 |
+
|
| 612 |
+
encoder_outputs = self.encoder(
|
| 613 |
+
embedding_output,
|
| 614 |
+
head_mask=head_mask,
|
| 615 |
+
output_attentions=output_attentions,
|
| 616 |
+
output_hidden_states=output_hidden_states,
|
| 617 |
+
return_dict=return_dict,
|
| 618 |
+
)
|
| 619 |
+
sequence_output = encoder_outputs[0]
|
| 620 |
+
sequence_output = self.layernorm(sequence_output)
|
| 621 |
+
pooled_output = sequence_output[:, 0, :]
|
| 622 |
+
|
| 623 |
+
if not return_dict:
|
| 624 |
+
head_outputs = (sequence_output, pooled_output)
|
| 625 |
+
return head_outputs + encoder_outputs[1:]
|
| 626 |
+
|
| 627 |
+
return BaseModelOutputWithPooling(
|
| 628 |
+
last_hidden_state=sequence_output,
|
| 629 |
+
pooler_output=pooled_output,
|
| 630 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 631 |
+
attentions=encoder_outputs.attentions,
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
@auto_docstring(
|
| 636 |
+
custom_intro="""
|
| 637 |
+
Dinov2WithRegisters Model transformer with an image classification head on top (a linear layer on top of the final hidden state
|
| 638 |
+
of the [CLS] token) e.g. for ImageNet.
|
| 639 |
+
"""
|
| 640 |
+
)
|
| 641 |
+
class Dinov2WithRegistersForImageClassification(Dinov2WithRegistersPreTrainedModel):
|
| 642 |
+
def __init__(self, config: Dinov2WithRegistersConfig) -> None:
|
| 643 |
+
super().__init__(config)
|
| 644 |
+
|
| 645 |
+
self.num_labels = config.num_labels
|
| 646 |
+
self.dinov2_with_registers = Dinov2WithRegistersModel(config)
|
| 647 |
+
|
| 648 |
+
# Classifier head
|
| 649 |
+
self.classifier = (
|
| 650 |
+
nn.Linear(config.hidden_size * 2, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 651 |
+
)
|
| 652 |
+
|
| 653 |
+
# Initialize weights and apply final processing
|
| 654 |
+
self.post_init()
|
| 655 |
+
|
| 656 |
+
@auto_docstring
|
| 657 |
+
def forward(
|
| 658 |
+
self,
|
| 659 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 660 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 661 |
+
labels: Optional[torch.Tensor] = None,
|
| 662 |
+
output_attentions: Optional[bool] = None,
|
| 663 |
+
output_hidden_states: Optional[bool] = None,
|
| 664 |
+
return_dict: Optional[bool] = None,
|
| 665 |
+
) -> Union[tuple, ImageClassifierOutput]:
|
| 666 |
+
r"""
|
| 667 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 668 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 669 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 670 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 671 |
+
"""
|
| 672 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 673 |
+
|
| 674 |
+
outputs = self.dinov2_with_registers(
|
| 675 |
+
pixel_values,
|
| 676 |
+
head_mask=head_mask,
|
| 677 |
+
output_attentions=output_attentions,
|
| 678 |
+
output_hidden_states=output_hidden_states,
|
| 679 |
+
return_dict=return_dict,
|
| 680 |
+
)
|
| 681 |
+
|
| 682 |
+
sequence_output = outputs[0] # batch_size, sequence_length, hidden_size
|
| 683 |
+
|
| 684 |
+
cls_token = sequence_output[:, 0]
|
| 685 |
+
# cls and register tokens should not be included in patch tokens variable
|
| 686 |
+
patch_tokens = sequence_output[:, 1 + self.config.num_register_tokens :]
|
| 687 |
+
|
| 688 |
+
linear_input = torch.cat([cls_token, patch_tokens.mean(dim=1)], dim=1)
|
| 689 |
+
|
| 690 |
+
logits = self.classifier(linear_input)
|
| 691 |
+
|
| 692 |
+
loss = None
|
| 693 |
+
if labels is not None:
|
| 694 |
+
# move labels to correct device to enable model parallelism
|
| 695 |
+
labels = labels.to(logits.device)
|
| 696 |
+
if self.config.problem_type is None:
|
| 697 |
+
if self.num_labels == 1:
|
| 698 |
+
self.config.problem_type = "regression"
|
| 699 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 700 |
+
self.config.problem_type = "single_label_classification"
|
| 701 |
+
else:
|
| 702 |
+
self.config.problem_type = "multi_label_classification"
|
| 703 |
+
|
| 704 |
+
if self.config.problem_type == "regression":
|
| 705 |
+
loss_fct = MSELoss()
|
| 706 |
+
if self.num_labels == 1:
|
| 707 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 708 |
+
else:
|
| 709 |
+
loss = loss_fct(logits, labels)
|
| 710 |
+
elif self.config.problem_type == "single_label_classification":
|
| 711 |
+
loss_fct = CrossEntropyLoss()
|
| 712 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 713 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 714 |
+
loss_fct = BCEWithLogitsLoss()
|
| 715 |
+
loss = loss_fct(logits, labels)
|
| 716 |
+
|
| 717 |
+
if not return_dict:
|
| 718 |
+
output = (logits,) + outputs[2:]
|
| 719 |
+
return ((loss,) + output) if loss is not None else output
|
| 720 |
+
|
| 721 |
+
return ImageClassifierOutput(
|
| 722 |
+
loss=loss,
|
| 723 |
+
logits=logits,
|
| 724 |
+
hidden_states=outputs.hidden_states,
|
| 725 |
+
attentions=outputs.attentions,
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
@auto_docstring(
|
| 730 |
+
custom_intro="""
|
| 731 |
+
Dinov2WithRegisters backbone, to be used with frameworks like DETR and MaskFormer.
|
| 732 |
+
"""
|
| 733 |
+
)
|
| 734 |
+
class Dinov2WithRegistersBackbone(Dinov2WithRegistersPreTrainedModel, BackboneMixin):
|
| 735 |
+
def __init__(self, config):
|
| 736 |
+
super().__init__(config)
|
| 737 |
+
super()._init_backbone(config)
|
| 738 |
+
self.num_features = [config.hidden_size for _ in range(config.num_hidden_layers + 1)]
|
| 739 |
+
self.embeddings = Dinov2WithRegistersEmbeddings(config)
|
| 740 |
+
self.encoder = Dinov2WithRegistersEncoder(config)
|
| 741 |
+
|
| 742 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 743 |
+
|
| 744 |
+
self.num_register_tokens = config.num_register_tokens
|
| 745 |
+
|
| 746 |
+
# Initialize weights and apply final processing
|
| 747 |
+
self.post_init()
|
| 748 |
+
|
| 749 |
+
def get_input_embeddings(self) -> Dinov2WithRegistersPatchEmbeddings:
|
| 750 |
+
return self.embeddings.patch_embeddings
|
| 751 |
+
|
| 752 |
+
@auto_docstring
|
| 753 |
+
def forward(
|
| 754 |
+
self,
|
| 755 |
+
pixel_values: torch.Tensor,
|
| 756 |
+
output_hidden_states: Optional[bool] = None,
|
| 757 |
+
output_attentions: Optional[bool] = None,
|
| 758 |
+
return_dict: Optional[bool] = None,
|
| 759 |
+
) -> BackboneOutput:
|
| 760 |
+
r"""
|
| 761 |
+
Examples:
|
| 762 |
+
|
| 763 |
+
```python
|
| 764 |
+
>>> from transformers import AutoImageProcessor, AutoBackbone
|
| 765 |
+
>>> import torch
|
| 766 |
+
>>> from PIL import Image
|
| 767 |
+
>>> import requests
|
| 768 |
+
|
| 769 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 770 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 771 |
+
|
| 772 |
+
>>> processor = AutoImageProcessor.from_pretrained("facebook/dinov2-with-registers-base")
|
| 773 |
+
>>> model = AutoBackbone.from_pretrained(
|
| 774 |
+
... "facebook/dinov2-with-registers-base", out_features=["stage2", "stage5", "stage8", "stage11"]
|
| 775 |
+
... )
|
| 776 |
+
|
| 777 |
+
>>> inputs = processor(image, return_tensors="pt")
|
| 778 |
+
|
| 779 |
+
>>> outputs = model(**inputs)
|
| 780 |
+
>>> feature_maps = outputs.feature_maps
|
| 781 |
+
>>> list(feature_maps[-1].shape)
|
| 782 |
+
[1, 768, 16, 16]
|
| 783 |
+
```"""
|
| 784 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 785 |
+
output_hidden_states = (
|
| 786 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 787 |
+
)
|
| 788 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 789 |
+
|
| 790 |
+
embedding_output = self.embeddings(pixel_values)
|
| 791 |
+
|
| 792 |
+
outputs = self.encoder(
|
| 793 |
+
embedding_output, output_hidden_states=True, output_attentions=output_attentions, return_dict=return_dict
|
| 794 |
+
)
|
| 795 |
+
|
| 796 |
+
hidden_states = outputs.hidden_states if return_dict else outputs[1]
|
| 797 |
+
|
| 798 |
+
feature_maps = ()
|
| 799 |
+
for stage, hidden_state in zip(self.stage_names, hidden_states):
|
| 800 |
+
if stage in self.out_features:
|
| 801 |
+
if self.config.apply_layernorm:
|
| 802 |
+
hidden_state = self.layernorm(hidden_state)
|
| 803 |
+
if self.config.reshape_hidden_states:
|
| 804 |
+
hidden_state = hidden_state[:, self.num_register_tokens + 1 :]
|
| 805 |
+
# this was actually a bug in the original implementation that we copied here,
|
| 806 |
+
# cause normally the order is height, width
|
| 807 |
+
batch_size, _, height, width = pixel_values.shape
|
| 808 |
+
patch_size = self.config.patch_size
|
| 809 |
+
hidden_state = hidden_state.reshape(batch_size, height // patch_size, width // patch_size, -1)
|
| 810 |
+
hidden_state = hidden_state.permute(0, 3, 1, 2).contiguous()
|
| 811 |
+
feature_maps += (hidden_state,)
|
| 812 |
+
|
| 813 |
+
if not return_dict:
|
| 814 |
+
if output_hidden_states:
|
| 815 |
+
output = (feature_maps,) + outputs[1:]
|
| 816 |
+
else:
|
| 817 |
+
output = (feature_maps,) + outputs[2:]
|
| 818 |
+
return output
|
| 819 |
+
|
| 820 |
+
return BackboneOutput(
|
| 821 |
+
feature_maps=feature_maps,
|
| 822 |
+
hidden_states=outputs.hidden_states if output_hidden_states else None,
|
| 823 |
+
attentions=outputs.attentions if output_attentions else None,
|
| 824 |
+
)
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
__all__ = [
|
| 828 |
+
"Dinov2WithRegistersPreTrainedModel",
|
| 829 |
+
"Dinov2WithRegistersModel",
|
| 830 |
+
"Dinov2WithRegistersForImageCl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
# coding=utf-8
|
| 2 |
+
# Copyright 2024 Meta Inc. and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
from typing import Optional, Union
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.utils.checkpoint
|
| 21 |
+
from torch import nn
|
| 22 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 23 |
+
|
| 24 |
+
from ....transformers.models.dinov2.modeling_dinov2 import (
|
| 25 |
+
Dinov2Backbone,
|
| 26 |
+
Dinov2Encoder,
|
| 27 |
+
Dinov2ForImageClassification,
|
| 28 |
+
Dinov2Model,
|
| 29 |
+
Dinov2PatchEmbeddings,
|
| 30 |
+
Dinov2PreTrainedModel,
|
| 31 |
+
)
|
| 32 |
+
from ...configuration_utils import PretrainedConfig
|
| 33 |
+
from ...modeling_outputs import BackboneOutput, ImageClassifierOutput
|
| 34 |
+
from ...utils import logging, torch_int
|
| 35 |
+
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
logger = logging.get_logger(__name__)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Dinov2WithRegistersConfig(BackboneConfigMixin, PretrainedConfig):
|
| 42 |
+
r"""
|
| 43 |
+
This is the configuration class to store the configuration of a [`Dinov2WithRegistersModel`]. It is used to instantiate an
|
| 44 |
+
Dinov2WithRegisters model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 45 |
+
with the defaults will yield a similar configuration to that of the DINOv2 with Registers
|
| 46 |
+
[facebook/dinov2-with-registers-base](https://huggingface.co/facebook/dinov2-with-registers-base) architecture.
|
| 47 |
+
|
| 48 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 49 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 53 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 54 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 55 |
+
Number of hidden layers in the Transformer encoder.
|
| 56 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 57 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 58 |
+
mlp_ratio (`int`, *optional*, defaults to 4):
|
| 59 |
+
Ratio of the hidden size of the MLPs relative to the `hidden_size`.
|
| 60 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 61 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 62 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 63 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 64 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 65 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 66 |
+
The dropout ratio for the attention probabilities.
|
| 67 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 68 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 69 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 70 |
+
The epsilon used by the layer normalization layers.
|
| 71 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 72 |
+
The size (resolution) of each image.
|
| 73 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 74 |
+
The size (resolution) of each patch.
|
| 75 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 76 |
+
The number of input channels.
|
| 77 |
+
qkv_bias (`bool`, *optional*, defaults to `True`):
|
| 78 |
+
Whether to add a bias to the queries, keys and values.
|
| 79 |
+
layerscale_value (`float`, *optional*, defaults to 1.0):
|
| 80 |
+
Initial value to use for layer scale.
|
| 81 |
+
drop_path_rate (`float`, *optional*, defaults to 0.0):
|
| 82 |
+
Stochastic depth rate per sample (when applied in the main path of residual layers).
|
| 83 |
+
use_swiglu_ffn (`bool`, *optional*, defaults to `False`):
|
| 84 |
+
Whether to use the SwiGLU feedforward neural network.
|
| 85 |
+
num_register_tokens (`int`, *optional*, defaults to 4):
|
| 86 |
+
Number of register tokens to use.
|
| 87 |
+
out_features (`list[str]`, *optional*):
|
| 88 |
+
If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
|
| 89 |
+
(depending on how many stages the model has). If unset and `out_indices` is set, will default to the
|
| 90 |
+
corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
|
| 91 |
+
same order as defined in the `stage_names` attribute.
|
| 92 |
+
out_indices (`list[int]`, *optional*):
|
| 93 |
+
If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
|
| 94 |
+
many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
|
| 95 |
+
If unset and `out_features` is unset, will default to the last stage. Must be in the
|
| 96 |
+
same order as defined in the `stage_names` attribute.
|
| 97 |
+
apply_layernorm (`bool`, *optional*, defaults to `True`):
|
| 98 |
+
Whether to apply layer normalization to the feature maps in case the model is used as backbone.
|
| 99 |
+
reshape_hidden_states (`bool`, *optional*, defaults to `True`):
|
| 100 |
+
Whether to reshape the feature maps to 4D tensors of shape `(batch_size, hidden_size, height, width)` in
|
| 101 |
+
case the model is used as backbone. If `False`, the feature maps will be 3D tensors of shape `(batch_size,
|
| 102 |
+
seq_len, hidden_size)`.
|
| 103 |
+
|
| 104 |
+
Example:
|
| 105 |
+
|
| 106 |
+
```python
|
| 107 |
+
>>> from transformers import Dinov2WithRegistersConfig, Dinov2WithRegistersModel
|
| 108 |
+
|
| 109 |
+
>>> # Initializing a Dinov2WithRegisters base style configuration
|
| 110 |
+
>>> configuration = Dinov2WithRegistersConfig()
|
| 111 |
+
|
| 112 |
+
>>> # Initializing a model (with random weights) from the base style configuration
|
| 113 |
+
>>> model = Dinov2WithRegistersModel(configuration)
|
| 114 |
+
|
| 115 |
+
>>> # Accessing the model configuration
|
| 116 |
+
>>> configuration = model.config
|
| 117 |
+
```"""
|
| 118 |
+
|
| 119 |
+
model_type = "dinov2_with_registers"
|
| 120 |
+
|
| 121 |
+
def __init__(
|
| 122 |
+
self,
|
| 123 |
+
hidden_size=768,
|
| 124 |
+
num_hidden_layers=12,
|
| 125 |
+
num_attention_heads=12,
|
| 126 |
+
mlp_ratio=4,
|
| 127 |
+
hidden_act="gelu",
|
| 128 |
+
hidden_dropout_prob=0.0,
|
| 129 |
+
attention_probs_dropout_prob=0.0,
|
| 130 |
+
initializer_range=0.02,
|
| 131 |
+
layer_norm_eps=1e-6,
|
| 132 |
+
image_size=224,
|
| 133 |
+
patch_size=16,
|
| 134 |
+
num_channels=3,
|
| 135 |
+
qkv_bias=True,
|
| 136 |
+
layerscale_value=1.0,
|
| 137 |
+
drop_path_rate=0.0,
|
| 138 |
+
use_swiglu_ffn=False,
|
| 139 |
+
num_register_tokens=4,
|
| 140 |
+
out_features=None,
|
| 141 |
+
out_indices=None,
|
| 142 |
+
apply_layernorm=True,
|
| 143 |
+
reshape_hidden_states=True,
|
| 144 |
+
**kwargs,
|
| 145 |
+
):
|
| 146 |
+
super().__init__(**kwargs)
|
| 147 |
+
|
| 148 |
+
self.hidden_size = hidden_size
|
| 149 |
+
self.num_hidden_layers = num_hidden_layers
|
| 150 |
+
self.num_attention_heads = num_attention_heads
|
| 151 |
+
self.mlp_ratio = mlp_ratio
|
| 152 |
+
self.hidden_act = hidden_act
|
| 153 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 154 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 155 |
+
self.initializer_range = initializer_range
|
| 156 |
+
self.layer_norm_eps = layer_norm_eps
|
| 157 |
+
self.image_size = image_size
|
| 158 |
+
self.patch_size = patch_size
|
| 159 |
+
self.num_channels = num_channels
|
| 160 |
+
self.qkv_bias = qkv_bias
|
| 161 |
+
self.layerscale_value = layerscale_value
|
| 162 |
+
self.drop_path_rate = drop_path_rate
|
| 163 |
+
self.use_swiglu_ffn = use_swiglu_ffn
|
| 164 |
+
self.num_register_tokens = num_register_tokens
|
| 165 |
+
self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, num_hidden_layers + 1)]
|
| 166 |
+
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
|
| 167 |
+
out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
|
| 168 |
+
)
|
| 169 |
+
self.apply_layernorm = apply_layernorm
|
| 170 |
+
self.reshape_hidden_states = reshape_hidden_states
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class Dinov2WithRegistersPatchEmbeddings(Dinov2PatchEmbeddings):
|
| 174 |
+
pass
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class Dinov2WithRegistersEmbeddings(nn.Module):
|
| 178 |
+
"""
|
| 179 |
+
Construct the CLS token, mask token, register tokens, position and patch embeddings.
|
| 180 |
+
"""
|
| 181 |
+
|
| 182 |
+
def __init__(self, config: Dinov2WithRegistersConfig) -> None:
|
| 183 |
+
super().__init__()
|
| 184 |
+
|
| 185 |
+
self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
| 186 |
+
self.mask_token = nn.Parameter(torch.zeros(1, config.hidden_size))
|
| 187 |
+
self.register_tokens = nn.Parameter(torch.zeros(1, config.num_register_tokens, config.hidden_size))
|
| 188 |
+
self.patch_embeddings = Dinov2WithRegistersPatchEmbeddings(config)
|
| 189 |
+
num_patches = self.patch_embeddings.num_patches
|
| 190 |
+
self.position_embeddings = nn.Parameter(torch.randn(1, num_patches + 1, config.hidden_size))
|
| 191 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 192 |
+
self.patch_size = config.patch_size
|
| 193 |
+
self.config = config
|
| 194 |
+
|
| 195 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 196 |
+
"""
|
| 197 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
|
| 198 |
+
resolution images. This implementation supports torch.jit tracing while maintaining backwards compatibility
|
| 199 |
+
with the original implementation.
|
| 200 |
+
|
| 201 |
+
Adapted from:
|
| 202 |
+
- https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
|
| 203 |
+
- https://github.com/facebookresearch/dinov2/blob/main/dinov2/models/vision_transformer.py
|
| 204 |
+
"""
|
| 205 |
+
num_patches = embeddings.shape[1] - 1
|
| 206 |
+
num_positions = self.position_embeddings.shape[1] - 1
|
| 207 |
+
|
| 208 |
+
# Skip interpolation for matching dimensions (unless tracing)
|
| 209 |
+
if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
|
| 210 |
+
return self.position_embeddings
|
| 211 |
+
|
| 212 |
+
# Handle class token and patch embeddings separately
|
| 213 |
+
class_pos_embed = self.position_embeddings[:, 0]
|
| 214 |
+
patch_pos_embed = self.position_embeddings[:, 1:]
|
| 215 |
+
dim = embeddings.shape[-1]
|
| 216 |
+
|
| 217 |
+
# Calculate new dimensions
|
| 218 |
+
height = height // self.config.patch_size
|
| 219 |
+
width = width // self.config.patch_size
|
| 220 |
+
|
| 221 |
+
# Reshape for interpolation
|
| 222 |
+
sqrt_num_positions = torch_int(num_positions**0.5)
|
| 223 |
+
patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
|
| 224 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 225 |
+
|
| 226 |
+
# Store original dtype for restoration after interpolation
|
| 227 |
+
target_dtype = patch_pos_embed.dtype
|
| 228 |
+
|
| 229 |
+
# Interpolate at float32 precision
|
| 230 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 231 |
+
patch_pos_embed.to(dtype=torch.float32),
|
| 232 |
+
size=(torch_int(height), torch_int(width)), # Explicit size instead of scale_factor
|
| 233 |
+
mode="bicubic",
|
| 234 |
+
align_corners=False,
|
| 235 |
+
antialias=True,
|
| 236 |
+
).to(dtype=target_dtype)
|
| 237 |
+
|
| 238 |
+
# Validate output dimensions if not tracing
|
| 239 |
+
if not torch.jit.is_tracing():
|
| 240 |
+
if int(height) != patch_pos_embed.shape[-2] or int(width) != patch_pos_embed.shape[-1]:
|
| 241 |
+
raise ValueError("Width or height does not match with the interpolated position embeddings")
|
| 242 |
+
|
| 243 |
+
# Reshape back to original format
|
| 244 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 245 |
+
|
| 246 |
+
# Combine class and patch embeddings
|
| 247 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
|
| 248 |
+
|
| 249 |
+
def forward(self, pixel_values: torch.Tensor, bool_masked_pos: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 250 |
+
batch_size, _, height, width = pixel_values.shape
|
| 251 |
+
target_dtype = self.patch_embeddings.projection.weight.dtype
|
| 252 |
+
embeddings = self.patch_embeddings(pixel_values.to(dtype=target_dtype))
|
| 253 |
+
|
| 254 |
+
if bool_masked_pos is not None:
|
| 255 |
+
embeddings = torch.where(
|
| 256 |
+
bool_masked_pos.unsqueeze(-1), self.mask_token.to(embeddings.dtype).unsqueeze(0), embeddings
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
# add the [CLS] token to the embedded patch tokens
|
| 260 |
+
cls_tokens = self.cls_token.expand(batch_size, -1, -1)
|
| 261 |
+
embeddings = torch.cat((cls_tokens, embeddings), dim=1)
|
| 262 |
+
|
| 263 |
+
# add positional encoding to each token
|
| 264 |
+
embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
|
| 265 |
+
|
| 266 |
+
# add register tokens
|
| 267 |
+
embeddings = torch.cat(
|
| 268 |
+
(embeddings[:, :1], self.register_tokens.expand(embeddings.shape[0], -1, -1), embeddings[:, 1:]), dim=1
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
embeddings = self.dropout(embeddings)
|
| 272 |
+
|
| 273 |
+
return embeddings
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class Dinov2WithRegistersEncoder(Dinov2Encoder):
|
| 277 |
+
pass
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
class Dinov2WithRegistersPreTrainedModel(Dinov2PreTrainedModel):
|
| 281 |
+
def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
|
| 282 |
+
"""Initialize the weights"""
|
| 283 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 284 |
+
# Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
|
| 285 |
+
# `trunc_normal_cpu` not implemented in `half` issues
|
| 286 |
+
module.weight.data = nn.init.trunc_normal_(
|
| 287 |
+
module.weight.data.to(torch.float32), mean=0.0, std=self.config.initializer_range
|
| 288 |
+
).to(module.weight.dtype)
|
| 289 |
+
if module.bias is not None:
|
| 290 |
+
module.bias.data.zero_()
|
| 291 |
+
elif isinstance(module, nn.LayerNorm):
|
| 292 |
+
module.bias.data.zero_()
|
| 293 |
+
module.weight.data.fill_(1.0)
|
| 294 |
+
elif isinstance(module, Dinov2WithRegistersEmbeddings):
|
| 295 |
+
module.position_embeddings.data = nn.init.trunc_normal_(
|
| 296 |
+
module.position_embeddings.data.to(torch.float32),
|
| 297 |
+
mean=0.0,
|
| 298 |
+
std=self.config.initializer_range,
|
| 299 |
+
).to(module.position_embeddings.dtype)
|
| 300 |
+
|
| 301 |
+
module.cls_token.data = nn.init.trunc_normal_(
|
| 302 |
+
module.cls_token.data.to(torch.float32),
|
| 303 |
+
mean=0.0,
|
| 304 |
+
std=self.config.initializer_range,
|
| 305 |
+
).to(module.cls_token.dtype)
|
| 306 |
+
|
| 307 |
+
module.mask_token.data.zero_()
|
| 308 |
+
module.register_tokens.data.zero_()
|
| 309 |
+
elif isinstance(module, Dinov2WithRegistersLayerScale): # noqa: F821
|
| 310 |
+
module.lambda1.data.fill_(self.config.layerscale_value)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
class Dinov2WithRegistersModel(Dinov2Model):
|
| 314 |
+
pass
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
class Dinov2WithRegistersForImageClassification(Dinov2ForImageClassification):
|
| 318 |
+
def forward(
|
| 319 |
+
self,
|
| 320 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 321 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 322 |
+
labels: Optional[torch.Tensor] = None,
|
| 323 |
+
output_attentions: Optional[bool] = None,
|
| 324 |
+
output_hidden_states: Optional[bool] = None,
|
| 325 |
+
return_dict: Optional[bool] = None,
|
| 326 |
+
) -> Union[tuple, ImageClassifierOutput]:
|
| 327 |
+
r"""
|
| 328 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 329 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 330 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 331 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 332 |
+
"""
|
| 333 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 334 |
+
|
| 335 |
+
outputs = self.dinov2_with_registers(
|
| 336 |
+
pixel_values,
|
| 337 |
+
head_mask=head_mask,
|
| 338 |
+
output_attentions=output_attentions,
|
| 339 |
+
output_hidden_states=output_hidden_states,
|
| 340 |
+
return_dict=return_dict,
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
sequence_output = outputs[0] # batch_size, sequence_length, hidden_size
|
| 344 |
+
|
| 345 |
+
cls_token = sequence_output[:, 0]
|
| 346 |
+
# cls and register tokens should not be included in patch tokens variable
|
| 347 |
+
patch_tokens = sequence_output[:, 1 + self.config.num_register_tokens :]
|
| 348 |
+
|
| 349 |
+
linear_input = torch.cat([cls_token, patch_tokens.mean(dim=1)], dim=1)
|
| 350 |
+
|
| 351 |
+
logits = self.classifier(linear_input)
|
| 352 |
+
|
| 353 |
+
loss = None
|
| 354 |
+
if labels is not None:
|
| 355 |
+
# move labels to correct device to enable model parallelism
|
| 356 |
+
labels = labels.to(logits.device)
|
| 357 |
+
if self.config.problem_type is None:
|
| 358 |
+
if self.num_labels == 1:
|
| 359 |
+
self.config.problem_type = "regression"
|
| 360 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 361 |
+
self.config.problem_type = "single_label_classification"
|
| 362 |
+
else:
|
| 363 |
+
self.config.problem_type = "multi_label_classification"
|
| 364 |
+
|
| 365 |
+
if self.config.problem_type == "regression":
|
| 366 |
+
loss_fct = MSELoss()
|
| 367 |
+
if self.num_labels == 1:
|
| 368 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 369 |
+
else:
|
| 370 |
+
loss = loss_fct(logits, labels)
|
| 371 |
+
elif self.config.problem_type == "single_label_classification":
|
| 372 |
+
loss_fct = CrossEntropyLoss()
|
| 373 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 374 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 375 |
+
loss_fct = BCEWithLogitsLoss()
|
| 376 |
+
loss = loss_fct(logits, labels)
|
| 377 |
+
|
| 378 |
+
if not return_dict:
|
| 379 |
+
output = (logits,) + outputs[2:]
|
| 380 |
+
return ((loss,) + output) if loss is not None else output
|
| 381 |
+
|
| 382 |
+
return ImageClassifierOutput(
|
| 383 |
+
loss=loss,
|
| 384 |
+
logits=logits,
|
| 385 |
+
hidden_states=outputs.hidden_states,
|
| 386 |
+
attentions=outputs.attentions,
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
class Dinov2WithRegistersBackbone(Dinov2Backbone):
|
| 391 |
+
def __init__(self, config):
|
| 392 |
+
super().__init__(config)
|
| 393 |
+
super()._init_backbone(config)
|
| 394 |
+
|
| 395 |
+
self.num_register_tokens = config.num_register_tokens
|
| 396 |
+
self.num_features = [config.hidden_size for _ in range(config.num_hidden_layers + 1)]
|
| 397 |
+
self.embeddings = Dinov2WithRegistersEmbeddings(config)
|
| 398 |
+
self.encoder = Dinov2WithRegistersEncoder(config)
|
| 399 |
+
|
| 400 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 401 |
+
|
| 402 |
+
# Initialize weights and apply final processing
|
| 403 |
+
self.post_init()
|
| 404 |
+
|
| 405 |
+
def get_input_embeddings(self) -> Dinov2WithRegistersPatchEmbeddings:
|
| 406 |
+
return self.embeddings.patch_embeddings
|
| 407 |
+
|
| 408 |
+
def forward(
|
| 409 |
+
self,
|
| 410 |
+
pixel_values: torch.Tensor,
|
| 411 |
+
output_hidden_states: Optional[bool] = None,
|
| 412 |
+
output_attentions: Optional[bool] = None,
|
| 413 |
+
return_dict: Optional[bool] = None,
|
| 414 |
+
) -> BackboneOutput:
|
| 415 |
+
r"""
|
| 416 |
+
Examples:
|
| 417 |
+
|
| 418 |
+
```python
|
| 419 |
+
>>> from transformers import AutoImageProcessor, AutoBackbone
|
| 420 |
+
>>> import torch
|
| 421 |
+
>>> from PIL import Image
|
| 422 |
+
>>> import requests
|
| 423 |
+
|
| 424 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 425 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 426 |
+
|
| 427 |
+
>>> processor = AutoImageProcessor.from_pretrained("facebook/dinov2-with-registers-base")
|
| 428 |
+
>>> model = AutoBackbone.from_pretrained(
|
| 429 |
+
... "facebook/dinov2-with-registers-base", out_features=["stage2", "stage5", "stage8", "stage11"]
|
| 430 |
+
... )
|
| 431 |
+
|
| 432 |
+
>>> inputs = processor(image, return_tensors="pt")
|
| 433 |
+
|
| 434 |
+
>>> outputs = model(**inputs)
|
| 435 |
+
>>> feature_maps = outputs.feature_maps
|
| 436 |
+
>>> list(feature_maps[-1].shape)
|
| 437 |
+
[1, 768, 16, 16]
|
| 438 |
+
```"""
|
| 439 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 440 |
+
output_hidden_states = (
|
| 441 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 442 |
+
)
|
| 443 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 444 |
+
|
| 445 |
+
embedding_output = self.embeddings(pixel_values)
|
| 446 |
+
|
| 447 |
+
outputs = self.encoder(
|
| 448 |
+
embedding_output, output_hidden_states=True, output_attentions=output_attentions, return_dict=return_dict
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
hidden_states = outputs.hidden_states if return_dict else outputs[1]
|
| 452 |
+
|
| 453 |
+
feature_maps = ()
|
| 454 |
+
for stage, hidden_state in zip(self.stage_names, hidden_states):
|
| 455 |
+
if stage in self.out_features:
|
| 456 |
+
if self.config.apply_layernorm:
|
| 457 |
+
hidden_state = self.layernorm(hidden_state)
|
| 458 |
+
if self.config.reshape_hidden_states:
|
| 459 |
+
hidden_state = hidden_state[:, self.num_register_tokens + 1 :]
|
| 460 |
+
# this was actually a bug in the original implementation that we copied here,
|
| 461 |
+
# cause normally the order is height, width
|
| 462 |
+
batch_size, _, height, width = pixel_values.shape
|
| 463 |
+
patch_size = self.config.patch_size
|
| 464 |
+
hidden_state = hidden_state.reshape(batch_size, height // patch_size, width // patch_size, -1)
|
| 465 |
+
hidden_state = hidden_state.permute(0, 3, 1, 2).contiguous()
|
| 466 |
+
feature_maps += (hidden_state,)
|
| 467 |
+
|
| 468 |
+
if not return_dict:
|
| 469 |
+
if output_hidden_states:
|
| 470 |
+
output = (feature_maps,) + outputs[1:]
|
| 471 |
+
else:
|
| 472 |
+
output = (feature_maps,) + outputs[2:]
|
| 473 |
+
return output
|
| 474 |
+
|
| 475 |
+
return BackboneOutput(
|
| 476 |
+
feature_maps=feature_maps,
|
| 477 |
+
hidden_states=outputs.hidden_states if output_hidden_states else None,
|
| 478 |
+
attentions=outputs.attentions if output_attentions else None,
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
__all__ = [
|
| 483 |
+
"Dinov2WithRegistersConfig",
|
| 484 |
+
"Dinov2WithRegistersPreTrainedModel",
|
| 485 |
+
"Dinov2WithRegistersModel",
|
| 486 |
+
"Dinov2WithRegistersForImageClassification",
|
| 487 |
+
"Dinov2WithRegistersBackbone",
|
| 488 |
+
]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_convnext/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 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_dinov3_convnext import *
|
| 22 |
+
from .modeling_dinov3_convnext import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_convnext/configuration_dinov3_convnext.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 Meta Platforms, Inc. and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""ConvNeXT model configuration"""
|
| 16 |
+
|
| 17 |
+
from typing import Optional
|
| 18 |
+
|
| 19 |
+
from ...configuration_utils import PretrainedConfig
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class DINOv3ConvNextConfig(PretrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
This is the configuration class to store the configuration of a [`DINOv3ConvNextModel`]. It is used to instantiate an
|
| 29 |
+
DINOv3ConvNext model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 30 |
+
with the defaults will yield a similar configuration to that of the DINOv3ConvNext
|
| 31 |
+
[facebook/dinov3-convnext-tiny-pretrain-lvd1689m](https://huggingface.co/facebook/dinov3-convnext-tiny-pretrain-lvd1689m) architecture.
|
| 32 |
+
|
| 33 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 34 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 38 |
+
The number of input channels.
|
| 39 |
+
hidden_sizes (`list[int]`, *optional*, defaults to [96, 192, 384, 768]):
|
| 40 |
+
Dimensionality (hidden size) at each stage.
|
| 41 |
+
depths (`list[int]`, *optional*, defaults to [3, 3, 9, 3]):
|
| 42 |
+
The number of layers for each stage.
|
| 43 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 44 |
+
The non-linear activation function (function or string) in each block. If string, `"gelu"`, `"relu"`,
|
| 45 |
+
`"selu"` and `"gelu_new"` are supported.
|
| 46 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 47 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 48 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 49 |
+
The epsilon used by the layer normalization layers.
|
| 50 |
+
layer_scale_init_value (`float`, *optional*, defaults to 1e-06):
|
| 51 |
+
The initial value for the layer scale.
|
| 52 |
+
drop_path_rate (`float`, *optional*, defaults to 0.0):
|
| 53 |
+
The drop rate for stochastic depth.
|
| 54 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 55 |
+
The size (resolution) of input images.
|
| 56 |
+
|
| 57 |
+
Example:
|
| 58 |
+
```python
|
| 59 |
+
>>> from transformers import DINOv3ConvNextConfig, DINOv3ConvNextModel
|
| 60 |
+
|
| 61 |
+
>>> # Initializing a DINOv3ConvNext (tiny variant) style configuration
|
| 62 |
+
>>> config = DINOv3ConvNextConfig()
|
| 63 |
+
|
| 64 |
+
>>> # Initializing a model (with random weights)
|
| 65 |
+
>>> model = DINOv3ConvNextModel(config)
|
| 66 |
+
|
| 67 |
+
>>> # Accessing the model config
|
| 68 |
+
>>> config = model.config
|
| 69 |
+
```"""
|
| 70 |
+
|
| 71 |
+
model_type = "dinov3_convnext"
|
| 72 |
+
|
| 73 |
+
def __init__(
|
| 74 |
+
self,
|
| 75 |
+
num_channels: int = 3,
|
| 76 |
+
hidden_sizes: Optional[list[int]] = None,
|
| 77 |
+
depths: Optional[list[int]] = None,
|
| 78 |
+
hidden_act: str = "gelu",
|
| 79 |
+
initializer_range: float = 0.02,
|
| 80 |
+
layer_norm_eps: float = 1e-6,
|
| 81 |
+
layer_scale_init_value: float = 1e-6,
|
| 82 |
+
drop_path_rate: float = 0.0,
|
| 83 |
+
image_size: int = 224,
|
| 84 |
+
**kwargs,
|
| 85 |
+
):
|
| 86 |
+
super().__init__(**kwargs)
|
| 87 |
+
|
| 88 |
+
self.num_channels = num_channels
|
| 89 |
+
self.hidden_sizes = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes
|
| 90 |
+
self.depths = [3, 3, 9, 3] if depths is None else depths
|
| 91 |
+
self.hidden_act = hidden_act
|
| 92 |
+
self.initializer_range = initializer_range
|
| 93 |
+
self.layer_norm_eps = layer_norm_eps
|
| 94 |
+
self.layer_scale_init_value = layer_scale_init_value
|
| 95 |
+
self.drop_path_rate = drop_path_rate
|
| 96 |
+
self.image_size = image_size
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def num_stages(self) -> int:
|
| 100 |
+
return len(self.hidden_sizes)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
__all__ = ["DINOv3ConvNextConfig"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_convnext/convert_dinov3_convnext_to_hf.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert DINOv3 checkpoints from the original repository.
|
| 16 |
+
|
| 17 |
+
URL: https://github.com/facebookresearch/dinov3/tree/main
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import os
|
| 22 |
+
import re
|
| 23 |
+
from typing import Optional
|
| 24 |
+
|
| 25 |
+
import requests
|
| 26 |
+
import torch
|
| 27 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 28 |
+
from PIL import Image
|
| 29 |
+
from torchvision import transforms
|
| 30 |
+
|
| 31 |
+
from transformers import DINOv3ConvNextConfig, DINOv3ConvNextModel, DINOv3ViTImageProcessorFast
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
HUB_MODELS = {
|
| 35 |
+
"convnext_tiny": "facebook/dinov3-convnext-tiny-pretrain-lvd1689m",
|
| 36 |
+
"convnext_small": "facebook/dinov3-convnext-small-pretrain-lvd1689m",
|
| 37 |
+
"convnext_base": "facebook/dinov3-convnext-base-pretrain-lvd1689m",
|
| 38 |
+
"convnext_large": "facebook/dinov3-convnext-large-pretrain-lvd1689m",
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
HUB_CHECKPOINTS = {
|
| 42 |
+
"convnext_tiny": "dinov3_convnext_tiny_pretrain_lvd1689m-21b726bb.pth",
|
| 43 |
+
"convnext_small": "dinov3_convnext_small_pretrain_lvd1689m-296db49d.pth",
|
| 44 |
+
"convnext_base": "dinov3_convnext_base_pretrain_lvd1689m-801f2ba9.pth",
|
| 45 |
+
"convnext_large": "dinov3_convnext_large_pretrain_lvd1689m-61fa432d.pth",
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
# fmt: off
|
| 49 |
+
ORIGINAL_TO_CONVERTED_KEY_MAPPING = {
|
| 50 |
+
r"dwconv": r"depthwise_conv",
|
| 51 |
+
r"pwconv": r"pointwise_conv",
|
| 52 |
+
r"norm": r"layer_norm",
|
| 53 |
+
r"stages.(\d+).(\d+)": r"stages.\1.layers.\2",
|
| 54 |
+
r"downsample_layers.(\d+).(\d+)": r"stages.\1.downsample_layers.\2",
|
| 55 |
+
}
|
| 56 |
+
# fmt: on
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def get_dinov3_config(model_name: str) -> DINOv3ConvNextConfig:
|
| 60 |
+
# size of the architecture
|
| 61 |
+
if model_name == "convnext_tiny":
|
| 62 |
+
return DINOv3ConvNextConfig(
|
| 63 |
+
depths=[3, 3, 9, 3],
|
| 64 |
+
hidden_sizes=[96, 192, 384, 768],
|
| 65 |
+
)
|
| 66 |
+
elif model_name == "convnext_small":
|
| 67 |
+
return DINOv3ConvNextConfig(
|
| 68 |
+
depths=[3, 3, 27, 3],
|
| 69 |
+
hidden_sizes=[96, 192, 384, 768],
|
| 70 |
+
)
|
| 71 |
+
elif model_name == "convnext_base":
|
| 72 |
+
return DINOv3ConvNextConfig(
|
| 73 |
+
depths=[3, 3, 27, 3],
|
| 74 |
+
hidden_sizes=[128, 256, 512, 1024],
|
| 75 |
+
)
|
| 76 |
+
elif model_name == "convnext_large":
|
| 77 |
+
return DINOv3ConvNextConfig(
|
| 78 |
+
depths=[3, 3, 27, 3],
|
| 79 |
+
hidden_sizes=[192, 384, 768, 1536],
|
| 80 |
+
)
|
| 81 |
+
else:
|
| 82 |
+
raise ValueError("Model not supported")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def prepare_img():
|
| 86 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 87 |
+
image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
|
| 88 |
+
return image
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def get_transform(resize_size: int = 224):
|
| 92 |
+
to_tensor = transforms.ToTensor()
|
| 93 |
+
resize = transforms.Resize((resize_size, resize_size), antialias=True)
|
| 94 |
+
normalize = transforms.Normalize(
|
| 95 |
+
mean=(0.485, 0.456, 0.406),
|
| 96 |
+
std=(0.229, 0.224, 0.225),
|
| 97 |
+
)
|
| 98 |
+
return transforms.Compose([to_tensor, resize, normalize])
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def get_image_processor(resize_size: int = 224):
|
| 102 |
+
return DINOv3ViTImageProcessorFast(
|
| 103 |
+
do_resize=True,
|
| 104 |
+
size={"height": resize_size, "width": resize_size},
|
| 105 |
+
resample=2, # BILINEAR
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def convert_old_keys_to_new_keys(state_dict_keys: Optional[dict] = None):
|
| 110 |
+
"""
|
| 111 |
+
This function should be applied only once, on the concatenated keys to efficiently rename using
|
| 112 |
+
the key mappings.
|
| 113 |
+
"""
|
| 114 |
+
output_dict = {}
|
| 115 |
+
if state_dict_keys is not None:
|
| 116 |
+
old_text = "\n".join(state_dict_keys)
|
| 117 |
+
new_text = old_text
|
| 118 |
+
for pattern, replacement in ORIGINAL_TO_CONVERTED_KEY_MAPPING.items():
|
| 119 |
+
if replacement is None:
|
| 120 |
+
new_text = re.sub(pattern, "", new_text) # an empty line
|
| 121 |
+
continue
|
| 122 |
+
new_text = re.sub(pattern, replacement, new_text)
|
| 123 |
+
output_dict = dict(zip(old_text.split("\n"), new_text.split("\n")))
|
| 124 |
+
return output_dict
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@torch.no_grad()
|
| 128 |
+
def convert_and_test_dinov3_checkpoint(args):
|
| 129 |
+
expected_outputs = {
|
| 130 |
+
"convnext_tiny_cls": [-6.372119, 1.300791, 2.074303, -0.079975, 0.607205],
|
| 131 |
+
"convnext_tiny_patch": [0.490530, -3.713466, 1.848513, -1.040319, -1.090818],
|
| 132 |
+
"convnext_small_cls": [-0.903914, 1.412183, 0.287465, 0.175296, -2.397940],
|
| 133 |
+
"convnext_small_patch": [-1.081114, 0.637362, 3.748765, 0.170179, 1.445153],
|
| 134 |
+
"convnext_base_cls": [0.155366, -0.378771, -0.735157, -2.818718, 0.015095],
|
| 135 |
+
"convnext_base_patch": [3.039118, 0.778155, -1.961322, -1.607147, -2.411941],
|
| 136 |
+
"convnext_large_cls": [-2.219094, -0.594451, -2.300294, -0.957415, -0.520473],
|
| 137 |
+
"convnext_large_patch": [-1.477349, -0.217038, -3.128137, 0.418962, 0.334949],
|
| 138 |
+
}
|
| 139 |
+
model_name = args.model_name
|
| 140 |
+
config = get_dinov3_config(model_name)
|
| 141 |
+
# print(config)
|
| 142 |
+
|
| 143 |
+
model = DINOv3ConvNextModel(config).eval()
|
| 144 |
+
state_dict_path = hf_hub_download(repo_id=HUB_MODELS[model_name], filename=HUB_CHECKPOINTS[model_name])
|
| 145 |
+
original_state_dict = torch.load(state_dict_path)
|
| 146 |
+
original_keys = list(original_state_dict.keys())
|
| 147 |
+
new_keys = convert_old_keys_to_new_keys(original_keys)
|
| 148 |
+
|
| 149 |
+
converted_state_dict = {}
|
| 150 |
+
for key in original_keys:
|
| 151 |
+
new_key = new_keys[key]
|
| 152 |
+
weight_tensor = original_state_dict[key]
|
| 153 |
+
if key == "norms.3.weight" or key == "norms.3.bias":
|
| 154 |
+
continue
|
| 155 |
+
converted_state_dict[new_key] = weight_tensor
|
| 156 |
+
model.load_state_dict(converted_state_dict, strict=True)
|
| 157 |
+
model = model.eval()
|
| 158 |
+
|
| 159 |
+
transform = get_transform()
|
| 160 |
+
image_processor = get_image_processor()
|
| 161 |
+
image = prepare_img()
|
| 162 |
+
|
| 163 |
+
# check preprocessing
|
| 164 |
+
original_pixel_values = transform(image).unsqueeze(0) # add batch dimension
|
| 165 |
+
inputs = image_processor(image, return_tensors="pt")
|
| 166 |
+
|
| 167 |
+
torch.testing.assert_close(original_pixel_values, inputs["pixel_values"], atol=1e-6, rtol=1e-6)
|
| 168 |
+
print("Preprocessing looks ok!")
|
| 169 |
+
|
| 170 |
+
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.float):
|
| 171 |
+
model_output = model(**inputs)
|
| 172 |
+
|
| 173 |
+
last_layer_class_token = model_output.pooler_output
|
| 174 |
+
last_layer_patch_tokens = model_output.last_hidden_state[:, 1:]
|
| 175 |
+
|
| 176 |
+
actual_outputs = {}
|
| 177 |
+
actual_outputs[f"{model_name}_cls"] = last_layer_class_token[0, :5].tolist()
|
| 178 |
+
actual_outputs[f"{model_name}_patch"] = last_layer_patch_tokens[0, 0, :5].tolist()
|
| 179 |
+
|
| 180 |
+
print("Actual: ", [round(x, 6) for x in actual_outputs[f"{model_name}_cls"]])
|
| 181 |
+
print("Expected:", expected_outputs[f"{model_name}_cls"])
|
| 182 |
+
|
| 183 |
+
torch.testing.assert_close(
|
| 184 |
+
torch.Tensor(actual_outputs[f"{model_name}_cls"]),
|
| 185 |
+
torch.Tensor(expected_outputs[f"{model_name}_cls"]),
|
| 186 |
+
atol=1e-3,
|
| 187 |
+
rtol=1e-3,
|
| 188 |
+
)
|
| 189 |
+
print("Actual: ", [round(x, 6) for x in actual_outputs[f"{model_name}_patch"]])
|
| 190 |
+
print("Expected:", expected_outputs[f"{model_name}_patch"])
|
| 191 |
+
|
| 192 |
+
torch.testing.assert_close(
|
| 193 |
+
torch.Tensor(actual_outputs[f"{model_name}_patch"]),
|
| 194 |
+
torch.Tensor(expected_outputs[f"{model_name}_patch"]),
|
| 195 |
+
atol=1e-3,
|
| 196 |
+
rtol=1e-3,
|
| 197 |
+
)
|
| 198 |
+
print("Forward pass looks ok!")
|
| 199 |
+
|
| 200 |
+
save_dir = os.path.join(args.save_dir, model_name)
|
| 201 |
+
os.makedirs(save_dir, exist_ok=True)
|
| 202 |
+
model.save_pretrained(save_dir)
|
| 203 |
+
image_processor.save_pretrained(save_dir)
|
| 204 |
+
print(f"Model saved to {save_dir}")
|
| 205 |
+
|
| 206 |
+
if args.push_to_hub:
|
| 207 |
+
api = HfApi()
|
| 208 |
+
repo = HUB_MODELS[model_name]
|
| 209 |
+
api.upload_folder(folder_path=save_dir, repo_id=repo, repo_type="model")
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
if __name__ == "__main__":
|
| 213 |
+
parser = argparse.ArgumentParser()
|
| 214 |
+
# Required parameters
|
| 215 |
+
parser.add_argument(
|
| 216 |
+
"--model-name",
|
| 217 |
+
default="convnext_tiny",
|
| 218 |
+
type=str,
|
| 219 |
+
choices=["convnext_tiny", "convnext_small", "convnext_base", "convnext_large"],
|
| 220 |
+
help="Name of the model you'd like to convert.",
|
| 221 |
+
)
|
| 222 |
+
parser.add_argument(
|
| 223 |
+
"--save-dir",
|
| 224 |
+
default="converted_models",
|
| 225 |
+
type=str,
|
| 226 |
+
help="Directory to save the converted model.",
|
| 227 |
+
)
|
| 228 |
+
parser.add_argument(
|
| 229 |
+
"--push-to-hub",
|
| 230 |
+
action="store_true",
|
| 231 |
+
help="Push the converted model to the Hugging Face Hub.",
|
| 232 |
+
)
|
| 233 |
+
args = parser.parse_args()
|
| 234 |
+
convert_and_test_dinov3_checkpoint(args)
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_convnext/modeling_dinov3_convnext.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 Meta Platforms, Inc. and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch ConvNext model."""
|
| 16 |
+
|
| 17 |
+
from typing import Optional
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
import torch.utils.checkpoint
|
| 22 |
+
from torch import nn
|
| 23 |
+
|
| 24 |
+
from ...activations import ACT2FN
|
| 25 |
+
from ...modeling_outputs import (
|
| 26 |
+
BaseModelOutputWithPoolingAndNoAttention,
|
| 27 |
+
)
|
| 28 |
+
from ...modeling_utils import PreTrainedModel
|
| 29 |
+
from ...utils import auto_docstring, logging
|
| 30 |
+
from ...utils.generic import can_return_tuple
|
| 31 |
+
from .configuration_dinov3_convnext import DINOv3ConvNextConfig
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
logger = logging.get_logger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# Copied from transformers.models.beit.modeling_beit.drop_path
|
| 38 |
+
def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
|
| 39 |
+
"""
|
| 40 |
+
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 41 |
+
|
| 42 |
+
Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
|
| 43 |
+
however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
|
| 44 |
+
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
|
| 45 |
+
layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
|
| 46 |
+
argument.
|
| 47 |
+
"""
|
| 48 |
+
if drop_prob == 0.0 or not training:
|
| 49 |
+
return input
|
| 50 |
+
keep_prob = 1 - drop_prob
|
| 51 |
+
shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 52 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
|
| 53 |
+
random_tensor.floor_() # binarize
|
| 54 |
+
output = input.div(keep_prob) * random_tensor
|
| 55 |
+
return output
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# Copied from transformers.models.convnext.modeling_convnext.ConvNextDropPath with ConvNext->DINOv3ConvNext
|
| 59 |
+
class DINOv3ConvNextDropPath(nn.Module):
|
| 60 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 61 |
+
|
| 62 |
+
def __init__(self, drop_prob: Optional[float] = None) -> None:
|
| 63 |
+
super().__init__()
|
| 64 |
+
self.drop_prob = drop_prob
|
| 65 |
+
|
| 66 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 67 |
+
return drop_path(hidden_states, self.drop_prob, self.training)
|
| 68 |
+
|
| 69 |
+
def extra_repr(self) -> str:
|
| 70 |
+
return f"p={self.drop_prob}"
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class DINOv3ConvNextLayerNorm(nn.LayerNorm):
|
| 74 |
+
r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
|
| 75 |
+
The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
|
| 76 |
+
width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
def __init__(self, *args, data_format="channels_last", **kwargs):
|
| 80 |
+
super().__init__(*args, **kwargs)
|
| 81 |
+
if data_format not in ["channels_last", "channels_first"]:
|
| 82 |
+
raise NotImplementedError(f"Unsupported data format: {data_format}")
|
| 83 |
+
self.data_format = data_format
|
| 84 |
+
|
| 85 |
+
def forward(self, features: torch.Tensor) -> torch.Tensor:
|
| 86 |
+
"""
|
| 87 |
+
Args:
|
| 88 |
+
features: Tensor of shape (batch_size, channels, height, width) OR (batch_size, height, width, channels)
|
| 89 |
+
"""
|
| 90 |
+
if self.data_format == "channels_first":
|
| 91 |
+
features = features.permute(0, 2, 3, 1)
|
| 92 |
+
features = super().forward(features)
|
| 93 |
+
features = features.permute(0, 3, 1, 2)
|
| 94 |
+
else:
|
| 95 |
+
features = super().forward(features)
|
| 96 |
+
return features
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class DINOv3ConvNextLayer(nn.Module):
|
| 100 |
+
"""This corresponds to the `Block` class in the original implementation.
|
| 101 |
+
|
| 102 |
+
There are two equivalent implementations:
|
| 103 |
+
1) DwConv, LayerNorm (channels_first), Conv, GELU, Conv (all in (N, C, H, W) format)
|
| 104 |
+
2) DwConv, Permute, LayerNorm (channels_last), Linear, GELU, Linear, Permute
|
| 105 |
+
|
| 106 |
+
The authors used (2) as they find it slightly faster in PyTorch.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
config ([`DINOv3ConvNextConfig`]):
|
| 110 |
+
Model config.
|
| 111 |
+
channels (`int`):
|
| 112 |
+
Number of input (and output) channels.
|
| 113 |
+
drop_path (`float`):
|
| 114 |
+
Drop path rate. Default: 0.0.
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
def __init__(self, config: DINOv3ConvNextConfig, channels: int, drop_path: float = 0.0):
|
| 118 |
+
super().__init__()
|
| 119 |
+
self.depthwise_conv = nn.Conv2d(channels, channels, kernel_size=7, padding=3, groups=channels)
|
| 120 |
+
self.layer_norm = DINOv3ConvNextLayerNorm(channels, eps=config.layer_norm_eps)
|
| 121 |
+
self.pointwise_conv1 = nn.Linear(channels, 4 * channels) # can be seen as a 1x1 conv
|
| 122 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 123 |
+
self.pointwise_conv2 = nn.Linear(4 * channels, channels) # can be seen as a 1x1 conv
|
| 124 |
+
self.gamma = nn.Parameter(torch.full((channels,), config.layer_scale_init_value), requires_grad=True)
|
| 125 |
+
self.drop_path = DINOv3ConvNextDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
| 126 |
+
|
| 127 |
+
def forward(self, features: torch.Tensor) -> torch.Tensor:
|
| 128 |
+
"""
|
| 129 |
+
Args:
|
| 130 |
+
features: Tensor of shape (batch_size, channels, height, width)
|
| 131 |
+
"""
|
| 132 |
+
residual = features
|
| 133 |
+
features = self.depthwise_conv(features)
|
| 134 |
+
features = features.permute(0, 2, 3, 1) # to channels last
|
| 135 |
+
features = self.layer_norm(features)
|
| 136 |
+
features = self.pointwise_conv1(features)
|
| 137 |
+
features = self.activation_fn(features)
|
| 138 |
+
features = self.pointwise_conv2(features)
|
| 139 |
+
features = features * self.gamma
|
| 140 |
+
features = features.permute(0, 3, 1, 2) # back to channels first
|
| 141 |
+
features = residual + self.drop_path(features)
|
| 142 |
+
return features
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class DINOv3ConvNextStage(nn.Module):
|
| 146 |
+
""" """
|
| 147 |
+
|
| 148 |
+
def __init__(self, config: DINOv3ConvNextConfig, stage_idx: int):
|
| 149 |
+
super().__init__()
|
| 150 |
+
|
| 151 |
+
in_channels = config.hidden_sizes[stage_idx - 1] if stage_idx > 0 else config.num_channels
|
| 152 |
+
out_channels = config.hidden_sizes[stage_idx]
|
| 153 |
+
|
| 154 |
+
if stage_idx == 0:
|
| 155 |
+
self.downsample_layers = nn.ModuleList(
|
| 156 |
+
[
|
| 157 |
+
nn.Conv2d(config.num_channels, out_channels, kernel_size=4, stride=4),
|
| 158 |
+
DINOv3ConvNextLayerNorm(out_channels, eps=config.layer_norm_eps, data_format="channels_first"),
|
| 159 |
+
]
|
| 160 |
+
)
|
| 161 |
+
else:
|
| 162 |
+
self.downsample_layers = nn.ModuleList(
|
| 163 |
+
[
|
| 164 |
+
DINOv3ConvNextLayerNorm(in_channels, eps=config.layer_norm_eps, data_format="channels_first"),
|
| 165 |
+
nn.Conv2d(in_channels, out_channels, kernel_size=2, stride=2),
|
| 166 |
+
]
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
num_stage_layers = config.depths[stage_idx]
|
| 170 |
+
num_previous_layers = sum(config.depths[:stage_idx])
|
| 171 |
+
num_total_layers = sum(config.depths)
|
| 172 |
+
drop_path_rates = np.linspace(0, config.drop_path_rate, num_total_layers).tolist()
|
| 173 |
+
|
| 174 |
+
self.layers = nn.ModuleList(
|
| 175 |
+
[
|
| 176 |
+
DINOv3ConvNextLayer(config, channels=out_channels, drop_path=drop_path_rates[i])
|
| 177 |
+
for i in range(num_previous_layers, num_previous_layers + num_stage_layers)
|
| 178 |
+
]
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
def forward(self, features: torch.Tensor) -> torch.Tensor:
|
| 182 |
+
"""
|
| 183 |
+
Args:
|
| 184 |
+
features: Tensor of shape (batch_size, channels, height, width)
|
| 185 |
+
"""
|
| 186 |
+
for layer in self.downsample_layers:
|
| 187 |
+
features = layer(features)
|
| 188 |
+
for layer in self.layers:
|
| 189 |
+
features = layer(features)
|
| 190 |
+
return features
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@auto_docstring
|
| 194 |
+
class DINOv3ConvNextPreTrainedModel(PreTrainedModel):
|
| 195 |
+
config: DINOv3ConvNextConfig
|
| 196 |
+
base_model_prefix = "dinov3_convnext"
|
| 197 |
+
main_input_name = "pixel_values"
|
| 198 |
+
_no_split_modules = ["DINOv3ConvNextLayer"]
|
| 199 |
+
|
| 200 |
+
def _init_weights(self, module):
|
| 201 |
+
"""Initialize the weights"""
|
| 202 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 203 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 204 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 205 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 206 |
+
if module.bias is not None:
|
| 207 |
+
module.bias.data.zero_()
|
| 208 |
+
elif isinstance(module, (nn.LayerNorm, DINOv3ConvNextLayerNorm)):
|
| 209 |
+
module.bias.data.zero_()
|
| 210 |
+
module.weight.data.fill_(1.0)
|
| 211 |
+
elif isinstance(module, DINOv3ConvNextLayer):
|
| 212 |
+
if module.gamma is not None:
|
| 213 |
+
module.gamma.data.fill_(self.config.layer_scale_init_value)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
@auto_docstring
|
| 217 |
+
class DINOv3ConvNextModel(DINOv3ConvNextPreTrainedModel):
|
| 218 |
+
def __init__(self, config: DINOv3ConvNextConfig):
|
| 219 |
+
super().__init__(config)
|
| 220 |
+
self.config = config
|
| 221 |
+
self.stages = nn.ModuleList([DINOv3ConvNextStage(config, stage_idx) for stage_idx in range(config.num_stages)])
|
| 222 |
+
self.layer_norm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps) # final norm layer
|
| 223 |
+
self.pool = nn.AdaptiveAvgPool2d(1)
|
| 224 |
+
self.post_init()
|
| 225 |
+
|
| 226 |
+
@can_return_tuple
|
| 227 |
+
@auto_docstring
|
| 228 |
+
def forward(
|
| 229 |
+
self, pixel_values: torch.FloatTensor, output_hidden_states: Optional[bool] = None
|
| 230 |
+
) -> BaseModelOutputWithPoolingAndNoAttention:
|
| 231 |
+
hidden_states = pixel_values
|
| 232 |
+
|
| 233 |
+
output_hidden_states = output_hidden_states or self.config.output_hidden_states
|
| 234 |
+
all_hidden_states = [hidden_states] if output_hidden_states else []
|
| 235 |
+
|
| 236 |
+
for stage in self.stages:
|
| 237 |
+
hidden_states = stage(hidden_states)
|
| 238 |
+
|
| 239 |
+
# store intermediate stage outputs
|
| 240 |
+
if output_hidden_states:
|
| 241 |
+
all_hidden_states.append(hidden_states)
|
| 242 |
+
|
| 243 |
+
# make global representation, a.k.a [CLS] token
|
| 244 |
+
pooled_output = self.pool(hidden_states)
|
| 245 |
+
|
| 246 |
+
# (batch_size, channels, height, width) -> (batch_size, height * width, channels)
|
| 247 |
+
pooled_output = pooled_output.flatten(2).transpose(1, 2)
|
| 248 |
+
hidden_states = hidden_states.flatten(2).transpose(1, 2)
|
| 249 |
+
|
| 250 |
+
# concat "cls" and "patch tokens" as (batch_size, 1 + height * width, channels)
|
| 251 |
+
hidden_states = torch.cat([pooled_output, hidden_states], dim=1)
|
| 252 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 253 |
+
|
| 254 |
+
return BaseModelOutputWithPoolingAndNoAttention(
|
| 255 |
+
last_hidden_state=hidden_states,
|
| 256 |
+
pooler_output=hidden_states[:, 0],
|
| 257 |
+
hidden_states=tuple(all_hidden_states) if output_hidden_states else None,
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
__all__ = ["DINOv3ConvNextModel", "DINOv3ConvNextPreTrainedModel"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_vit/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 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_dinov3_vit import *
|
| 22 |
+
from .image_processing_dinov3_vit_fast import *
|
| 23 |
+
from .modeling_dinov3_vit 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__)
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_vit/configuration_dinov3_vit.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""DINOv3 model configuration"""
|
| 16 |
+
|
| 17 |
+
from typing import Optional
|
| 18 |
+
|
| 19 |
+
from ...configuration_utils import PretrainedConfig
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class DINOv3ViTConfig(PretrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
This is the configuration class to store the configuration of a [`DINOv3Model`]. It is used to instantiate an
|
| 29 |
+
DINOv3 model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 30 |
+
with the defaults will yield a similar configuration to that of the DINOv3
|
| 31 |
+
[facebook/dinov3-vits16-pretrain-lvd1689m](https://huggingface.co/facebook/dinov3-vits16-pretrain-lvd1689m) architecture.
|
| 32 |
+
|
| 33 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 34 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 38 |
+
The size (resolution) of each patch.
|
| 39 |
+
hidden_size (`int`, *optional*, defaults to 384):
|
| 40 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 41 |
+
intermediate_size (`int`, *optional*, defaults to 1536):
|
| 42 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer.
|
| 43 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 44 |
+
Number of hidden layers in the Transformer encoder.
|
| 45 |
+
num_attention_heads (`int`, *optional*, defaults to 6):
|
| 46 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 47 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 48 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 49 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 50 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 51 |
+
The dropout ratio for the attention probabilities.
|
| 52 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 53 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 54 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 55 |
+
The epsilon used by the layer normalization layers.
|
| 56 |
+
rope_theta (`float`, *optional*, defaults to 100.0):
|
| 57 |
+
The base period of the RoPE embeddings.
|
| 58 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 59 |
+
The size (resolution) of each image.
|
| 60 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 61 |
+
The number of input channels.
|
| 62 |
+
query_bias (`bool`, *optional*, defaults to `True`):
|
| 63 |
+
Whether to add a bias to the query projection.
|
| 64 |
+
key_bias (`bool`, *optional*, defaults to `False`):
|
| 65 |
+
Whether to add a bias to the key projection.
|
| 66 |
+
value_bias (`bool`, *optional*, defaults to `True`):
|
| 67 |
+
Whether to add a bias to the value projection.
|
| 68 |
+
proj_bias (`bool`, *optional*, defaults to `True`):
|
| 69 |
+
Whether to add a bias to the output projection.
|
| 70 |
+
mlp_bias (`bool`, *optional*, defaults to `True`):
|
| 71 |
+
Whether to add a bias to the MLP layers.
|
| 72 |
+
layerscale_value (`float`, *optional*, defaults to 1.0):
|
| 73 |
+
Initial value to use for layer scale.
|
| 74 |
+
drop_path_rate (`float`, *optional*, defaults to 0.0):
|
| 75 |
+
Stochastic depth rate per sample (when applied in the main path of residual layers).
|
| 76 |
+
use_gated_mlp (`bool`, *optional*, defaults to `False`):
|
| 77 |
+
Whether to use the SwiGLU feedforward neural network.
|
| 78 |
+
num_register_tokens (`int`, *optional*, defaults to 0):
|
| 79 |
+
The number of register tokens.
|
| 80 |
+
pos_embed_shift (`float`, *optional*):
|
| 81 |
+
Amount to randomly shift position embedding coordinates in [-shift, shift],
|
| 82 |
+
applied only in training mode if not `None`.
|
| 83 |
+
pos_embed_jitter (`float`, *optional*):
|
| 84 |
+
Amount to randomly jitter position embedding coordinates in log-uniform value in [1/jitter, jitter],
|
| 85 |
+
applied only in training mode if not `None`.
|
| 86 |
+
pos_embed_rescale (`float`, *optional*, defaults to 2.0):
|
| 87 |
+
Amount to randomly rescale position embedding coordinates in log-uniform value in [1/rescale, rescale],
|
| 88 |
+
applied only in training mode if not `None`.
|
| 89 |
+
|
| 90 |
+
Example:
|
| 91 |
+
|
| 92 |
+
```python
|
| 93 |
+
>>> from transformers import DINOv3ViTConfig, DINOv3ViTModel
|
| 94 |
+
|
| 95 |
+
>>> # Initializing a DINOv3 ViT-small style configuration
|
| 96 |
+
>>> config = DINOv3ViTConfig()
|
| 97 |
+
|
| 98 |
+
>>> # Initializing a model (with random weights) from the config
|
| 99 |
+
>>> model = DINOv3ViTModel(config)
|
| 100 |
+
|
| 101 |
+
>>> # Accessing the model config
|
| 102 |
+
>>> config = model.config
|
| 103 |
+
```"""
|
| 104 |
+
|
| 105 |
+
model_type = "dinov3_vit"
|
| 106 |
+
|
| 107 |
+
def __init__(
|
| 108 |
+
self,
|
| 109 |
+
patch_size: int = 16,
|
| 110 |
+
hidden_size: int = 384,
|
| 111 |
+
intermediate_size: int = 1536,
|
| 112 |
+
num_hidden_layers: int = 12,
|
| 113 |
+
num_attention_heads: int = 6,
|
| 114 |
+
hidden_act: str = "gelu",
|
| 115 |
+
attention_dropout: float = 0.0,
|
| 116 |
+
initializer_range: float = 0.02,
|
| 117 |
+
layer_norm_eps: float = 1e-5,
|
| 118 |
+
rope_theta: float = 100.0,
|
| 119 |
+
image_size: int = 224,
|
| 120 |
+
num_channels: int = 3,
|
| 121 |
+
query_bias: bool = True,
|
| 122 |
+
key_bias: bool = False,
|
| 123 |
+
value_bias: bool = True,
|
| 124 |
+
proj_bias: bool = True,
|
| 125 |
+
mlp_bias: bool = True,
|
| 126 |
+
layerscale_value: float = 1.0,
|
| 127 |
+
drop_path_rate: float = 0.0,
|
| 128 |
+
use_gated_mlp: bool = False,
|
| 129 |
+
num_register_tokens: int = 0,
|
| 130 |
+
# train augs
|
| 131 |
+
pos_embed_shift: Optional[float] = None,
|
| 132 |
+
pos_embed_jitter: Optional[float] = None,
|
| 133 |
+
pos_embed_rescale: Optional[float] = 2.0,
|
| 134 |
+
**kwargs,
|
| 135 |
+
):
|
| 136 |
+
super().__init__(**kwargs)
|
| 137 |
+
|
| 138 |
+
self.image_size = image_size
|
| 139 |
+
self.patch_size = patch_size
|
| 140 |
+
self.num_channels = num_channels
|
| 141 |
+
self.hidden_size = hidden_size
|
| 142 |
+
self.intermediate_size = intermediate_size
|
| 143 |
+
self.num_hidden_layers = num_hidden_layers
|
| 144 |
+
self.num_attention_heads = num_attention_heads
|
| 145 |
+
self.hidden_act = hidden_act
|
| 146 |
+
self.attention_dropout = attention_dropout
|
| 147 |
+
self.initializer_range = initializer_range
|
| 148 |
+
self.layer_norm_eps = layer_norm_eps
|
| 149 |
+
self.layerscale_value = layerscale_value
|
| 150 |
+
self.drop_path_rate = drop_path_rate
|
| 151 |
+
self.use_gated_mlp = use_gated_mlp
|
| 152 |
+
self.rope_theta = rope_theta
|
| 153 |
+
self.query_bias = query_bias
|
| 154 |
+
self.key_bias = key_bias
|
| 155 |
+
self.value_bias = value_bias
|
| 156 |
+
self.proj_bias = proj_bias
|
| 157 |
+
self.mlp_bias = mlp_bias
|
| 158 |
+
self.num_register_tokens = num_register_tokens
|
| 159 |
+
|
| 160 |
+
# train augs
|
| 161 |
+
self.pos_embed_shift = pos_embed_shift
|
| 162 |
+
self.pos_embed_jitter = pos_embed_jitter
|
| 163 |
+
self.pos_embed_rescale = pos_embed_rescale
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
__all__ = ["DINOv3ViTConfig"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_vit/convert_dinov3_vit_to_hf.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert DINOv3 checkpoints from the original repository.
|
| 16 |
+
|
| 17 |
+
URL: https://github.com/facebookresearch/dinov3/tree/main
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import os
|
| 22 |
+
import re
|
| 23 |
+
from typing import Optional
|
| 24 |
+
|
| 25 |
+
import requests
|
| 26 |
+
import torch
|
| 27 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 28 |
+
from PIL import Image
|
| 29 |
+
from torchvision import transforms
|
| 30 |
+
|
| 31 |
+
from transformers import DINOv3ViTConfig, DINOv3ViTImageProcessorFast, DINOv3ViTModel
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
HUB_MODELS = {
|
| 35 |
+
"vits16_lvd1689m": "facebook/dinov3-vits16-pretrain-lvd1689m",
|
| 36 |
+
"vits16plus_lvd1689m": "facebook/dinov3-vits16plus-pretrain-lvd1689m",
|
| 37 |
+
"vitb16_lvd1689m": "facebook/dinov3-vitb16-pretrain-lvd1689m",
|
| 38 |
+
"vitl16_lvd1689m": "facebook/dinov3-vitl16-pretrain-lvd1689m",
|
| 39 |
+
"vitl16_sat493m": "facebook/dinov3-vitl16-pretrain-sat493m",
|
| 40 |
+
"vith16plus_lvd1689m": "facebook/dinov3-vith16plus-pretrain-lvd1689m",
|
| 41 |
+
"vit7b16_lvd1689m": "facebook/dinov3-vit7b16-pretrain-lvd1689m",
|
| 42 |
+
"vit7b16_sat493m": "facebook/dinov3-vit7b16-pretrain-sat493m",
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
HUB_CHECKPOINTS = {
|
| 46 |
+
"vits16_lvd1689m": "dinov3_vits16_pretrain_lvd1689m-08c60483.pth",
|
| 47 |
+
"vits16plus_lvd1689m": "dinov3_vits16plus_pretrain_lvd1689m-4057cbaa.pth",
|
| 48 |
+
"vitb16_lvd1689m": "dinov3_vitb16_pretrain_lvd1689m-73cec8be.pth",
|
| 49 |
+
"vitl16_lvd1689m": "dinov3_vitl16_pretrain_lvd1689m-8aa4cbdd.pth",
|
| 50 |
+
"vitl16_sat493m": "dinov3_vitl16_pretrain_sat493m-eadcf0ff.pth",
|
| 51 |
+
"vith16plus_lvd1689m": "dinov3_vith16plus_pretrain_lvd1689m-7c1da9a5.pth",
|
| 52 |
+
"vit7b16_lvd1689m": "dinov3_vit7b16_pretrain_lvd1689m-a955f4ea.pth",
|
| 53 |
+
"vit7b16_sat493m": "dinov3_vit7b16_pretrain_sat493m-a6675841.pth",
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
# fmt: off
|
| 57 |
+
ORIGINAL_TO_CONVERTED_KEY_MAPPING = {
|
| 58 |
+
r"cls_token": r"embeddings.cls_token",
|
| 59 |
+
r"mask_token": r"embeddings.mask_token",
|
| 60 |
+
r"storage_tokens": r"embeddings.register_tokens",
|
| 61 |
+
r"patch_embed.proj": r"embeddings.patch_embeddings",
|
| 62 |
+
r"periods": r"inv_freq",
|
| 63 |
+
r"rope_embed": r"rope_embeddings",
|
| 64 |
+
r"blocks.(\d+).attn.proj": r"layer.\1.attention.o_proj",
|
| 65 |
+
r"blocks.(\d+).attn.": r"layer.\1.attention.",
|
| 66 |
+
r"blocks.(\d+).ls(\d+).gamma": r"layer.\1.layer_scale\2.lambda1",
|
| 67 |
+
r"blocks.(\d+).mlp.fc1": r"layer.\1.mlp.up_proj",
|
| 68 |
+
r"blocks.(\d+).mlp.fc2": r"layer.\1.mlp.down_proj",
|
| 69 |
+
r"blocks.(\d+).mlp": r"layer.\1.mlp",
|
| 70 |
+
r"blocks.(\d+).norm": r"layer.\1.norm",
|
| 71 |
+
r"w1": r"gate_proj",
|
| 72 |
+
r"w2": r"up_proj",
|
| 73 |
+
r"w3": r"down_proj",
|
| 74 |
+
}
|
| 75 |
+
# fmt: on
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def convert_old_keys_to_new_keys(state_dict_keys: Optional[dict] = None):
|
| 79 |
+
"""
|
| 80 |
+
This function should be applied only once, on the concatenated keys to efficiently rename using
|
| 81 |
+
the key mappings.
|
| 82 |
+
"""
|
| 83 |
+
output_dict = {}
|
| 84 |
+
if state_dict_keys is not None:
|
| 85 |
+
old_text = "\n".join(state_dict_keys)
|
| 86 |
+
new_text = old_text
|
| 87 |
+
for pattern, replacement in ORIGINAL_TO_CONVERTED_KEY_MAPPING.items():
|
| 88 |
+
if replacement is None:
|
| 89 |
+
new_text = re.sub(pattern, "", new_text) # an empty line
|
| 90 |
+
continue
|
| 91 |
+
new_text = re.sub(pattern, replacement, new_text)
|
| 92 |
+
output_dict = dict(zip(old_text.split("\n"), new_text.split("\n")))
|
| 93 |
+
return output_dict
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def split_qkv(state_dict: dict):
|
| 97 |
+
keys = [x for x in state_dict.keys() if "qkv" in x]
|
| 98 |
+
for key in keys:
|
| 99 |
+
qkv = state_dict.pop(key)
|
| 100 |
+
q, k, v = torch.chunk(qkv, 3, dim=0)
|
| 101 |
+
state_dict[key.replace("qkv", "q_proj")] = q
|
| 102 |
+
state_dict[key.replace("qkv", "k_proj")] = k
|
| 103 |
+
state_dict[key.replace("qkv", "v_proj")] = v
|
| 104 |
+
return state_dict
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def get_dinov3_config(model_name: str) -> DINOv3ViTConfig:
|
| 108 |
+
# size of the architecture
|
| 109 |
+
if model_name == "vits16_lvd1689m":
|
| 110 |
+
return DINOv3ViTConfig(
|
| 111 |
+
patch_size=16,
|
| 112 |
+
hidden_size=384,
|
| 113 |
+
intermediate_size=1536,
|
| 114 |
+
num_hidden_layers=12,
|
| 115 |
+
num_attention_heads=6,
|
| 116 |
+
proj_bias=True,
|
| 117 |
+
num_register_tokens=4,
|
| 118 |
+
use_gated_mlp=False,
|
| 119 |
+
hidden_act="gelu",
|
| 120 |
+
)
|
| 121 |
+
elif model_name == "vits16plus_lvd1689m":
|
| 122 |
+
return DINOv3ViTConfig(
|
| 123 |
+
patch_size=16,
|
| 124 |
+
hidden_size=384,
|
| 125 |
+
intermediate_size=1536,
|
| 126 |
+
num_hidden_layers=12,
|
| 127 |
+
num_attention_heads=6,
|
| 128 |
+
num_register_tokens=4,
|
| 129 |
+
use_gated_mlp=True,
|
| 130 |
+
hidden_act="silu",
|
| 131 |
+
)
|
| 132 |
+
elif model_name == "vitb16_lvd1689m":
|
| 133 |
+
return DINOv3ViTConfig(
|
| 134 |
+
patch_size=16,
|
| 135 |
+
hidden_size=768,
|
| 136 |
+
intermediate_size=3072,
|
| 137 |
+
num_hidden_layers=12,
|
| 138 |
+
num_attention_heads=12,
|
| 139 |
+
proj_bias=True,
|
| 140 |
+
num_register_tokens=4,
|
| 141 |
+
use_gated_mlp=False,
|
| 142 |
+
hidden_act="gelu",
|
| 143 |
+
)
|
| 144 |
+
elif model_name in ("vitl16_lvd1689m", "vitl16_sat493m"):
|
| 145 |
+
return DINOv3ViTConfig(
|
| 146 |
+
patch_size=16,
|
| 147 |
+
hidden_size=1024,
|
| 148 |
+
intermediate_size=4096,
|
| 149 |
+
num_hidden_layers=24,
|
| 150 |
+
num_attention_heads=16,
|
| 151 |
+
num_register_tokens=4,
|
| 152 |
+
use_gated_mlp=False,
|
| 153 |
+
hidden_act="gelu",
|
| 154 |
+
)
|
| 155 |
+
elif model_name == "vith16plus_lvd1689m":
|
| 156 |
+
return DINOv3ViTConfig(
|
| 157 |
+
patch_size=16,
|
| 158 |
+
hidden_size=1280,
|
| 159 |
+
intermediate_size=5120,
|
| 160 |
+
num_hidden_layers=32,
|
| 161 |
+
num_attention_heads=20,
|
| 162 |
+
num_register_tokens=4,
|
| 163 |
+
use_gated_mlp=True,
|
| 164 |
+
hidden_act="silu",
|
| 165 |
+
)
|
| 166 |
+
elif model_name in ("vit7b16_lvd1689m", "vit7b16_sat493m"):
|
| 167 |
+
return DINOv3ViTConfig(
|
| 168 |
+
patch_size=16,
|
| 169 |
+
hidden_size=4096,
|
| 170 |
+
intermediate_size=8192,
|
| 171 |
+
num_hidden_layers=40,
|
| 172 |
+
num_attention_heads=32,
|
| 173 |
+
query_bias=False,
|
| 174 |
+
value_bias=False,
|
| 175 |
+
num_register_tokens=4,
|
| 176 |
+
use_gated_mlp=True,
|
| 177 |
+
hidden_act="silu",
|
| 178 |
+
)
|
| 179 |
+
else:
|
| 180 |
+
raise ValueError("Model not supported")
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def prepare_img():
|
| 184 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 185 |
+
image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
|
| 186 |
+
return image
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def get_transform(resize_size: int = 224):
|
| 190 |
+
to_tensor = transforms.ToTensor()
|
| 191 |
+
resize = transforms.Resize((resize_size, resize_size), antialias=True)
|
| 192 |
+
normalize = transforms.Normalize(
|
| 193 |
+
mean=(0.485, 0.456, 0.406),
|
| 194 |
+
std=(0.229, 0.224, 0.225),
|
| 195 |
+
)
|
| 196 |
+
return transforms.Compose([to_tensor, resize, normalize])
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def get_image_processor(resize_size: int = 224):
|
| 200 |
+
return DINOv3ViTImageProcessorFast(
|
| 201 |
+
do_resize=True,
|
| 202 |
+
size={"height": resize_size, "width": resize_size},
|
| 203 |
+
resample=2, # BILINEAR
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
@torch.no_grad()
|
| 208 |
+
def convert_and_test_dinov3_checkpoint(args):
|
| 209 |
+
expected_outputs = {
|
| 210 |
+
"vits16_lvd1689m_cls": [0.463561, -0.415609, 0.408236, -0.126613, -0.286636],
|
| 211 |
+
"vits16_lvd1689m_patch": [-0.038754, -0.250895, -0.016392, -0.455473, 0.571582],
|
| 212 |
+
"vits16plus_lvd1689m_cls": [-0.471349, -1.365778, -0.317983, 0.377219, -0.769085],
|
| 213 |
+
"vits16plus_lvd1689m_patch": [0.144551, -0.388117, -0.393433, -0.157695, -0.600380],
|
| 214 |
+
"vitb16_lvd1689m_cls": [1.034643, -0.180609, -0.341018, -0.066376, -0.011383],
|
| 215 |
+
"vitb16_lvd1689m_patch": [-0.082523, -0.456272, -0.728029, -0.430680, -0.152880],
|
| 216 |
+
"vitl16_lvd1689m_cls": [0.484527, -0.582214, 0.480636, 0.592040, 0.945166],
|
| 217 |
+
"vitl16_lvd1689m_patch": [-0.211367, -0.490863, -0.257131, 0.101763, 0.154511],
|
| 218 |
+
"vith16plus_lvd1689m_cls": [-0.064575, -0.148866, -0.621524, 0.634878, 0.152695],
|
| 219 |
+
"vith16plus_lvd1689m_patch": [-0.093817, 0.287407, -0.050036, 0.428043, 0.094561],
|
| 220 |
+
"vit7b16_lvd1689m_cls": [0.275439, -0.261353, 0.067772, 0.049936, -0.158747],
|
| 221 |
+
"vit7b16_lvd1689m_patch": [0.044442, -0.052542, 0.070777, -0.065111, -0.026546],
|
| 222 |
+
"vitl16_sat493m_cls": [-0.33235, 0.34052, -0.22087, 0.21434, 0.09003],
|
| 223 |
+
"vitl16_sat493m_patch": [0.18488, 0.30309, -0.20689, 0.12848, 0.06207],
|
| 224 |
+
"vit7b16_sat493m_cls": [-0.19779, 0.11819, -0.00581, -0.21055, -0.03971],
|
| 225 |
+
"vit7b16_sat493m_patch": [-0.12423, 0.07879, -0.10057, 0.02835, -0.11727],
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
model_name = args.model_name
|
| 229 |
+
config = get_dinov3_config(model_name)
|
| 230 |
+
|
| 231 |
+
model = DINOv3ViTModel(config).eval()
|
| 232 |
+
state_dict_path = hf_hub_download(repo_id=HUB_MODELS[model_name], filename=HUB_CHECKPOINTS[model_name])
|
| 233 |
+
original_state_dict = torch.load(state_dict_path, mmap=True)
|
| 234 |
+
|
| 235 |
+
original_state_dict = split_qkv(original_state_dict)
|
| 236 |
+
original_keys = list(original_state_dict.keys())
|
| 237 |
+
new_keys = convert_old_keys_to_new_keys(original_keys)
|
| 238 |
+
|
| 239 |
+
converted_state_dict = {}
|
| 240 |
+
for key in original_keys:
|
| 241 |
+
new_key = new_keys[key]
|
| 242 |
+
weight_tensor = original_state_dict[key]
|
| 243 |
+
|
| 244 |
+
if "bias_mask" in key or "attn.k_proj.bias" in key or "local_cls_norm" in key:
|
| 245 |
+
continue
|
| 246 |
+
if "embeddings.mask_token" in new_key:
|
| 247 |
+
weight_tensor = weight_tensor.unsqueeze(1)
|
| 248 |
+
if "inv_freq" in new_key:
|
| 249 |
+
continue
|
| 250 |
+
|
| 251 |
+
converted_state_dict[new_key] = weight_tensor
|
| 252 |
+
|
| 253 |
+
model.load_state_dict(converted_state_dict, strict=True)
|
| 254 |
+
model = model.eval()
|
| 255 |
+
|
| 256 |
+
transform = get_transform()
|
| 257 |
+
image_processor = get_image_processor()
|
| 258 |
+
image = prepare_img()
|
| 259 |
+
|
| 260 |
+
# check preprocessing
|
| 261 |
+
original_pixel_values = transform(image).unsqueeze(0) # add batch dimension
|
| 262 |
+
inputs = image_processor(image, return_tensors="pt")
|
| 263 |
+
|
| 264 |
+
torch.testing.assert_close(original_pixel_values, inputs["pixel_values"], atol=1e-6, rtol=1e-6)
|
| 265 |
+
print("Preprocessing looks ok!")
|
| 266 |
+
|
| 267 |
+
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.float):
|
| 268 |
+
model_output = model(**inputs)
|
| 269 |
+
|
| 270 |
+
last_layer_class_token = model_output.pooler_output
|
| 271 |
+
last_layer_patch_tokens = model_output.last_hidden_state[:, config.num_register_tokens + 1 :]
|
| 272 |
+
|
| 273 |
+
actual_outputs = {}
|
| 274 |
+
actual_outputs[f"{model_name}_cls"] = last_layer_class_token[0, :5].tolist()
|
| 275 |
+
actual_outputs[f"{model_name}_patch"] = last_layer_patch_tokens[0, 0, :5].tolist()
|
| 276 |
+
|
| 277 |
+
print("Actual: ", [round(x, 6) for x in actual_outputs[f"{model_name}_cls"]])
|
| 278 |
+
print("Expected:", expected_outputs[f"{model_name}_cls"])
|
| 279 |
+
|
| 280 |
+
torch.testing.assert_close(
|
| 281 |
+
torch.Tensor(actual_outputs[f"{model_name}_cls"]),
|
| 282 |
+
torch.Tensor(expected_outputs[f"{model_name}_cls"]),
|
| 283 |
+
atol=1e-3,
|
| 284 |
+
rtol=1e-3,
|
| 285 |
+
)
|
| 286 |
+
torch.testing.assert_close(
|
| 287 |
+
torch.Tensor(actual_outputs[f"{model_name}_patch"]),
|
| 288 |
+
torch.Tensor(expected_outputs[f"{model_name}_patch"]),
|
| 289 |
+
atol=1e-3,
|
| 290 |
+
rtol=1e-3,
|
| 291 |
+
)
|
| 292 |
+
print("Forward pass looks ok!")
|
| 293 |
+
|
| 294 |
+
save_dir = os.path.join(args.save_dir, model_name)
|
| 295 |
+
os.makedirs(save_dir, exist_ok=True)
|
| 296 |
+
model.save_pretrained(save_dir)
|
| 297 |
+
image_processor.save_pretrained(save_dir)
|
| 298 |
+
print(f"Model saved to {save_dir}")
|
| 299 |
+
|
| 300 |
+
if args.push_to_hub:
|
| 301 |
+
api = HfApi()
|
| 302 |
+
repo = HUB_MODELS[model_name]
|
| 303 |
+
api.upload_folder(folder_path=save_dir, repo_id=repo, repo_type="model")
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
if __name__ == "__main__":
|
| 307 |
+
parser = argparse.ArgumentParser()
|
| 308 |
+
# Required parameters
|
| 309 |
+
parser.add_argument(
|
| 310 |
+
"--model-name",
|
| 311 |
+
default="vith16plus_lvd1689m",
|
| 312 |
+
type=str,
|
| 313 |
+
choices=[
|
| 314 |
+
"vits16_lvd1689m",
|
| 315 |
+
"vits16plus_lvd1689m",
|
| 316 |
+
"vitb16_lvd1689m",
|
| 317 |
+
"vitl16_lvd1689m",
|
| 318 |
+
"vitl16_sat493m",
|
| 319 |
+
"vith16plus_lvd1689m",
|
| 320 |
+
"vit7b16_lvd1689m",
|
| 321 |
+
"vit7b16_sat493m",
|
| 322 |
+
],
|
| 323 |
+
help="Name of the model you'd like to convert.",
|
| 324 |
+
)
|
| 325 |
+
parser.add_argument(
|
| 326 |
+
"--save-dir",
|
| 327 |
+
default="converted_models",
|
| 328 |
+
type=str,
|
| 329 |
+
help="Directory to save the converted model.",
|
| 330 |
+
)
|
| 331 |
+
parser.add_argument(
|
| 332 |
+
"--push-to-hub",
|
| 333 |
+
action="store_true",
|
| 334 |
+
help="Push the converted model to the Hugging Face Hub.",
|
| 335 |
+
)
|
| 336 |
+
args = parser.parse_args()
|
| 337 |
+
convert_and_test_dinov3_checkpoint(args)
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_vit/image_processing_dinov3_vit_fast.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Fast Image processor class for DINOv3."""
|
| 16 |
+
|
| 17 |
+
from typing import Optional, Union
|
| 18 |
+
|
| 19 |
+
from transformers.image_processing_base import BatchFeature
|
| 20 |
+
from transformers.image_processing_utils_fast import BaseImageProcessorFast, group_images_by_shape, reorder_images
|
| 21 |
+
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling, SizeDict
|
| 22 |
+
from transformers.utils import (
|
| 23 |
+
TensorType,
|
| 24 |
+
auto_docstring,
|
| 25 |
+
is_torch_available,
|
| 26 |
+
is_torchvision_available,
|
| 27 |
+
is_torchvision_v2_available,
|
| 28 |
+
logging,
|
| 29 |
+
)
|
| 30 |
+
from transformers.utils.import_utils import requires
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if is_torch_available():
|
| 37 |
+
import torch
|
| 38 |
+
|
| 39 |
+
if is_torchvision_v2_available():
|
| 40 |
+
from torchvision.transforms.v2 import functional as F
|
| 41 |
+
elif is_torchvision_available():
|
| 42 |
+
from torchvision.transforms import functional as F
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@auto_docstring
|
| 46 |
+
@requires(backends=("torchvision", "torch"))
|
| 47 |
+
class DINOv3ViTImageProcessorFast(BaseImageProcessorFast):
|
| 48 |
+
resample = PILImageResampling.BILINEAR
|
| 49 |
+
image_mean = IMAGENET_DEFAULT_MEAN
|
| 50 |
+
image_std = IMAGENET_DEFAULT_STD
|
| 51 |
+
size = {"height": 224, "width": 224}
|
| 52 |
+
do_resize = True
|
| 53 |
+
do_rescale = True
|
| 54 |
+
do_normalize = True
|
| 55 |
+
|
| 56 |
+
# Overriden for DINOv3 to preserve order of transforms
|
| 57 |
+
# rescale -> resize -> normalize
|
| 58 |
+
def _preprocess(
|
| 59 |
+
self,
|
| 60 |
+
images: list["torch.Tensor"],
|
| 61 |
+
do_resize: bool,
|
| 62 |
+
size: SizeDict,
|
| 63 |
+
interpolation: Optional["F.InterpolationMode"],
|
| 64 |
+
do_center_crop: bool,
|
| 65 |
+
crop_size: SizeDict,
|
| 66 |
+
do_rescale: bool,
|
| 67 |
+
rescale_factor: float,
|
| 68 |
+
do_normalize: bool,
|
| 69 |
+
image_mean: Optional[Union[float, list[float]]],
|
| 70 |
+
image_std: Optional[Union[float, list[float]]],
|
| 71 |
+
disable_grouping: Optional[bool],
|
| 72 |
+
return_tensors: Optional[Union[str, TensorType]],
|
| 73 |
+
) -> BatchFeature:
|
| 74 |
+
# Group images by size for batched resizing
|
| 75 |
+
grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
|
| 76 |
+
resized_images_grouped = {}
|
| 77 |
+
for shape, stacked_images in grouped_images.items():
|
| 78 |
+
if do_rescale:
|
| 79 |
+
stacked_images = self.rescale(stacked_images, rescale_factor)
|
| 80 |
+
if do_resize:
|
| 81 |
+
stacked_images = self.resize(
|
| 82 |
+
image=stacked_images, size=size, interpolation=interpolation, antialias=True
|
| 83 |
+
)
|
| 84 |
+
resized_images_grouped[shape] = stacked_images
|
| 85 |
+
resized_images = reorder_images(resized_images_grouped, grouped_images_index)
|
| 86 |
+
|
| 87 |
+
# Group images by size for further processing
|
| 88 |
+
# Needed in case do_resize is False, or resize returns images with different sizes
|
| 89 |
+
grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
|
| 90 |
+
processed_images_grouped = {}
|
| 91 |
+
for shape, stacked_images in grouped_images.items():
|
| 92 |
+
if do_center_crop:
|
| 93 |
+
stacked_images = self.center_crop(stacked_images, crop_size)
|
| 94 |
+
if do_normalize:
|
| 95 |
+
stacked_images = self.normalize(stacked_images, image_mean, image_std)
|
| 96 |
+
processed_images_grouped[shape] = stacked_images
|
| 97 |
+
|
| 98 |
+
processed_images = reorder_images(processed_images_grouped, grouped_images_index)
|
| 99 |
+
processed_images = torch.stack(processed_images, dim=0) if return_tensors else processed_images
|
| 100 |
+
|
| 101 |
+
return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
__all__ = ["DINOv3ViTImageProcessorFast"]
|
tasks/tasksmith-5cbfd9f64dbc/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/dinov3_vit/modular_dinov3_vit.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_dinov3_vit.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 Meta AI and The HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
|
| 22 |
+
import math
|
| 23 |
+
from typing import Callable, Optional
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
import torch
|
| 27 |
+
from torch import nn
|
| 28 |
+
|
| 29 |
+
from ...activations import ACT2FN
|
| 30 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 31 |
+
from ...modeling_outputs import BaseModelOutputWithPooling
|
| 32 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 33 |
+
from ...processing_utils import Unpack
|
| 34 |
+
from ...pytorch_utils import compile_compatible_method_lru_cache
|
| 35 |
+
from ...utils import TransformersKwargs, auto_docstring
|
| 36 |
+
from ...utils.generic import check_model_inputs
|
| 37 |
+
from .configuration_dinov3_vit import DINOv3ViTConfig
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class DINOv3ViTEmbeddings(nn.Module):
|
| 41 |
+
"""
|
| 42 |
+
Construct the CLS token, mask token, position and patch embeddings.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 46 |
+
super().__init__()
|
| 47 |
+
self.config = config
|
| 48 |
+
self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
| 49 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 50 |
+
self.register_tokens = nn.Parameter(torch.empty(1, config.num_register_tokens, config.hidden_size))
|
| 51 |
+
self.patch_embeddings = nn.Conv2d(
|
| 52 |
+
config.num_channels, config.hidden_size, kernel_size=config.patch_size, stride=config.patch_size
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
def forward(self, pixel_values: torch.Tensor, bool_masked_pos: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 56 |
+
batch_size = pixel_values.shape[0]
|
| 57 |
+
target_dtype = self.patch_embeddings.weight.dtype
|
| 58 |
+
|
| 59 |
+
# (batch_size, num_channels, height, width) -> (batch_size, num_patches, hidden_size)
|
| 60 |
+
patch_embeddings = self.patch_embeddings(pixel_values.to(dtype=target_dtype))
|
| 61 |
+
patch_embeddings = patch_embeddings.flatten(2).transpose(1, 2)
|
| 62 |
+
|
| 63 |
+
if bool_masked_pos is not None:
|
| 64 |
+
mask_token = self.mask_token.to(patch_embeddings.dtype)
|
| 65 |
+
patch_embeddings = torch.where(bool_masked_pos.unsqueeze(-1), mask_token, patch_embeddings)
|
| 66 |
+
|
| 67 |
+
# Add CLS and register tokens
|
| 68 |
+
cls_token = self.cls_token.expand(batch_size, -1, -1)
|
| 69 |
+
register_tokens = self.register_tokens.expand(batch_size, -1, -1)
|
| 70 |
+
embeddings = torch.cat([cls_token, register_tokens, patch_embeddings], dim=1)
|
| 71 |
+
|
| 72 |
+
return embeddings
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@compile_compatible_method_lru_cache(maxsize=32)
|
| 76 |
+
def get_patches_center_coordinates(
|
| 77 |
+
num_patches_h: int, num_patches_w: int, dtype: torch.dtype, device: torch.device
|
| 78 |
+
) -> torch.Tensor:
|
| 79 |
+
"""
|
| 80 |
+
Computes the 2D coordinates of the centers of image patches, normalized to the range [-1, +1].
|
| 81 |
+
The center of each patch is exactly halfway between its top-left and bottom-right corners.
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
num_patches_h (int): Number of patches along the vertical (height) axis.
|
| 85 |
+
num_patches_w (int): Number of patches along the horizontal (width) axis.
|
| 86 |
+
dtype (torch.dtype): The desired data type of the returned tensor.
|
| 87 |
+
|
| 88 |
+
Returns:
|
| 89 |
+
torch.Tensor: A tensor of shape (height * width, 2), where each row contains the (y, x)
|
| 90 |
+
coordinates of a patch center, normalized to [-1, +1].
|
| 91 |
+
"""
|
| 92 |
+
coords_h = torch.arange(0.5, num_patches_h, dtype=dtype, device=device)
|
| 93 |
+
coords_w = torch.arange(0.5, num_patches_w, dtype=dtype, device=device)
|
| 94 |
+
coords_h = coords_h / num_patches_h
|
| 95 |
+
coords_w = coords_w / num_patches_w
|
| 96 |
+
# (height, width, 2) -> (height * width, 2)
|
| 97 |
+
coords = torch.stack(torch.meshgrid(coords_h, coords_w, indexing="ij"), dim=-1)
|
| 98 |
+
coords = coords.flatten(0, 1)
|
| 99 |
+
# Shift range [0, 1] to [-1, +1]
|
| 100 |
+
coords = 2.0 * coords - 1.0
|
| 101 |
+
return coords
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def augment_patches_center_coordinates(
|
| 105 |
+
coords: torch.Tensor,
|
| 106 |
+
shift: Optional[float] = None,
|
| 107 |
+
jitter: Optional[float] = None,
|
| 108 |
+
rescale: Optional[float] = None,
|
| 109 |
+
) -> torch.Tensor:
|
| 110 |
+
# Shift coords by adding a uniform value in [-shift, shift]
|
| 111 |
+
if shift is not None:
|
| 112 |
+
shift_hw = torch.empty((1, 2), device=coords.device, dtype=coords.dtype)
|
| 113 |
+
shift_hw = shift_hw.uniform_(-shift, shift)
|
| 114 |
+
coords = coords + shift_hw
|
| 115 |
+
|
| 116 |
+
# Jitter coords by multiplying the range [-1, 1] by a log-uniform value in [1/jitter, jitter]
|
| 117 |
+
if jitter is not None:
|
| 118 |
+
jitter_range = np.log(jitter)
|
| 119 |
+
jitter_hw = torch.empty((1, 2), device=coords.device, dtype=coords.dtype)
|
| 120 |
+
jitter_hw = jitter_hw.uniform_(-jitter_range, jitter_range).exp()
|
| 121 |
+
coords = coords * jitter_hw
|
| 122 |
+
|
| 123 |
+
# Rescale coords by multiplying the range [-1, 1] by a log-uniform value in [1/rescale, rescale]
|
| 124 |
+
if rescale is not None:
|
| 125 |
+
rescale_range = np.log(rescale)
|
| 126 |
+
rescale_hw = torch.empty(1, device=coords.device, dtype=coords.dtype)
|
| 127 |
+
rescale_hw = rescale_hw.uniform_(-rescale_range, rescale_range).exp()
|
| 128 |
+
coords = coords * rescale_hw
|
| 129 |
+
|
| 130 |
+
return coords
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class DINOv3ViTRopePositionEmbedding(nn.Module):
|
| 134 |
+
inv_freq: torch.Tensor
|
| 135 |
+
|
| 136 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 137 |
+
super().__init__()
|
| 138 |
+
|
| 139 |
+
self.config = config
|
| 140 |
+
self.base = config.rope_theta
|
| 141 |
+
self.head_dim = config.hidden_size // config.num_attention_heads
|
| 142 |
+
self.num_patches_h = config.image_size // config.patch_size
|
| 143 |
+
self.num_patches_w = config.image_size // config.patch_size
|
| 144 |
+
|
| 145 |
+
inv_freq = 1 / self.base ** torch.arange(0, 1, 4 / self.head_dim, dtype=torch.float32) # (head_dim / 4,)
|
| 146 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 147 |
+
|
| 148 |
+
def forward(self, pixel_values: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 149 |
+
_, _, height, width = pixel_values.shape
|
| 150 |
+
num_patches_h = height // self.config.patch_size
|
| 151 |
+
num_patches_w = width // self.config.patch_size
|
| 152 |
+
|
| 153 |
+
device = pixel_values.device
|
| 154 |
+
device_type = device.type if isinstance(device.type, str) and device.type != "mps" else "cpu"
|
| 155 |
+
|
| 156 |
+
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
| 157 |
+
# Although we could precompute static patch_coords from image_size and patch_size in the config,
|
| 158 |
+
# the model was trained with random_scale, so it can process images of varying sizes.
|
| 159 |
+
# Therefore, it's better to compute patch_coords dynamically (with lru_cache).
|
| 160 |
+
patch_coords = get_patches_center_coordinates(
|
| 161 |
+
num_patches_h, num_patches_w, dtype=torch.float32, device=device
|
| 162 |
+
)
|
| 163 |
+
if self.training:
|
| 164 |
+
patch_coords = augment_patches_center_coordinates(
|
| 165 |
+
patch_coords,
|
| 166 |
+
shift=self.config.pos_embed_shift,
|
| 167 |
+
jitter=self.config.pos_embed_jitter,
|
| 168 |
+
rescale=self.config.pos_embed_rescale,
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
# (height * width, 2, head_dim / 4) -> (height * width, head_dim / 2) -> (height * width, head_dim)
|
| 172 |
+
angles = 2 * math.pi * patch_coords[:, :, None] * self.inv_freq[None, None, :]
|
| 173 |
+
angles = angles.flatten(1, 2)
|
| 174 |
+
angles = angles.tile(2)
|
| 175 |
+
|
| 176 |
+
cos = torch.cos(angles)
|
| 177 |
+
sin = torch.sin(angles)
|
| 178 |
+
|
| 179 |
+
dtype = pixel_values.dtype
|
| 180 |
+
return cos.to(dtype=dtype), sin.to(dtype=dtype)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def rotate_half(x):
|
| 184 |
+
"""Rotates half the hidden dims of the input."""
|
| 185 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 186 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 187 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def eager_attention_forward(
|
| 191 |
+
module: nn.Module,
|
| 192 |
+
query: torch.Tensor,
|
| 193 |
+
key: torch.Tensor,
|
| 194 |
+
value: torch.Tensor,
|
| 195 |
+
attention_mask: Optional[torch.Tensor],
|
| 196 |
+
scaling: float,
|
| 197 |
+
dropout: float = 0.0,
|
| 198 |
+
**kwargs,
|
| 199 |
+
):
|
| 200 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 201 |
+
attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
|
| 202 |
+
|
| 203 |
+
# Normalize the attention scores to probabilities.
|
| 204 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 205 |
+
|
| 206 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 207 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 208 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 209 |
+
|
| 210 |
+
# Mask heads if we want to
|
| 211 |
+
if attention_mask is not None:
|
| 212 |
+
attn_weights = attn_weights * attention_mask
|
| 213 |
+
|
| 214 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 215 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 216 |
+
|
| 217 |
+
return attn_output, attn_weights
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def apply_rotary_pos_emb(
|
| 221 |
+
q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, **kwargs
|
| 222 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 223 |
+
"""Applies Rotary Position Embedding to the query and key tensors, but only to the patch tokens,
|
| 224 |
+
ignoring the prefix tokens (cls token and register tokens).
|
| 225 |
+
|
| 226 |
+
Args:
|
| 227 |
+
q (`torch.Tensor`): The query tensor.
|
| 228 |
+
k (`torch.Tensor`): The key tensor.
|
| 229 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 230 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 231 |
+
|
| 232 |
+
Returns:
|
| 233 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 234 |
+
"""
|
| 235 |
+
|
| 236 |
+
num_tokens = q.shape[-2]
|
| 237 |
+
num_patches = sin.shape[-2]
|
| 238 |
+
num_prefix_tokens = num_tokens - num_patches # cls token + register tokens
|
| 239 |
+
|
| 240 |
+
q_prefix_tokens, q_patches = q.split((num_prefix_tokens, num_patches), dim=-2)
|
| 241 |
+
k_prefix_tokens, k_patches = k.split((num_prefix_tokens, num_patches), dim=-2)
|
| 242 |
+
|
| 243 |
+
# apply rope only to patch tokens
|
| 244 |
+
q_patches = (q_patches * cos) + (rotate_half(q_patches) * sin)
|
| 245 |
+
k_patches = (k_patches * cos) + (rotate_half(k_patches) * sin)
|
| 246 |
+
|
| 247 |
+
q = torch.cat((q_prefix_tokens, q_patches), dim=-2)
|
| 248 |
+
k = torch.cat((k_prefix_tokens, k_patches), dim=-2)
|
| 249 |
+
|
| 250 |
+
return q, k
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
class DINOv3ViTAttention(nn.Module):
|
| 254 |
+
"""
|
| 255 |
+
Multi-headed attention compatible with ALL_ATTENTION_FUNCTIONS.
|
| 256 |
+
"""
|
| 257 |
+
|
| 258 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 259 |
+
super().__init__()
|
| 260 |
+
self.config = config
|
| 261 |
+
self.embed_dim = config.hidden_size
|
| 262 |
+
self.num_heads = config.num_attention_heads
|
| 263 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 264 |
+
self.is_causal = False
|
| 265 |
+
|
| 266 |
+
self.scaling = self.head_dim**-0.5
|
| 267 |
+
self.is_causal = False
|
| 268 |
+
|
| 269 |
+
self.dropout = config.attention_dropout
|
| 270 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.key_bias)
|
| 271 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.value_bias)
|
| 272 |
+
|
| 273 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.query_bias)
|
| 274 |
+
self.o_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.proj_bias)
|
| 275 |
+
|
| 276 |
+
def forward(
|
| 277 |
+
self,
|
| 278 |
+
hidden_states: torch.Tensor,
|
| 279 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 280 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
| 281 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 282 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 283 |
+
"""Input shape: Batch x Time x Channel"""
|
| 284 |
+
|
| 285 |
+
batch_size, patches, _ = hidden_states.size()
|
| 286 |
+
|
| 287 |
+
query_states = self.q_proj(hidden_states)
|
| 288 |
+
key_states = self.k_proj(hidden_states)
|
| 289 |
+
value_states = self.v_proj(hidden_states)
|
| 290 |
+
|
| 291 |
+
query_states = query_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
|
| 292 |
+
key_states = key_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
|
| 293 |
+
value_states = value_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
|
| 294 |
+
|
| 295 |
+
cos, sin = position_embeddings
|
| 296 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 297 |
+
|
| 298 |
+
attention_interface: Callable = eager_attention_forward
|
| 299 |
+
if self.config._attn_implementation != "eager":
|
| 300 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 301 |
+
|
| 302 |
+
attn_output, attn_weights = attention_interface(
|
| 303 |
+
self,
|
| 304 |
+
query_states,
|
| 305 |
+
key_states,
|
| 306 |
+
value_states,
|
| 307 |
+
attention_mask,
|
| 308 |
+
dropout=0.0 if not self.training else self.dropout,
|
| 309 |
+
scaling=self.scaling,
|
| 310 |
+
**kwargs,
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
attn_output = attn_output.reshape(batch_size, patches, -1).contiguous()
|
| 314 |
+
attn_output = self.o_proj(attn_output)
|
| 315 |
+
|
| 316 |
+
return attn_output, attn_weights
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class DINOv3ViTLayerScale(nn.Module):
|
| 320 |
+
def __init__(self, config) -> None:
|
| 321 |
+
super().__init__()
|
| 322 |
+
self.lambda1 = nn.Parameter(config.layerscale_value * torch.ones(config.hidden_size))
|
| 323 |
+
|
| 324 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 325 |
+
return hidden_state * self.lambda1
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
|
| 329 |
+
"""
|
| 330 |
+
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 331 |
+
|
| 332 |
+
Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
|
| 333 |
+
however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
|
| 334 |
+
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
|
| 335 |
+
layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
|
| 336 |
+
argument.
|
| 337 |
+
"""
|
| 338 |
+
if drop_prob == 0.0 or not training:
|
| 339 |
+
return input
|
| 340 |
+
keep_prob = 1 - drop_prob
|
| 341 |
+
shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 342 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
|
| 343 |
+
random_tensor.floor_() # binarize
|
| 344 |
+
output = input.div(keep_prob) * random_tensor
|
| 345 |
+
return output
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
class DINOv3ViTDropPath(nn.Module):
|
| 349 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 350 |
+
|
| 351 |
+
def __init__(self, drop_prob: Optional[float] = None) -> None:
|
| 352 |
+
super().__init__()
|
| 353 |
+
self.drop_prob = drop_prob
|
| 354 |
+
|
| 355 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 356 |
+
return drop_path(hidden_states, self.drop_prob, self.training)
|
| 357 |
+
|
| 358 |
+
def extra_repr(self) -> str:
|
| 359 |
+
return f"p={self.drop_prob}"
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
class DINOv3ViTMLP(nn.Module):
|
| 363 |
+
def __init__(self, config):
|
| 364 |
+
super().__init__()
|
| 365 |
+
self.config = config
|
| 366 |
+
self.hidden_size = config.hidden_size
|
| 367 |
+
self.intermediate_size = config.intermediate_size
|
| 368 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 369 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
| 370 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 371 |
+
|
| 372 |
+
def forward(self, x):
|
| 373 |
+
return self.down_proj(self.act_fn(self.up_proj(x)))
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
class DINOv3ViTGatedMLP(nn.Module):
|
| 377 |
+
def __init__(self, config):
|
| 378 |
+
super().__init__()
|
| 379 |
+
self.config = config
|
| 380 |
+
self.hidden_size = config.hidden_size
|
| 381 |
+
self.intermediate_size = config.intermediate_size
|
| 382 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 383 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 384 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
| 385 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 386 |
+
|
| 387 |
+
def forward(self, x):
|
| 388 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 389 |
+
return down_proj
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
class DINOv3ViTLayer(GradientCheckpointingLayer):
|
| 393 |
+
"""This corresponds to the Block class in the original implementation."""
|
| 394 |
+
|
| 395 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 396 |
+
super().__init__()
|
| 397 |
+
|
| 398 |
+
self.norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 399 |
+
self.attention = DINOv3ViTAttention(config)
|
| 400 |
+
self.layer_scale1 = DINOv3ViTLayerScale(config)
|
| 401 |
+
self.drop_path = DINOv3ViTDropPath(config.drop_path_rate) if config.drop_path_rate > 0.0 else nn.Identity()
|
| 402 |
+
|
| 403 |
+
self.norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 404 |
+
|
| 405 |
+
if config.use_gated_mlp:
|
| 406 |
+
self.mlp = DINOv3ViTGatedMLP(config)
|
| 407 |
+
else:
|
| 408 |
+
self.mlp = DINOv3ViTMLP(config)
|
| 409 |
+
self.layer_scale2 = DINOv3ViTLayerScale(config)
|
| 410 |
+
|
| 411 |
+
def forward(
|
| 412 |
+
self,
|
| 413 |
+
hidden_states: torch.Tensor,
|
| 414 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 415 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
| 416 |
+
) -> torch.Tensor:
|
| 417 |
+
# Attention with residual connection
|
| 418 |
+
residual = hidden_states
|
| 419 |
+
hidden_states = self.norm1(hidden_states)
|
| 420 |
+
hidden_states, _ = self.attention(
|
| 421 |
+
hidden_states,
|
| 422 |
+
attention_mask=attention_mask,
|
| 423 |
+
position_embeddings=position_embeddings,
|
| 424 |
+
)
|
| 425 |
+
hidden_states = self.layer_scale1(hidden_states)
|
| 426 |
+
hidden_states = self.drop_path(hidden_states) + residual
|
| 427 |
+
|
| 428 |
+
# MLP with residual connection
|
| 429 |
+
residual = hidden_states
|
| 430 |
+
hidden_states = self.norm2(hidden_states)
|
| 431 |
+
hidden_states = self.mlp(hidden_states)
|
| 432 |
+
hidden_states = self.layer_scale2(hidden_states)
|
| 433 |
+
hidden_states = self.drop_path(hidden_states) + residual
|
| 434 |
+
|
| 435 |
+
return hidden_states
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
@auto_docstring
|
| 439 |
+
class DINOv3ViTPreTrainedModel(PreTrainedModel):
|
| 440 |
+
config: DINOv3ViTConfig
|
| 441 |
+
base_model_prefix = "dinov3_vit"
|
| 442 |
+
main_input_name = "pixel_values"
|
| 443 |
+
supports_gradient_checkpointing = True
|
| 444 |
+
_no_split_modules = ["DINOv3ViTLayer"]
|
| 445 |
+
_supports_sdpa = True
|
| 446 |
+
_supports_flash_attn = True
|
| 447 |
+
_supports_flex_attn = True
|
| 448 |
+
_supports_attention_backend = True
|
| 449 |
+
_can_record_outputs = {
|
| 450 |
+
"hidden_states": DINOv3ViTLayer,
|
| 451 |
+
"attentions": DINOv3ViTAttention,
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
def _init_weights(self, module) -> None:
|
| 455 |
+
"""Initialize the weights"""
|
| 456 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 457 |
+
# Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
|
| 458 |
+
# `trunc_normal_cpu` not implemented in `half` issues
|
| 459 |
+
module.weight.data = nn.init.trunc_normal_(
|
| 460 |
+
module.weight.data.to(torch.float32),
|
| 461 |
+
mean=0.0,
|
| 462 |
+
std=self.config.initializer_range,
|
| 463 |
+
).to(module.weight.dtype)
|
| 464 |
+
if module.bias is not None:
|
| 465 |
+
module.bias.data.zero_()
|
| 466 |
+
elif isinstance(module, nn.LayerNorm):
|
| 467 |
+
module.bias.data.zero_()
|
| 468 |
+
module.weight.data.fill_(1.0)
|
| 469 |
+
elif isinstance(module, DINOv3ViTEmbeddings):
|
| 470 |
+
module.cls_token.data = nn.init.trunc_normal_(
|
| 471 |
+
module.cls_token.data.to(torch.float32),
|
| 472 |
+
mean=0.0,
|
| 473 |
+
std=self.config.initializer_range,
|
| 474 |
+
).to(module.cls_token.dtype)
|
| 475 |
+
if module.config.num_register_tokens > 0:
|
| 476 |
+
module.register_tokens.data = nn.init.trunc_normal_(
|
| 477 |
+
module.register_tokens.data.to(torch.float32),
|
| 478 |
+
mean=0.0,
|
| 479 |
+
std=self.config.initializer_range,
|
| 480 |
+
).to(module.register_tokens.dtype)
|
| 481 |
+
module.mask_token.data.zero_()
|
| 482 |
+
elif isinstance(module, DINOv3ViTLayerScale):
|
| 483 |
+
module.lambda1.data.fill_(self.config.layerscale_value)
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
@auto_docstring
|
| 487 |
+
class DINOv3ViTModel(DINOv3ViTPreTrainedModel):
|
| 488 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 489 |
+
super().__init__(config)
|
| 490 |
+
self.config = config
|
| 491 |
+
self.embeddings = DINOv3ViTEmbeddings(config)
|
| 492 |
+
self.rope_embeddings = DINOv3ViTRopePositionEmbedding(config)
|
| 493 |
+
self.layer = nn.ModuleList([DINOv3ViTLayer(config) for _ in range(config.num_hidden_layers)])
|
| 494 |
+
self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 495 |
+
self.gradient_checkpointing = False
|
| 496 |
+
# Initialize weights and apply final processing
|
| 497 |
+
self.post_init()
|
| 498 |
+
|
| 499 |
+
def get_input_embeddings(self):
|
| 500 |
+
return self.embeddings.patch_embeddings
|
| 501 |
+
|
| 502 |
+
@check_model_inputs
|
| 503 |
+
@auto_docstring
|
| 504 |
+
def forward(
|
| 505 |
+
self,
|
| 506 |
+
pixel_values: torch.Tensor,
|
| 507 |
+
bool_masked_pos: Optional[torch.Tensor] = None,
|
| 508 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 509 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 510 |
+
) -> BaseModelOutputWithPooling:
|
| 511 |
+
r"""
|
| 512 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
|
| 513 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0). Only relevant for
|
| 514 |
+
pre-training.
|
| 515 |
+
"""
|
| 516 |
+
|
| 517 |
+
pixel_values = pixel_values.to(self.embeddings.patch_embeddings.weight.dtype)
|
| 518 |
+
hidden_states = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
|
| 519 |
+
position_embeddings = self.rope_embeddings(pixel_values)
|
| 520 |
+
|
| 521 |
+
for i, layer_module in enumerate(self.layer):
|
| 522 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 523 |
+
hidden_states = layer_module(
|
| 524 |
+
hidden_states,
|
| 525 |
+
attention_mask=layer_head_mask,
|
| 526 |
+
position_embeddings=position_embeddings,
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
sequence_output = self.norm(hidden_states)
|
| 530 |
+
pooled_output = sequence_output[:, 0, :]
|
| 531 |
+
|
| 532 |
+
return BaseModelOutputWithPooling(
|
| 533 |
+
last_hidden_state=sequence_output,
|
| 534 |
+
pooler_output=pooled_output,
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
__all__ = ["DINOv3ViTModel", "DINOv3ViTPreTrainedModel"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dinov3_vit/modular_dinov3_vit.py
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 Meta AI and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch DINOv3 model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from typing import Callable, Optional
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
import torch.utils.checkpoint
|
| 23 |
+
from torch import nn
|
| 24 |
+
|
| 25 |
+
from transformers.models.arcee.modeling_arcee import ArceeMLP
|
| 26 |
+
from transformers.models.dinov2.modeling_dinov2 import (
|
| 27 |
+
Dinov2DropPath,
|
| 28 |
+
Dinov2LayerScale,
|
| 29 |
+
Dinov2PreTrainedModel,
|
| 30 |
+
eager_attention_forward,
|
| 31 |
+
)
|
| 32 |
+
from transformers.models.llama.modeling_llama import LlamaMLP
|
| 33 |
+
from transformers.models.pixtral.modeling_pixtral import PixtralAttention, rotate_half
|
| 34 |
+
|
| 35 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 36 |
+
from ...modeling_outputs import BaseModelOutputWithPooling
|
| 37 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
|
| 38 |
+
from ...processing_utils import Unpack
|
| 39 |
+
from ...pytorch_utils import compile_compatible_method_lru_cache
|
| 40 |
+
from ...utils import TransformersKwargs, auto_docstring, logging
|
| 41 |
+
from ...utils.generic import check_model_inputs
|
| 42 |
+
from .configuration_dinov3_vit import DINOv3ViTConfig
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
logger = logging.get_logger(__name__)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class DINOv3ViTEmbeddings(nn.Module):
|
| 49 |
+
"""
|
| 50 |
+
Construct the CLS token, mask token, position and patch embeddings.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 54 |
+
super().__init__()
|
| 55 |
+
self.config = config
|
| 56 |
+
self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
| 57 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 58 |
+
self.register_tokens = nn.Parameter(torch.empty(1, config.num_register_tokens, config.hidden_size))
|
| 59 |
+
self.patch_embeddings = nn.Conv2d(
|
| 60 |
+
config.num_channels, config.hidden_size, kernel_size=config.patch_size, stride=config.patch_size
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
def forward(self, pixel_values: torch.Tensor, bool_masked_pos: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 64 |
+
batch_size = pixel_values.shape[0]
|
| 65 |
+
target_dtype = self.patch_embeddings.weight.dtype
|
| 66 |
+
|
| 67 |
+
# (batch_size, num_channels, height, width) -> (batch_size, num_patches, hidden_size)
|
| 68 |
+
patch_embeddings = self.patch_embeddings(pixel_values.to(dtype=target_dtype))
|
| 69 |
+
patch_embeddings = patch_embeddings.flatten(2).transpose(1, 2)
|
| 70 |
+
|
| 71 |
+
if bool_masked_pos is not None:
|
| 72 |
+
mask_token = self.mask_token.to(patch_embeddings.dtype)
|
| 73 |
+
patch_embeddings = torch.where(bool_masked_pos.unsqueeze(-1), mask_token, patch_embeddings)
|
| 74 |
+
|
| 75 |
+
# Add CLS and register tokens
|
| 76 |
+
cls_token = self.cls_token.expand(batch_size, -1, -1)
|
| 77 |
+
register_tokens = self.register_tokens.expand(batch_size, -1, -1)
|
| 78 |
+
embeddings = torch.cat([cls_token, register_tokens, patch_embeddings], dim=1)
|
| 79 |
+
|
| 80 |
+
return embeddings
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@compile_compatible_method_lru_cache(maxsize=32)
|
| 84 |
+
def get_patches_center_coordinates(
|
| 85 |
+
num_patches_h: int, num_patches_w: int, dtype: torch.dtype, device: torch.device
|
| 86 |
+
) -> torch.Tensor:
|
| 87 |
+
"""
|
| 88 |
+
Computes the 2D coordinates of the centers of image patches, normalized to the range [-1, +1].
|
| 89 |
+
The center of each patch is exactly halfway between its top-left and bottom-right corners.
|
| 90 |
+
|
| 91 |
+
Args:
|
| 92 |
+
num_patches_h (int): Number of patches along the vertical (height) axis.
|
| 93 |
+
num_patches_w (int): Number of patches along the horizontal (width) axis.
|
| 94 |
+
dtype (torch.dtype): The desired data type of the returned tensor.
|
| 95 |
+
|
| 96 |
+
Returns:
|
| 97 |
+
torch.Tensor: A tensor of shape (height * width, 2), where each row contains the (y, x)
|
| 98 |
+
coordinates of a patch center, normalized to [-1, +1].
|
| 99 |
+
"""
|
| 100 |
+
coords_h = torch.arange(0.5, num_patches_h, dtype=dtype, device=device)
|
| 101 |
+
coords_w = torch.arange(0.5, num_patches_w, dtype=dtype, device=device)
|
| 102 |
+
coords_h = coords_h / num_patches_h
|
| 103 |
+
coords_w = coords_w / num_patches_w
|
| 104 |
+
# (height, width, 2) -> (height * width, 2)
|
| 105 |
+
coords = torch.stack(torch.meshgrid(coords_h, coords_w, indexing="ij"), dim=-1)
|
| 106 |
+
coords = coords.flatten(0, 1)
|
| 107 |
+
# Shift range [0, 1] to [-1, +1]
|
| 108 |
+
coords = 2.0 * coords - 1.0
|
| 109 |
+
return coords
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def augment_patches_center_coordinates(
|
| 113 |
+
coords: torch.Tensor,
|
| 114 |
+
shift: Optional[float] = None,
|
| 115 |
+
jitter: Optional[float] = None,
|
| 116 |
+
rescale: Optional[float] = None,
|
| 117 |
+
) -> torch.Tensor:
|
| 118 |
+
# Shift coords by adding a uniform value in [-shift, shift]
|
| 119 |
+
if shift is not None:
|
| 120 |
+
shift_hw = torch.empty((1, 2), device=coords.device, dtype=coords.dtype)
|
| 121 |
+
shift_hw = shift_hw.uniform_(-shift, shift)
|
| 122 |
+
coords = coords + shift_hw
|
| 123 |
+
|
| 124 |
+
# Jitter coords by multiplying the range [-1, 1] by a log-uniform value in [1/jitter, jitter]
|
| 125 |
+
if jitter is not None:
|
| 126 |
+
jitter_range = np.log(jitter)
|
| 127 |
+
jitter_hw = torch.empty((1, 2), device=coords.device, dtype=coords.dtype)
|
| 128 |
+
jitter_hw = jitter_hw.uniform_(-jitter_range, jitter_range).exp()
|
| 129 |
+
coords = coords * jitter_hw
|
| 130 |
+
|
| 131 |
+
# Rescale coords by multiplying the range [-1, 1] by a log-uniform value in [1/rescale, rescale]
|
| 132 |
+
if rescale is not None:
|
| 133 |
+
rescale_range = np.log(rescale)
|
| 134 |
+
rescale_hw = torch.empty(1, device=coords.device, dtype=coords.dtype)
|
| 135 |
+
rescale_hw = rescale_hw.uniform_(-rescale_range, rescale_range).exp()
|
| 136 |
+
coords = coords * rescale_hw
|
| 137 |
+
|
| 138 |
+
return coords
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class DINOv3ViTRopePositionEmbedding(nn.Module):
|
| 142 |
+
inv_freq: torch.Tensor
|
| 143 |
+
|
| 144 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 145 |
+
super().__init__()
|
| 146 |
+
|
| 147 |
+
self.config = config
|
| 148 |
+
self.base = config.rope_theta
|
| 149 |
+
self.head_dim = config.hidden_size // config.num_attention_heads
|
| 150 |
+
self.num_patches_h = config.image_size // config.patch_size
|
| 151 |
+
self.num_patches_w = config.image_size // config.patch_size
|
| 152 |
+
|
| 153 |
+
inv_freq = 1 / self.base ** torch.arange(0, 1, 4 / self.head_dim, dtype=torch.float32) # (head_dim / 4,)
|
| 154 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 155 |
+
|
| 156 |
+
def forward(self, pixel_values: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 157 |
+
_, _, height, width = pixel_values.shape
|
| 158 |
+
num_patches_h = height // self.config.patch_size
|
| 159 |
+
num_patches_w = width // self.config.patch_size
|
| 160 |
+
|
| 161 |
+
device = pixel_values.device
|
| 162 |
+
device_type = device.type if isinstance(device.type, str) and device.type != "mps" else "cpu"
|
| 163 |
+
|
| 164 |
+
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
| 165 |
+
# Although we could precompute static patch_coords from image_size and patch_size in the config,
|
| 166 |
+
# the model was trained with random_scale, so it can process images of varying sizes.
|
| 167 |
+
# Therefore, it's better to compute patch_coords dynamically (with lru_cache).
|
| 168 |
+
patch_coords = get_patches_center_coordinates(
|
| 169 |
+
num_patches_h, num_patches_w, dtype=torch.float32, device=device
|
| 170 |
+
)
|
| 171 |
+
if self.training:
|
| 172 |
+
patch_coords = augment_patches_center_coordinates(
|
| 173 |
+
patch_coords,
|
| 174 |
+
shift=self.config.pos_embed_shift,
|
| 175 |
+
jitter=self.config.pos_embed_jitter,
|
| 176 |
+
rescale=self.config.pos_embed_rescale,
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# (height * width, 2, head_dim / 4) -> (height * width, head_dim / 2) -> (height * width, head_dim)
|
| 180 |
+
angles = 2 * math.pi * patch_coords[:, :, None] * self.inv_freq[None, None, :]
|
| 181 |
+
angles = angles.flatten(1, 2)
|
| 182 |
+
angles = angles.tile(2)
|
| 183 |
+
|
| 184 |
+
cos = torch.cos(angles)
|
| 185 |
+
sin = torch.sin(angles)
|
| 186 |
+
|
| 187 |
+
dtype = pixel_values.dtype
|
| 188 |
+
return cos.to(dtype=dtype), sin.to(dtype=dtype)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def apply_rotary_pos_emb(
|
| 192 |
+
q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, **kwargs
|
| 193 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 194 |
+
"""Applies Rotary Position Embedding to the query and key tensors, but only to the patch tokens,
|
| 195 |
+
ignoring the prefix tokens (cls token and register tokens).
|
| 196 |
+
|
| 197 |
+
Args:
|
| 198 |
+
q (`torch.Tensor`): The query tensor.
|
| 199 |
+
k (`torch.Tensor`): The key tensor.
|
| 200 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 201 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 202 |
+
|
| 203 |
+
Returns:
|
| 204 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 205 |
+
"""
|
| 206 |
+
|
| 207 |
+
num_tokens = q.shape[-2]
|
| 208 |
+
num_patches = sin.shape[-2]
|
| 209 |
+
num_prefix_tokens = num_tokens - num_patches # cls token + register tokens
|
| 210 |
+
|
| 211 |
+
q_prefix_tokens, q_patches = q.split((num_prefix_tokens, num_patches), dim=-2)
|
| 212 |
+
k_prefix_tokens, k_patches = k.split((num_prefix_tokens, num_patches), dim=-2)
|
| 213 |
+
|
| 214 |
+
# apply rope only to patch tokens
|
| 215 |
+
q_patches = (q_patches * cos) + (rotate_half(q_patches) * sin)
|
| 216 |
+
k_patches = (k_patches * cos) + (rotate_half(k_patches) * sin)
|
| 217 |
+
|
| 218 |
+
q = torch.cat((q_prefix_tokens, q_patches), dim=-2)
|
| 219 |
+
k = torch.cat((k_prefix_tokens, k_patches), dim=-2)
|
| 220 |
+
|
| 221 |
+
return q, k
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
class DINOv3ViTAttention(PixtralAttention):
|
| 225 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 226 |
+
super().__init__(config)
|
| 227 |
+
|
| 228 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.query_bias)
|
| 229 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.key_bias)
|
| 230 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.value_bias)
|
| 231 |
+
self.o_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.proj_bias)
|
| 232 |
+
|
| 233 |
+
def forward(
|
| 234 |
+
self,
|
| 235 |
+
hidden_states: torch.Tensor,
|
| 236 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 237 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
| 238 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 239 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 240 |
+
"""Input shape: Batch x Time x Channel"""
|
| 241 |
+
|
| 242 |
+
batch_size, patches, _ = hidden_states.size()
|
| 243 |
+
|
| 244 |
+
query_states = self.q_proj(hidden_states)
|
| 245 |
+
key_states = self.k_proj(hidden_states)
|
| 246 |
+
value_states = self.v_proj(hidden_states)
|
| 247 |
+
|
| 248 |
+
query_states = query_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
|
| 249 |
+
key_states = key_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
|
| 250 |
+
value_states = value_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
|
| 251 |
+
|
| 252 |
+
cos, sin = position_embeddings
|
| 253 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 254 |
+
|
| 255 |
+
attention_interface: Callable = eager_attention_forward
|
| 256 |
+
if self.config._attn_implementation != "eager":
|
| 257 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 258 |
+
|
| 259 |
+
attn_output, attn_weights = attention_interface(
|
| 260 |
+
self,
|
| 261 |
+
query_states,
|
| 262 |
+
key_states,
|
| 263 |
+
value_states,
|
| 264 |
+
attention_mask,
|
| 265 |
+
dropout=0.0 if not self.training else self.dropout,
|
| 266 |
+
scaling=self.scaling,
|
| 267 |
+
**kwargs,
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
attn_output = attn_output.reshape(batch_size, patches, -1).contiguous()
|
| 271 |
+
attn_output = self.o_proj(attn_output)
|
| 272 |
+
|
| 273 |
+
return attn_output, attn_weights
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class DINOv3ViTLayerScale(Dinov2LayerScale):
|
| 277 |
+
pass
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
class DINOv3ViTDropPath(Dinov2DropPath):
|
| 281 |
+
pass
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
class DINOv3ViTMLP(ArceeMLP):
|
| 285 |
+
pass
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class DINOv3ViTGatedMLP(LlamaMLP):
|
| 289 |
+
pass
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
class DINOv3ViTLayer(GradientCheckpointingLayer):
|
| 293 |
+
"""This corresponds to the Block class in the original implementation."""
|
| 294 |
+
|
| 295 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 296 |
+
super().__init__()
|
| 297 |
+
|
| 298 |
+
self.norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 299 |
+
self.attention = DINOv3ViTAttention(config)
|
| 300 |
+
self.layer_scale1 = DINOv3ViTLayerScale(config)
|
| 301 |
+
self.drop_path = DINOv3ViTDropPath(config.drop_path_rate) if config.drop_path_rate > 0.0 else nn.Identity()
|
| 302 |
+
|
| 303 |
+
self.norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 304 |
+
|
| 305 |
+
if config.use_gated_mlp:
|
| 306 |
+
self.mlp = DINOv3ViTGatedMLP(config)
|
| 307 |
+
else:
|
| 308 |
+
self.mlp = DINOv3ViTMLP(config)
|
| 309 |
+
self.layer_scale2 = DINOv3ViTLayerScale(config)
|
| 310 |
+
|
| 311 |
+
def forward(
|
| 312 |
+
self,
|
| 313 |
+
hidden_states: torch.Tensor,
|
| 314 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 315 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
| 316 |
+
) -> torch.Tensor:
|
| 317 |
+
# Attention with residual connection
|
| 318 |
+
residual = hidden_states
|
| 319 |
+
hidden_states = self.norm1(hidden_states)
|
| 320 |
+
hidden_states, _ = self.attention(
|
| 321 |
+
hidden_states,
|
| 322 |
+
attention_mask=attention_mask,
|
| 323 |
+
position_embeddings=position_embeddings,
|
| 324 |
+
)
|
| 325 |
+
hidden_states = self.layer_scale1(hidden_states)
|
| 326 |
+
hidden_states = self.drop_path(hidden_states) + residual
|
| 327 |
+
|
| 328 |
+
# MLP with residual connection
|
| 329 |
+
residual = hidden_states
|
| 330 |
+
hidden_states = self.norm2(hidden_states)
|
| 331 |
+
hidden_states = self.mlp(hidden_states)
|
| 332 |
+
hidden_states = self.layer_scale2(hidden_states)
|
| 333 |
+
hidden_states = self.drop_path(hidden_states) + residual
|
| 334 |
+
|
| 335 |
+
return hidden_states
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
@auto_docstring
|
| 339 |
+
class DINOv3ViTPreTrainedModel(Dinov2PreTrainedModel):
|
| 340 |
+
_can_record_outputs = {
|
| 341 |
+
"hidden_states": DINOv3ViTLayer,
|
| 342 |
+
"attentions": DINOv3ViTAttention,
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
def _init_weights(self, module):
|
| 346 |
+
"""Initialize the weights"""
|
| 347 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 348 |
+
# Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
|
| 349 |
+
# `trunc_normal_cpu` not implemented in `half` issues
|
| 350 |
+
module.weight.data = nn.init.trunc_normal_(
|
| 351 |
+
module.weight.data.to(torch.float32),
|
| 352 |
+
mean=0.0,
|
| 353 |
+
std=self.config.initializer_range,
|
| 354 |
+
).to(module.weight.dtype)
|
| 355 |
+
if module.bias is not None:
|
| 356 |
+
module.bias.data.zero_()
|
| 357 |
+
elif isinstance(module, nn.LayerNorm):
|
| 358 |
+
module.bias.data.zero_()
|
| 359 |
+
module.weight.data.fill_(1.0)
|
| 360 |
+
elif isinstance(module, DINOv3ViTEmbeddings):
|
| 361 |
+
module.cls_token.data = nn.init.trunc_normal_(
|
| 362 |
+
module.cls_token.data.to(torch.float32),
|
| 363 |
+
mean=0.0,
|
| 364 |
+
std=self.config.initializer_range,
|
| 365 |
+
).to(module.cls_token.dtype)
|
| 366 |
+
if module.config.num_register_tokens > 0:
|
| 367 |
+
module.register_tokens.data = nn.init.trunc_normal_(
|
| 368 |
+
module.register_tokens.data.to(torch.float32),
|
| 369 |
+
mean=0.0,
|
| 370 |
+
std=self.config.initializer_range,
|
| 371 |
+
).to(module.register_tokens.dtype)
|
| 372 |
+
module.mask_token.data.zero_()
|
| 373 |
+
elif isinstance(module, DINOv3ViTLayerScale):
|
| 374 |
+
module.lambda1.data.fill_(self.config.layerscale_value)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
@auto_docstring
|
| 378 |
+
class DINOv3ViTModel(DINOv3ViTPreTrainedModel):
|
| 379 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 380 |
+
super().__init__(config)
|
| 381 |
+
self.config = config
|
| 382 |
+
self.embeddings = DINOv3ViTEmbeddings(config)
|
| 383 |
+
self.rope_embeddings = DINOv3ViTRopePositionEmbedding(config)
|
| 384 |
+
self.layer = nn.ModuleList([DINOv3ViTLayer(config) for _ in range(config.num_hidden_layers)])
|
| 385 |
+
self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 386 |
+
self.gradient_checkpointing = False
|
| 387 |
+
# Initialize weights and apply final processing
|
| 388 |
+
self.post_init()
|
| 389 |
+
|
| 390 |
+
def get_input_embeddings(self):
|
| 391 |
+
return self.embeddings.patch_embeddings
|
| 392 |
+
|
| 393 |
+
@check_model_inputs
|
| 394 |
+
@auto_docstring
|
| 395 |
+
def forward(
|
| 396 |
+
self,
|
| 397 |
+
pixel_values: torch.Tensor,
|
| 398 |
+
bool_masked_pos: Optional[torch.Tensor] = None,
|
| 399 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 400 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 401 |
+
) -> BaseModelOutputWithPooling:
|
| 402 |
+
r"""
|
| 403 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
|
| 404 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0). Only relevant for
|
| 405 |
+
pre-training.
|
| 406 |
+
"""
|
| 407 |
+
|
| 408 |
+
pixel_values = pixel_values.to(self.embeddings.patch_embeddings.weight.dtype)
|
| 409 |
+
hidden_states = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
|
| 410 |
+
position_embeddings = self.rope_embeddings(pixel_values)
|
| 411 |
+
|
| 412 |
+
for i, layer_module in enumerate(self.layer):
|
| 413 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 414 |
+
hidden_states = layer_module(
|
| 415 |
+
hidden_states,
|
| 416 |
+
attention_mask=layer_head_mask,
|
| 417 |
+
position_embeddings=position_embeddings,
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
sequence_output = self.norm(hidden_states)
|
| 421 |
+
pooled_output = sequence_output[:, 0, :]
|
| 422 |
+
|
| 423 |
+
return BaseModelOutputWithPooling(
|
| 424 |
+
last_hidden_state=sequence_output,
|
| 425 |
+
pooler_output=pooled_output,
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
__all__ = ["DINOv3ViTModel", "DINOv3ViTPreTrainedModel"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/distilbert/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_distilbert import *
|
| 22 |
+
from .modeling_distilbert import *
|
| 23 |
+
from .modeling_flax_distilbert import *
|
| 24 |
+
from .modeling_tf_distilbert import *
|
| 25 |
+
from .tokenization_distilbert import *
|
| 26 |
+
from .tokenization_distilbert_fast import *
|
| 27 |
+
else:
|
| 28 |
+
import sys
|
| 29 |
+
|
| 30 |
+
_file = globals()["__file__"]
|
| 31 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/distilbert/configuration_distilbert.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""DistilBERT model configuration"""
|
| 16 |
+
|
| 17 |
+
from collections import OrderedDict
|
| 18 |
+
from collections.abc import Mapping
|
| 19 |
+
|
| 20 |
+
from ...configuration_utils import PretrainedConfig
|
| 21 |
+
from ...onnx import OnnxConfig
|
| 22 |
+
from ...utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class DistilBertConfig(PretrainedConfig):
|
| 29 |
+
r"""
|
| 30 |
+
This is the configuration class to store the configuration of a [`DistilBertModel`] or a [`TFDistilBertModel`]. It
|
| 31 |
+
is used to instantiate a DistilBERT model according to the specified arguments, defining the model architecture.
|
| 32 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the DistilBERT
|
| 33 |
+
[distilbert-base-uncased](https://huggingface.co/distilbert-base-uncased) architecture.
|
| 34 |
+
|
| 35 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 36 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
| 40 |
+
Vocabulary size of the DistilBERT model. Defines the number of different tokens that can be represented by
|
| 41 |
+
the `inputs_ids` passed when calling [`DistilBertModel`] or [`TFDistilBertModel`].
|
| 42 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 43 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 44 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 45 |
+
sinusoidal_pos_embds (`boolean`, *optional*, defaults to `False`):
|
| 46 |
+
Whether to use sinusoidal positional embeddings.
|
| 47 |
+
n_layers (`int`, *optional*, defaults to 6):
|
| 48 |
+
Number of hidden layers in the Transformer encoder.
|
| 49 |
+
n_heads (`int`, *optional*, defaults to 12):
|
| 50 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 51 |
+
dim (`int`, *optional*, defaults to 768):
|
| 52 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 53 |
+
hidden_dim (`int`, *optional*, defaults to 3072):
|
| 54 |
+
The size of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 55 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 56 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 57 |
+
attention_dropout (`float`, *optional*, defaults to 0.1):
|
| 58 |
+
The dropout ratio for the attention probabilities.
|
| 59 |
+
activation (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
| 60 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 61 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 62 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 63 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 64 |
+
qa_dropout (`float`, *optional*, defaults to 0.1):
|
| 65 |
+
The dropout probabilities used in the question answering model [`DistilBertForQuestionAnswering`].
|
| 66 |
+
seq_classif_dropout (`float`, *optional*, defaults to 0.2):
|
| 67 |
+
The dropout probabilities used in the sequence classification and the multiple choice model
|
| 68 |
+
[`DistilBertForSequenceClassification`].
|
| 69 |
+
|
| 70 |
+
Examples:
|
| 71 |
+
|
| 72 |
+
```python
|
| 73 |
+
>>> from transformers import DistilBertConfig, DistilBertModel
|
| 74 |
+
|
| 75 |
+
>>> # Initializing a DistilBERT configuration
|
| 76 |
+
>>> configuration = DistilBertConfig()
|
| 77 |
+
|
| 78 |
+
>>> # Initializing a model (with random weights) from the configuration
|
| 79 |
+
>>> model = DistilBertModel(configuration)
|
| 80 |
+
|
| 81 |
+
>>> # Accessing the model configuration
|
| 82 |
+
>>> configuration = model.config
|
| 83 |
+
```"""
|
| 84 |
+
|
| 85 |
+
model_type = "distilbert"
|
| 86 |
+
attribute_map = {
|
| 87 |
+
"hidden_size": "dim",
|
| 88 |
+
"num_attention_heads": "n_heads",
|
| 89 |
+
"num_hidden_layers": "n_layers",
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
def __init__(
|
| 93 |
+
self,
|
| 94 |
+
vocab_size=30522,
|
| 95 |
+
max_position_embeddings=512,
|
| 96 |
+
sinusoidal_pos_embds=False,
|
| 97 |
+
n_layers=6,
|
| 98 |
+
n_heads=12,
|
| 99 |
+
dim=768,
|
| 100 |
+
hidden_dim=4 * 768,
|
| 101 |
+
dropout=0.1,
|
| 102 |
+
attention_dropout=0.1,
|
| 103 |
+
activation="gelu",
|
| 104 |
+
initializer_range=0.02,
|
| 105 |
+
qa_dropout=0.1,
|
| 106 |
+
seq_classif_dropout=0.2,
|
| 107 |
+
pad_token_id=0,
|
| 108 |
+
**kwargs,
|
| 109 |
+
):
|
| 110 |
+
self.vocab_size = vocab_size
|
| 111 |
+
self.max_position_embeddings = max_position_embeddings
|
| 112 |
+
self.sinusoidal_pos_embds = sinusoidal_pos_embds
|
| 113 |
+
self.n_layers = n_layers
|
| 114 |
+
self.n_heads = n_heads
|
| 115 |
+
self.dim = dim
|
| 116 |
+
self.hidden_dim = hidden_dim
|
| 117 |
+
self.dropout = dropout
|
| 118 |
+
self.attention_dropout = attention_dropout
|
| 119 |
+
self.activation = activation
|
| 120 |
+
self.initializer_range = initializer_range
|
| 121 |
+
self.qa_dropout = qa_dropout
|
| 122 |
+
self.seq_classif_dropout = seq_classif_dropout
|
| 123 |
+
super().__init__(**kwargs, pad_token_id=pad_token_id)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class DistilBertOnnxConfig(OnnxConfig):
|
| 127 |
+
@property
|
| 128 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 129 |
+
if self.task == "multiple-choice":
|
| 130 |
+
dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
|
| 131 |
+
else:
|
| 132 |
+
dynamic_axis = {0: "batch", 1: "sequence"}
|
| 133 |
+
return OrderedDict(
|
| 134 |
+
[
|
| 135 |
+
("input_ids", dynamic_axis),
|
| 136 |
+
("attention_mask", dynamic_axis),
|
| 137 |
+
]
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
__all__ = ["DistilBertConfig", "DistilBertOnnxConfig"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transform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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
"""
|
| 17 |
+
PyTorch DistilBERT model adapted in part from Facebook, Inc XLM model (https://github.com/facebookresearch/XLM) and in
|
| 18 |
+
part from HuggingFace PyTorch version of Google AI Bert model (https://github.com/google-research/bert)
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import math
|
| 22 |
+
from typing import Optional, Union
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import torch
|
| 26 |
+
from torch import nn
|
| 27 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 28 |
+
|
| 29 |
+
from ...activations import get_activation
|
| 30 |
+
from ...configuration_utils import PretrainedConfig
|
| 31 |
+
from ...integrations.deepspeed import is_deepspeed_zero3_enabled
|
| 32 |
+
from ...modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa
|
| 33 |
+
from ...modeling_flash_attention_utils import flash_attn_supports_top_left_mask, is_flash_attn_available
|
| 34 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 35 |
+
from ...modeling_outputs import (
|
| 36 |
+
BaseModelOutput,
|
| 37 |
+
MaskedLMOutput,
|
| 38 |
+
MultipleChoiceModelOutput,
|
| 39 |
+
QuestionAnsweringModelOutput,
|
| 40 |
+
SequenceClassifierOutput,
|
| 41 |
+
TokenClassifierOutput,
|
| 42 |
+
)
|
| 43 |
+
from ...modeling_utils import PreTrainedModel
|
| 44 |
+
from ...pytorch_utils import (
|
| 45 |
+
apply_chunking_to_forward,
|
| 46 |
+
find_pruneable_heads_and_indices,
|
| 47 |
+
is_torch_greater_or_equal_than_2_2,
|
| 48 |
+
prune_linear_layer,
|
| 49 |
+
)
|
| 50 |
+
from ...utils import (
|
| 51 |
+
auto_docstring,
|
| 52 |
+
logging,
|
| 53 |
+
)
|
| 54 |
+
from .configuration_distilbert import DistilBertConfig
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
if is_flash_attn_available():
|
| 58 |
+
from ...modeling_flash_attention_utils import _flash_attention_forward
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
logger = logging.get_logger(__name__)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# UTILS AND BUILDING BLOCKS OF THE ARCHITECTURE #
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def create_sinusoidal_embeddings(n_pos: int, dim: int, out: torch.Tensor):
|
| 68 |
+
if is_deepspeed_zero3_enabled():
|
| 69 |
+
import deepspeed
|
| 70 |
+
|
| 71 |
+
with deepspeed.zero.GatheredParameters(out, modifier_rank=0):
|
| 72 |
+
if torch.distributed.get_rank() == 0:
|
| 73 |
+
_create_sinusoidal_embeddings(n_pos=n_pos, dim=dim, out=out)
|
| 74 |
+
else:
|
| 75 |
+
_create_sinusoidal_embeddings(n_pos=n_pos, dim=dim, out=out)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _create_sinusoidal_embeddings(n_pos: int, dim: int, out: torch.Tensor):
|
| 79 |
+
position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)])
|
| 80 |
+
out.requires_grad = False
|
| 81 |
+
out[:, 0::2] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
|
| 82 |
+
out[:, 1::2] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
|
| 83 |
+
out.detach_()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class Embeddings(nn.Module):
|
| 87 |
+
def __init__(self, config: PretrainedConfig):
|
| 88 |
+
super().__init__()
|
| 89 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.dim, padding_idx=config.pad_token_id)
|
| 90 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.dim)
|
| 91 |
+
|
| 92 |
+
self.LayerNorm = nn.LayerNorm(config.dim, eps=1e-12)
|
| 93 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 94 |
+
self.register_buffer(
|
| 95 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
def forward(self, input_ids: torch.Tensor, input_embeds: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 99 |
+
"""
|
| 100 |
+
Parameters:
|
| 101 |
+
input_ids (torch.Tensor):
|
| 102 |
+
torch.tensor(bs, max_seq_length) The token ids to embed.
|
| 103 |
+
input_embeds (*optional*, torch.Tensor):
|
| 104 |
+
The pre-computed word embeddings. Can only be passed if the input ids are `None`.
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
Returns: torch.tensor(bs, max_seq_length, dim) The embedded tokens (plus position embeddings, no token_type
|
| 108 |
+
embeddings)
|
| 109 |
+
"""
|
| 110 |
+
if input_ids is not None:
|
| 111 |
+
input_embeds = self.word_embeddings(input_ids) # (bs, max_seq_length, dim)
|
| 112 |
+
|
| 113 |
+
seq_length = input_embeds.size(1)
|
| 114 |
+
|
| 115 |
+
# Setting the position-ids to the registered buffer in constructor, it helps
|
| 116 |
+
# when tracing the model without passing position-ids, solves
|
| 117 |
+
# issues similar to issue #5664
|
| 118 |
+
if hasattr(self, "position_ids"):
|
| 119 |
+
position_ids = self.position_ids[:, :seq_length]
|
| 120 |
+
else:
|
| 121 |
+
position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device) # (max_seq_length)
|
| 122 |
+
position_ids = position_ids.unsqueeze(0).expand_as(input_ids) # (bs, max_seq_length)
|
| 123 |
+
|
| 124 |
+
position_embeddings = self.position_embeddings(position_ids) # (bs, max_seq_length, dim)
|
| 125 |
+
|
| 126 |
+
embeddings = input_embeds + position_embeddings # (bs, max_seq_length, dim)
|
| 127 |
+
embeddings = self.LayerNorm(embeddings) # (bs, max_seq_length, dim)
|
| 128 |
+
embeddings = self.dropout(embeddings) # (bs, max_seq_length, dim)
|
| 129 |
+
return embeddings
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class MultiHeadSelfAttention(nn.Module):
|
| 133 |
+
def __init__(self, config: PretrainedConfig):
|
| 134 |
+
super().__init__()
|
| 135 |
+
self.config = config
|
| 136 |
+
|
| 137 |
+
self.n_heads = config.n_heads
|
| 138 |
+
self.dim = config.dim
|
| 139 |
+
self.dropout = nn.Dropout(p=config.attention_dropout)
|
| 140 |
+
self.is_causal = False
|
| 141 |
+
|
| 142 |
+
# Have an even number of multi heads that divide the dimensions
|
| 143 |
+
if self.dim % self.n_heads != 0:
|
| 144 |
+
# Raise value errors for even multi-head attention nodes
|
| 145 |
+
raise ValueError(f"self.n_heads: {self.n_heads} must divide self.dim: {self.dim} evenly")
|
| 146 |
+
|
| 147 |
+
self.q_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
|
| 148 |
+
self.k_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
|
| 149 |
+
self.v_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
|
| 150 |
+
self.out_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
|
| 151 |
+
|
| 152 |
+
self.pruned_heads: set[int] = set()
|
| 153 |
+
self.attention_head_size = self.dim // self.n_heads
|
| 154 |
+
|
| 155 |
+
def prune_heads(self, heads: list[int]):
|
| 156 |
+
if len(heads) == 0:
|
| 157 |
+
return
|
| 158 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 159 |
+
heads, self.n_heads, self.attention_head_size, self.pruned_heads
|
| 160 |
+
)
|
| 161 |
+
# Prune linear layers
|
| 162 |
+
self.q_lin = prune_linear_layer(self.q_lin, index)
|
| 163 |
+
self.k_lin = prune_linear_layer(self.k_lin, index)
|
| 164 |
+
self.v_lin = prune_linear_layer(self.v_lin, index)
|
| 165 |
+
self.out_lin = prune_linear_layer(self.out_lin, index, dim=1)
|
| 166 |
+
# Update hyper params
|
| 167 |
+
self.n_heads = self.n_heads - len(heads)
|
| 168 |
+
self.dim = self.attention_head_size * self.n_heads
|
| 169 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 170 |
+
|
| 171 |
+
def forward(
|
| 172 |
+
self,
|
| 173 |
+
query: torch.Tensor,
|
| 174 |
+
key: torch.Tensor,
|
| 175 |
+
value: torch.Tensor,
|
| 176 |
+
mask: torch.Tensor,
|
| 177 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 178 |
+
output_attentions: bool = False,
|
| 179 |
+
) -> tuple[torch.Tensor, ...]:
|
| 180 |
+
"""
|
| 181 |
+
Parameters:
|
| 182 |
+
query: torch.tensor(bs, seq_length, dim)
|
| 183 |
+
key: torch.tensor(bs, seq_length, dim)
|
| 184 |
+
value: torch.tensor(bs, seq_length, dim)
|
| 185 |
+
mask: torch.tensor(bs, seq_length)
|
| 186 |
+
|
| 187 |
+
Returns:
|
| 188 |
+
weights: torch.tensor(bs, n_heads, seq_length, seq_length) Attention weights context: torch.tensor(bs,
|
| 189 |
+
seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
|
| 190 |
+
"""
|
| 191 |
+
bs, q_length, dim = query.size()
|
| 192 |
+
k_length = key.size(1)
|
| 193 |
+
# assert dim == self.dim, f'Dimensions do not match: {dim} input vs {self.dim} configured'
|
| 194 |
+
# assert key.size() == value.size()
|
| 195 |
+
|
| 196 |
+
dim_per_head = self.dim // self.n_heads
|
| 197 |
+
|
| 198 |
+
mask_reshp = (bs, 1, 1, k_length)
|
| 199 |
+
|
| 200 |
+
def shape(x: torch.Tensor) -> torch.Tensor:
|
| 201 |
+
"""separate heads"""
|
| 202 |
+
return x.view(bs, -1, self.n_heads, dim_per_head).transpose(1, 2)
|
| 203 |
+
|
| 204 |
+
def unshape(x: torch.Tensor) -> torch.Tensor:
|
| 205 |
+
"""group heads"""
|
| 206 |
+
return x.transpose(1, 2).contiguous().view(bs, -1, self.n_heads * dim_per_head)
|
| 207 |
+
|
| 208 |
+
q = shape(self.q_lin(query)) # (bs, n_heads, q_length, dim_per_head)
|
| 209 |
+
k = shape(self.k_lin(key)) # (bs, n_heads, k_length, dim_per_head)
|
| 210 |
+
v = shape(self.v_lin(value)) # (bs, n_heads, k_length, dim_per_head)
|
| 211 |
+
|
| 212 |
+
q = q / math.sqrt(dim_per_head) # (bs, n_heads, q_length, dim_per_head)
|
| 213 |
+
scores = torch.matmul(q, k.transpose(2, 3)) # (bs, n_heads, q_length, k_length)
|
| 214 |
+
mask = (mask == 0).view(mask_reshp).expand_as(scores) # (bs, n_heads, q_length, k_length)
|
| 215 |
+
scores = scores.masked_fill(
|
| 216 |
+
mask, torch.tensor(torch.finfo(scores.dtype).min)
|
| 217 |
+
) # (bs, n_heads, q_length, k_length)
|
| 218 |
+
|
| 219 |
+
weights = nn.functional.softmax(scores, dim=-1) # (bs, n_heads, q_length, k_length)
|
| 220 |
+
weights = self.dropout(weights) # (bs, n_heads, q_length, k_length)
|
| 221 |
+
|
| 222 |
+
# Mask heads if we want to
|
| 223 |
+
if head_mask is not None:
|
| 224 |
+
weights = weights * head_mask
|
| 225 |
+
|
| 226 |
+
context = torch.matmul(weights, v) # (bs, n_heads, q_length, dim_per_head)
|
| 227 |
+
context = unshape(context) # (bs, q_length, dim)
|
| 228 |
+
context = self.out_lin(context) # (bs, q_length, dim)
|
| 229 |
+
|
| 230 |
+
if output_attentions:
|
| 231 |
+
return (context, weights)
|
| 232 |
+
else:
|
| 233 |
+
return (context,)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
class DistilBertFlashAttention2(MultiHeadSelfAttention):
|
| 237 |
+
"""
|
| 238 |
+
DistilBert flash attention module. This module inherits from `MultiHeadSelfAttention` as the weights of the module
|
| 239 |
+
stays untouched. The only required change would be on the forward pass where it needs to correctly call the public
|
| 240 |
+
API of flash attention and deal with padding tokens in case the input contains any of them.
|
| 241 |
+
"""
|
| 242 |
+
|
| 243 |
+
def __init__(self, *args, **kwargs):
|
| 244 |
+
super().__init__(*args, **kwargs)
|
| 245 |
+
|
| 246 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
| 247 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
| 248 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
| 249 |
+
self._flash_attn_uses_top_left_mask = flash_attn_supports_top_left_mask()
|
| 250 |
+
|
| 251 |
+
def forward(
|
| 252 |
+
self,
|
| 253 |
+
query: torch.Tensor,
|
| 254 |
+
key: torch.Tensor,
|
| 255 |
+
value: torch.Tensor,
|
| 256 |
+
mask: torch.Tensor,
|
| 257 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 258 |
+
output_attentions: bool = False,
|
| 259 |
+
) -> tuple[torch.Tensor, ...]:
|
| 260 |
+
"""
|
| 261 |
+
Parameters:
|
| 262 |
+
query: torch.tensor(bs, seq_length, dim)
|
| 263 |
+
key: torch.tensor(bs, seq_length, dim)
|
| 264 |
+
value: torch.tensor(bs, seq_length, dim)
|
| 265 |
+
mask: torch.tensor(bs, seq_length)
|
| 266 |
+
|
| 267 |
+
Returns:
|
| 268 |
+
weights: torch.tensor(bs, n_heads, seq_length, seq_length) Attention weights context: torch.tensor(bs,
|
| 269 |
+
seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
|
| 270 |
+
"""
|
| 271 |
+
batch_size, q_length, dim = query.size()
|
| 272 |
+
|
| 273 |
+
dim_per_head = self.dim // self.n_heads
|
| 274 |
+
|
| 275 |
+
def reshape(x: torch.Tensor) -> torch.Tensor:
|
| 276 |
+
"""separate heads"""
|
| 277 |
+
return x.view(batch_size, -1, self.n_heads, dim_per_head)
|
| 278 |
+
|
| 279 |
+
# Flash attention requires the input to have the shape
|
| 280 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
| 281 |
+
query_states = reshape(self.q_lin(query))
|
| 282 |
+
key_states = reshape(self.k_lin(key))
|
| 283 |
+
value_states = reshape(self.v_lin(value))
|
| 284 |
+
|
| 285 |
+
attn_dropout = self.config.attention_dropout if self.training else 0.0
|
| 286 |
+
|
| 287 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
| 288 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
| 289 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
| 290 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
| 291 |
+
# in fp32. (LlamaRMSNorm handles it correctly)
|
| 292 |
+
|
| 293 |
+
device_type = query_states.device.type if query_states.device.type != "mps" else "cpu"
|
| 294 |
+
if query_states.dtype == torch.float32:
|
| 295 |
+
if torch.is_autocast_enabled():
|
| 296 |
+
target_dtype = (
|
| 297 |
+
torch.get_autocast_dtype(device_type)
|
| 298 |
+
if hasattr(torch, "get_autocast_dtype")
|
| 299 |
+
else torch.get_autocast_gpu_dtype()
|
| 300 |
+
)
|
| 301 |
+
# Handle the case where the model is quantized
|
| 302 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
| 303 |
+
target_dtype = self.config._pre_quantization_dtype
|
| 304 |
+
else:
|
| 305 |
+
target_dtype = self.q_lin.weight.dtype
|
| 306 |
+
|
| 307 |
+
logger.warning_once(
|
| 308 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
| 309 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
| 310 |
+
f" {target_dtype}."
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
query_states = query_states.to(target_dtype)
|
| 314 |
+
key_states = key_states.to(target_dtype)
|
| 315 |
+
value_states = value_states.to(target_dtype)
|
| 316 |
+
|
| 317 |
+
attn_weights = _flash_attention_forward(
|
| 318 |
+
query_states,
|
| 319 |
+
key_states,
|
| 320 |
+
value_states,
|
| 321 |
+
mask,
|
| 322 |
+
q_length,
|
| 323 |
+
dropout=attn_dropout,
|
| 324 |
+
use_top_left_mask=self._flash_attn_uses_top_left_mask,
|
| 325 |
+
is_causal=self.is_causal,
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
attn_weights_reshaped = attn_weights.reshape(batch_size, q_length, self.n_heads * dim_per_head)
|
| 329 |
+
attn_output = self.out_lin(attn_weights_reshaped)
|
| 330 |
+
|
| 331 |
+
if output_attentions:
|
| 332 |
+
return (attn_output, attn_weights)
|
| 333 |
+
else:
|
| 334 |
+
return (attn_output,)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class DistilBertSdpaAttention(MultiHeadSelfAttention):
|
| 338 |
+
def __init__(self, config: PretrainedConfig):
|
| 339 |
+
super().__init__(config=config)
|
| 340 |
+
self.dropout_prob = config.attention_dropout
|
| 341 |
+
self.require_contiguous_qkv = not is_torch_greater_or_equal_than_2_2
|
| 342 |
+
|
| 343 |
+
def forward(
|
| 344 |
+
self,
|
| 345 |
+
query: torch.Tensor,
|
| 346 |
+
key: torch.Tensor,
|
| 347 |
+
value: torch.Tensor,
|
| 348 |
+
mask: torch.Tensor,
|
| 349 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 350 |
+
output_attentions: bool = False,
|
| 351 |
+
) -> tuple[torch.Tensor, ...]:
|
| 352 |
+
"""
|
| 353 |
+
Parameters:
|
| 354 |
+
query: torch.tensor(bs, seq_length, dim)
|
| 355 |
+
key: torch.tensor(bs, seq_length, dim)
|
| 356 |
+
value: torch.tensor(bs, seq_length, dim)
|
| 357 |
+
mask: torch.tensor(bs, seq_length)
|
| 358 |
+
|
| 359 |
+
Returns:
|
| 360 |
+
weights: torch.tensor(bs, n_heads, seq_length, seq_length) Attention weights context: torch.tensor(bs,
|
| 361 |
+
seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
|
| 362 |
+
"""
|
| 363 |
+
if output_attentions or head_mask is not None:
|
| 364 |
+
logger.warning_once(
|
| 365 |
+
"DistilBertSdpaAttention is used but `torch.nn.functional.scaled_dot_product_attention` does not support"
|
| 366 |
+
" `output_attentions=True` or `head_mask`. Falling back to the manual attention implementation, but specifying"
|
| 367 |
+
" the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be"
|
| 368 |
+
' removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 369 |
+
)
|
| 370 |
+
return super().forward(
|
| 371 |
+
query,
|
| 372 |
+
key,
|
| 373 |
+
value,
|
| 374 |
+
mask,
|
| 375 |
+
head_mask,
|
| 376 |
+
output_attentions,
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
batch_size, _, _ = query.size()
|
| 380 |
+
dim_per_head = self.dim // self.n_heads
|
| 381 |
+
|
| 382 |
+
def shape(x: torch.Tensor) -> torch.Tensor:
|
| 383 |
+
"""separate heads"""
|
| 384 |
+
return x.view(batch_size, -1, self.n_heads, dim_per_head).transpose(1, 2)
|
| 385 |
+
|
| 386 |
+
def unshape(x: torch.Tensor) -> torch.Tensor:
|
| 387 |
+
"""group heads"""
|
| 388 |
+
return x.transpose(1, 2).contiguous().view(batch_size, -1, self.n_heads * dim_per_head)
|
| 389 |
+
|
| 390 |
+
q = shape(self.q_lin(query)) # (bs, n_heads, q_length, dim_per_head)
|
| 391 |
+
k = shape(self.k_lin(key)) # (bs, n_heads, k_length, dim_per_head)
|
| 392 |
+
v = shape(self.v_lin(value)) # (bs, n_heads, k_length, dim_per_head)
|
| 393 |
+
|
| 394 |
+
# SDPA with memory-efficient backend is broken in torch==2.1.2 when using non-contiguous inputs and a custom
|
| 395 |
+
# attn_mask, so we need to call `.contiguous()` here. This was fixed in torch==2.2.0.
|
| 396 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577
|
| 397 |
+
if self.require_contiguous_qkv and q.device.type == "cuda" and mask is not None:
|
| 398 |
+
q = q.contiguous()
|
| 399 |
+
k = k.contiguous()
|
| 400 |
+
v = v.contiguous()
|
| 401 |
+
|
| 402 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
| 403 |
+
q,
|
| 404 |
+
k,
|
| 405 |
+
v,
|
| 406 |
+
attn_mask=mask,
|
| 407 |
+
dropout_p=self.dropout_prob if self.training else 0.0,
|
| 408 |
+
is_causal=False,
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
attn_output = unshape(attn_output)
|
| 412 |
+
attn_output = self.out_lin(attn_output)
|
| 413 |
+
|
| 414 |
+
return (attn_output,)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
class FFN(nn.Module):
|
| 418 |
+
def __init__(self, config: PretrainedConfig):
|
| 419 |
+
super().__init__()
|
| 420 |
+
self.dropout = nn.Dropout(p=config.dropout)
|
| 421 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 422 |
+
self.seq_len_dim = 1
|
| 423 |
+
self.lin1 = nn.Linear(in_features=config.dim, out_features=config.hidden_dim)
|
| 424 |
+
self.lin2 = nn.Linear(in_features=config.hidden_dim, out_features=config.dim)
|
| 425 |
+
self.activation = get_activation(config.activation)
|
| 426 |
+
|
| 427 |
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
|
| 428 |
+
return apply_chunking_to_forward(self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, input)
|
| 429 |
+
|
| 430 |
+
def ff_chunk(self, input: torch.Tensor) -> torch.Tensor:
|
| 431 |
+
x = self.lin1(input)
|
| 432 |
+
x = self.activation(x)
|
| 433 |
+
x = self.lin2(x)
|
| 434 |
+
x = self.dropout(x)
|
| 435 |
+
return x
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
DISTILBERT_ATTENTION_CLASSES = {
|
| 439 |
+
"eager": MultiHeadSelfAttention,
|
| 440 |
+
"flash_attention_2": DistilBertFlashAttention2,
|
| 441 |
+
"sdpa": DistilBertSdpaAttention,
|
| 442 |
+
}
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
class TransformerBlock(GradientCheckpointingLayer):
|
| 446 |
+
def __init__(self, config: PretrainedConfig):
|
| 447 |
+
super().__init__()
|
| 448 |
+
|
| 449 |
+
# Have an even number of Configure multi-heads
|
| 450 |
+
if config.dim % config.n_heads != 0:
|
| 451 |
+
raise ValueError(f"config.n_heads {config.n_heads} must divide config.dim {config.dim} evenly")
|
| 452 |
+
|
| 453 |
+
self.attention = DISTILBERT_ATTENTION_CLASSES[config._attn_implementation](config)
|
| 454 |
+
self.sa_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)
|
| 455 |
+
|
| 456 |
+
self.ffn = FFN(config)
|
| 457 |
+
self.output_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)
|
| 458 |
+
|
| 459 |
+
def forward(
|
| 460 |
+
self,
|
| 461 |
+
x: torch.Tensor,
|
| 462 |
+
attn_mask: Optional[torch.Tensor] = None,
|
| 463 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 464 |
+
output_attentions: bool = False,
|
| 465 |
+
) -> tuple[torch.Tensor, ...]:
|
| 466 |
+
"""
|
| 467 |
+
Parameters:
|
| 468 |
+
x: torch.tensor(bs, seq_length, dim)
|
| 469 |
+
attn_mask: torch.tensor(bs, seq_length)
|
| 470 |
+
|
| 471 |
+
Returns:
|
| 472 |
+
sa_weights: torch.tensor(bs, n_heads, seq_length, seq_length) The attention weights ffn_output:
|
| 473 |
+
torch.tensor(bs, seq_length, dim) The output of the transformer block contextualization.
|
| 474 |
+
"""
|
| 475 |
+
# Self-Attention
|
| 476 |
+
sa_output = self.attention(
|
| 477 |
+
query=x,
|
| 478 |
+
key=x,
|
| 479 |
+
value=x,
|
| 480 |
+
mask=attn_mask,
|
| 481 |
+
head_mask=head_mask,
|
| 482 |
+
output_attentions=output_attentions,
|
| 483 |
+
)
|
| 484 |
+
if output_attentions:
|
| 485 |
+
sa_output, sa_weights = sa_output # (bs, seq_length, dim), (bs, n_heads, seq_length, seq_length)
|
| 486 |
+
else: # To handle these `output_attentions` or `output_hidden_states` cases returning tuples
|
| 487 |
+
if type(sa_output) is not tuple:
|
| 488 |
+
raise TypeError(f"sa_output must be a tuple but it is {type(sa_output)} type")
|
| 489 |
+
|
| 490 |
+
sa_output = sa_output[0]
|
| 491 |
+
sa_output = self.sa_layer_norm(sa_output + x) # (bs, seq_length, dim)
|
| 492 |
+
|
| 493 |
+
# Feed Forward Network
|
| 494 |
+
ffn_output = self.ffn(sa_output) # (bs, seq_length, dim)
|
| 495 |
+
ffn_output: torch.Tensor = self.output_layer_norm(ffn_output + sa_output) # (bs, seq_length, dim)
|
| 496 |
+
|
| 497 |
+
output = (ffn_output,)
|
| 498 |
+
if output_attentions:
|
| 499 |
+
output = (sa_weights,) + output
|
| 500 |
+
return output
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
class Transformer(nn.Module):
|
| 504 |
+
def __init__(self, config: PretrainedConfig):
|
| 505 |
+
super().__init__()
|
| 506 |
+
self.n_layers = config.n_layers
|
| 507 |
+
self.layer = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layers)])
|
| 508 |
+
self.gradient_checkpointing = False
|
| 509 |
+
|
| 510 |
+
def forward(
|
| 511 |
+
self,
|
| 512 |
+
x: torch.Tensor,
|
| 513 |
+
attn_mask: Optional[torch.Tensor] = None,
|
| 514 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 515 |
+
output_attentions: bool = False,
|
| 516 |
+
output_hidden_states: bool = False,
|
| 517 |
+
return_dict: Optional[bool] = None,
|
| 518 |
+
) -> Union[BaseModelOutput, tuple[torch.Tensor, ...]]: # docstyle-ignore
|
| 519 |
+
"""
|
| 520 |
+
Parameters:
|
| 521 |
+
x: torch.tensor(bs, seq_length, dim) Input sequence embedded.
|
| 522 |
+
attn_mask: torch.tensor(bs, seq_length) Attention mask on the sequence.
|
| 523 |
+
|
| 524 |
+
Returns:
|
| 525 |
+
hidden_state: torch.tensor(bs, seq_length, dim) Sequence of hidden states in the last (top)
|
| 526 |
+
layer all_hidden_states: tuple[torch.tensor(bs, seq_length, dim)]
|
| 527 |
+
Tuple of length n_layers with the hidden states from each layer.
|
| 528 |
+
Optional: only if output_hidden_states=True
|
| 529 |
+
all_attentions: tuple[torch.tensor(bs, n_heads, seq_length, seq_length)]
|
| 530 |
+
Tuple of length n_layers with the attention weights from each layer
|
| 531 |
+
Optional: only if output_attentions=True
|
| 532 |
+
"""
|
| 533 |
+
all_hidden_states = () if output_hidden_states else None
|
| 534 |
+
all_attentions = () if output_attentions else None
|
| 535 |
+
|
| 536 |
+
hidden_state = x
|
| 537 |
+
for i, layer_module in enumerate(self.layer):
|
| 538 |
+
if output_hidden_states:
|
| 539 |
+
all_hidden_states = all_hidden_states + (hidden_state,)
|
| 540 |
+
|
| 541 |
+
layer_outputs = layer_module(
|
| 542 |
+
hidden_state,
|
| 543 |
+
attn_mask,
|
| 544 |
+
head_mask[i],
|
| 545 |
+
output_attentions,
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
hidden_state = layer_outputs[-1]
|
| 549 |
+
|
| 550 |
+
if output_attentions:
|
| 551 |
+
if len(layer_outputs) != 2:
|
| 552 |
+
raise ValueError(f"The length of the layer_outputs should be 2, but it is {len(layer_outputs)}")
|
| 553 |
+
|
| 554 |
+
attentions = layer_outputs[0]
|
| 555 |
+
all_attentions = all_attentions + (attentions,)
|
| 556 |
+
else:
|
| 557 |
+
if len(layer_outputs) != 1:
|
| 558 |
+
raise ValueError(f"The length of the layer_outputs should be 1, but it is {len(layer_outputs)}")
|
| 559 |
+
|
| 560 |
+
# Add last layer
|
| 561 |
+
if output_hidden_states:
|
| 562 |
+
all_hidden_states = all_hidden_states + (hidden_state,)
|
| 563 |
+
|
| 564 |
+
if not return_dict:
|
| 565 |
+
return tuple(v for v in [hidden_state, all_hidden_states, all_attentions] if v is not None)
|
| 566 |
+
return BaseModelOutput(
|
| 567 |
+
last_hidden_state=hidden_state, hidden_states=all_hidden_states, attentions=all_attentions
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
# INTERFACE FOR ENCODER AND TASK SPECIFIC MODEL #
|
| 572 |
+
@auto_docstring
|
| 573 |
+
class DistilBertPreTrainedModel(PreTrainedModel):
|
| 574 |
+
config: DistilBertConfig
|
| 575 |
+
load_tf_weights = None
|
| 576 |
+
base_model_prefix = "distilbert"
|
| 577 |
+
supports_gradient_checkpointing = True
|
| 578 |
+
_supports_flash_attn = True
|
| 579 |
+
_supports_sdpa = True
|
| 580 |
+
|
| 581 |
+
def _init_weights(self, module: nn.Module):
|
| 582 |
+
"""Initialize the weights."""
|
| 583 |
+
if isinstance(module, nn.Linear):
|
| 584 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 585 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 586 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 587 |
+
if module.bias is not None:
|
| 588 |
+
module.bias.data.zero_()
|
| 589 |
+
elif isinstance(module, nn.Embedding):
|
| 590 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 591 |
+
if module.padding_idx is not None:
|
| 592 |
+
module.weight.data[module.padding_idx].zero_()
|
| 593 |
+
elif isinstance(module, nn.LayerNorm):
|
| 594 |
+
module.bias.data.zero_()
|
| 595 |
+
module.weight.data.fill_(1.0)
|
| 596 |
+
elif isinstance(module, Embeddings) and self.config.sinusoidal_pos_embds:
|
| 597 |
+
create_sinusoidal_embeddings(
|
| 598 |
+
self.config.max_position_embeddings, self.config.dim, module.position_embeddings.weight
|
| 599 |
+
)
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
@auto_docstring
|
| 603 |
+
class DistilBertModel(DistilBertPreTrainedModel):
|
| 604 |
+
def __init__(self, config: PretrainedConfig):
|
| 605 |
+
super().__init__(config)
|
| 606 |
+
|
| 607 |
+
self.embeddings = Embeddings(config) # Embeddings
|
| 608 |
+
self.transformer = Transformer(config) # Encoder
|
| 609 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
| 610 |
+
self._use_sdpa = config._attn_implementation == "sdpa"
|
| 611 |
+
|
| 612 |
+
# Initialize weights and apply final processing
|
| 613 |
+
self.post_init()
|
| 614 |
+
|
| 615 |
+
def get_position_embeddings(self) -> nn.Embedding:
|
| 616 |
+
"""
|
| 617 |
+
Returns the position embeddings
|
| 618 |
+
"""
|
| 619 |
+
return self.embeddings.position_embeddings
|
| 620 |
+
|
| 621 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 622 |
+
"""
|
| 623 |
+
Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
|
| 624 |
+
|
| 625 |
+
Arguments:
|
| 626 |
+
new_num_position_embeddings (`int`):
|
| 627 |
+
The number of new position embedding matrix. If position embeddings are learned, increasing the size
|
| 628 |
+
will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
|
| 629 |
+
end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
|
| 630 |
+
size will add correct vectors at the end following the position encoding algorithm, whereas reducing
|
| 631 |
+
the size will remove vectors from the end.
|
| 632 |
+
"""
|
| 633 |
+
num_position_embeds_diff = new_num_position_embeddings - self.config.max_position_embeddings
|
| 634 |
+
|
| 635 |
+
# no resizing needs to be done if the length stays the same
|
| 636 |
+
if num_position_embeds_diff == 0:
|
| 637 |
+
return
|
| 638 |
+
|
| 639 |
+
logger.info(f"Setting `config.max_position_embeddings={new_num_position_embeddings}`...")
|
| 640 |
+
self.config.max_position_embeddings = new_num_position_embeddings
|
| 641 |
+
|
| 642 |
+
old_position_embeddings_weight = self.embeddings.position_embeddings.weight.clone()
|
| 643 |
+
|
| 644 |
+
self.embeddings.position_embeddings = nn.Embedding(self.config.max_position_embeddings, self.config.dim)
|
| 645 |
+
|
| 646 |
+
if self.config.sinusoidal_pos_embds:
|
| 647 |
+
create_sinusoidal_embeddings(
|
| 648 |
+
n_pos=self.config.max_position_embeddings, dim=self.config.dim, out=self.position_embeddings.weight
|
| 649 |
+
)
|
| 650 |
+
else:
|
| 651 |
+
with torch.no_grad():
|
| 652 |
+
if num_position_embeds_diff > 0:
|
| 653 |
+
self.embeddings.position_embeddings.weight[:-num_position_embeds_diff] = nn.Parameter(
|
| 654 |
+
old_position_embeddings_weight
|
| 655 |
+
)
|
| 656 |
+
else:
|
| 657 |
+
self.embeddings.position_embeddings.weight = nn.Parameter(
|
| 658 |
+
old_position_embeddings_weight[:num_position_embeds_diff]
|
| 659 |
+
)
|
| 660 |
+
# move position_embeddings to correct device
|
| 661 |
+
self.embeddings.position_embeddings.to(self.device)
|
| 662 |
+
|
| 663 |
+
def get_input_embeddings(self) -> nn.Embedding:
|
| 664 |
+
return self.embeddings.word_embeddings
|
| 665 |
+
|
| 666 |
+
def set_input_embeddings(self, new_embeddings: nn.Embedding):
|
| 667 |
+
self.embeddings.word_embeddings = new_embeddings
|
| 668 |
+
|
| 669 |
+
def _prune_heads(self, heads_to_prune: dict[int, list[list[int]]]):
|
| 670 |
+
"""
|
| 671 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 672 |
+
class PreTrainedModel
|
| 673 |
+
"""
|
| 674 |
+
for layer, heads in heads_to_prune.items():
|
| 675 |
+
self.transformer.layer[layer].attention.prune_heads(heads)
|
| 676 |
+
|
| 677 |
+
@auto_docstring
|
| 678 |
+
def forward(
|
| 679 |
+
self,
|
| 680 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 681 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 682 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 683 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 684 |
+
output_attentions: Optional[bool] = None,
|
| 685 |
+
output_hidden_states: Optional[bool] = None,
|
| 686 |
+
return_dict: Optional[bool] = None,
|
| 687 |
+
) -> Union[BaseModelOutput, tuple[torch.Tensor, ...]]:
|
| 688 |
+
r"""
|
| 689 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`):
|
| 690 |
+
Indices of input sequence tokens in the vocabulary.
|
| 691 |
+
|
| 692 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 693 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 694 |
+
|
| 695 |
+
[What are input IDs?](../glossary#input-ids)
|
| 696 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, hidden_size)`, *optional*):
|
| 697 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 698 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 699 |
+
model's internal embedding lookup matrix.
|
| 700 |
+
"""
|
| 701 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 702 |
+
output_hidden_states = (
|
| 703 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 704 |
+
)
|
| 705 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 706 |
+
|
| 707 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 708 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 709 |
+
elif input_ids is not None:
|
| 710 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 711 |
+
input_shape = input_ids.size()
|
| 712 |
+
elif inputs_embeds is not None:
|
| 713 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 714 |
+
else:
|
| 715 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 716 |
+
|
| 717 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 718 |
+
|
| 719 |
+
head_mask_is_none = head_mask is None
|
| 720 |
+
# Prepare head mask if needed
|
| 721 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 722 |
+
|
| 723 |
+
embeddings = self.embeddings(input_ids, inputs_embeds) # (bs, seq_length, dim)
|
| 724 |
+
|
| 725 |
+
if self._use_flash_attention_2:
|
| 726 |
+
attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
| 727 |
+
else:
|
| 728 |
+
if attention_mask is None:
|
| 729 |
+
attention_mask = torch.ones(input_shape, device=device) # (bs, seq_length)
|
| 730 |
+
|
| 731 |
+
if self._use_sdpa and head_mask_is_none and not output_attentions:
|
| 732 |
+
attention_mask = _prepare_4d_attention_mask_for_sdpa(
|
| 733 |
+
attention_mask, embeddings.dtype, tgt_len=input_shape[1]
|
| 734 |
+
)
|
| 735 |
+
|
| 736 |
+
return self.transformer(
|
| 737 |
+
x=embeddings,
|
| 738 |
+
attn_mask=attention_mask,
|
| 739 |
+
head_mask=head_mask,
|
| 740 |
+
output_attentions=output_attentions,
|
| 741 |
+
output_hidden_states=output_hidden_states,
|
| 742 |
+
return_dict=return_dict,
|
| 743 |
+
)
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
@auto_docstring(
|
| 747 |
+
custom_intro="""
|
| 748 |
+
DistilBert Model with a `masked language modeling` head on top.
|
| 749 |
+
"""
|
| 750 |
+
)
|
| 751 |
+
class DistilBertForMaskedLM(DistilBertPreTrainedModel):
|
| 752 |
+
_tied_weights_keys = ["vocab_projector.weight"]
|
| 753 |
+
|
| 754 |
+
def __init__(self, config: PretrainedConfig):
|
| 755 |
+
super().__init__(config)
|
| 756 |
+
|
| 757 |
+
self.activation = get_activation(config.activation)
|
| 758 |
+
|
| 759 |
+
self.distilbert = DistilBertModel(config)
|
| 760 |
+
self.vocab_transform = nn.Linear(config.dim, config.dim)
|
| 761 |
+
self.vocab_layer_norm = nn.LayerNorm(config.dim, eps=1e-12)
|
| 762 |
+
self.vocab_projector = nn.Linear(config.dim, config.vocab_size)
|
| 763 |
+
|
| 764 |
+
# Initialize weights and apply final processing
|
| 765 |
+
self.post_init()
|
| 766 |
+
|
| 767 |
+
self.mlm_loss_fct = nn.CrossEntropyLoss()
|
| 768 |
+
|
| 769 |
+
def get_position_embeddings(self) -> nn.Embedding:
|
| 770 |
+
"""
|
| 771 |
+
Returns the position embeddings
|
| 772 |
+
"""
|
| 773 |
+
return self.distilbert.get_position_embeddings()
|
| 774 |
+
|
| 775 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 776 |
+
"""
|
| 777 |
+
Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
|
| 778 |
+
|
| 779 |
+
Arguments:
|
| 780 |
+
new_num_position_embeddings (`int`):
|
| 781 |
+
The number of new position embedding matrix. If position embeddings are learned, increasing the size
|
| 782 |
+
will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
|
| 783 |
+
end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
|
| 784 |
+
size will add correct vectors at the end following the position encoding algorithm, whereas reducing
|
| 785 |
+
the size will remove vectors from the end.
|
| 786 |
+
"""
|
| 787 |
+
self.distilbert.resize_position_embeddings(new_num_position_embeddings)
|
| 788 |
+
|
| 789 |
+
def get_output_embeddings(self) -> nn.Module:
|
| 790 |
+
return self.vocab_projector
|
| 791 |
+
|
| 792 |
+
def set_output_embeddings(self, new_embeddings: nn.Module):
|
| 793 |
+
self.vocab_projector = new_embeddings
|
| 794 |
+
|
| 795 |
+
@auto_docstring
|
| 796 |
+
def forward(
|
| 797 |
+
self,
|
| 798 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 799 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 800 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 801 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 802 |
+
labels: Optional[torch.LongTensor] = None,
|
| 803 |
+
output_attentions: Optional[bool] = None,
|
| 804 |
+
output_hidden_states: Optional[bool] = None,
|
| 805 |
+
return_dict: Optional[bool] = None,
|
| 806 |
+
) -> Union[MaskedLMOutput, tuple[torch.Tensor, ...]]:
|
| 807 |
+
r"""
|
| 808 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`):
|
| 809 |
+
Indices of input sequence tokens in the vocabulary.
|
| 810 |
+
|
| 811 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 812 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 813 |
+
|
| 814 |
+
[What are input IDs?](../glossary#input-ids)
|
| 815 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, hidden_size)`, *optional*):
|
| 816 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 817 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 818 |
+
model's internal embedding lookup matrix.
|
| 819 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 820 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 821 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 822 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 823 |
+
"""
|
| 824 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 825 |
+
|
| 826 |
+
dlbrt_output = self.distilbert(
|
| 827 |
+
input_ids=input_ids,
|
| 828 |
+
attention_mask=attention_mask,
|
| 829 |
+
head_mask=head_mask,
|
| 830 |
+
inputs_embeds=inputs_embeds,
|
| 831 |
+
output_attentions=output_attentions,
|
| 832 |
+
output_hidden_states=output_hidden_states,
|
| 833 |
+
return_dict=return_dict,
|
| 834 |
+
)
|
| 835 |
+
hidden_states = dlbrt_output[0] # (bs, seq_length, dim)
|
| 836 |
+
prediction_logits = self.vocab_transform(hidden_states) # (bs, seq_length, dim)
|
| 837 |
+
prediction_logits = self.activation(prediction_logits) # (bs, seq_length, dim)
|
| 838 |
+
prediction_logits = self.vocab_layer_norm(prediction_logits) # (bs, seq_length, dim)
|
| 839 |
+
prediction_logits = self.vocab_projector(prediction_logits) # (bs, seq_length, vocab_size)
|
| 840 |
+
|
| 841 |
+
mlm_loss = None
|
| 842 |
+
if labels is not None:
|
| 843 |
+
mlm_loss = self.mlm_loss_fct(prediction_logits.view(-1, prediction_logits.size(-1)), labels.view(-1))
|
| 844 |
+
|
| 845 |
+
if not return_dict:
|
| 846 |
+
output = (prediction_logits,) + dlbrt_output[1:]
|
| 847 |
+
return ((mlm_loss,) + output) if mlm_loss is not None else output
|
| 848 |
+
|
| 849 |
+
return MaskedLMOutput(
|
| 850 |
+
loss=mlm_loss,
|
| 851 |
+
logits=prediction_logits,
|
| 852 |
+
hidden_states=dlbrt_output.hidden_states,
|
| 853 |
+
attentions=dlbrt_output.attentions,
|
| 854 |
+
)
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
@auto_docstring(
|
| 858 |
+
custom_intro="""
|
| 859 |
+
DistilBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
|
| 860 |
+
pooled output) e.g. for GLUE tasks.
|
| 861 |
+
"""
|
| 862 |
+
)
|
| 863 |
+
class DistilBertForSequenceClassification(DistilBertPreTrainedModel):
|
| 864 |
+
def __init__(self, config: PretrainedConfig):
|
| 865 |
+
super().__init__(config)
|
| 866 |
+
self.num_labels = config.num_labels
|
| 867 |
+
self.config = config
|
| 868 |
+
|
| 869 |
+
self.distilbert = DistilBertModel(config)
|
| 870 |
+
self.pre_classifier = nn.Linear(config.dim, config.dim)
|
| 871 |
+
self.classifier = nn.Linear(config.dim, config.num_labels)
|
| 872 |
+
self.dropout = nn.Dropout(config.seq_classif_dropout)
|
| 873 |
+
|
| 874 |
+
# Initialize weights and apply final processing
|
| 875 |
+
self.post_init()
|
| 876 |
+
|
| 877 |
+
def get_position_embeddings(self) -> nn.Embedding:
|
| 878 |
+
"""
|
| 879 |
+
Returns the position embeddings
|
| 880 |
+
"""
|
| 881 |
+
return self.distilbert.get_position_embeddings()
|
| 882 |
+
|
| 883 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 884 |
+
"""
|
| 885 |
+
Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
|
| 886 |
+
|
| 887 |
+
Arguments:
|
| 888 |
+
new_num_position_embeddings (`int`):
|
| 889 |
+
The number of new position embedding matrix. If position embeddings are learned, increasing the size
|
| 890 |
+
will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
|
| 891 |
+
end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
|
| 892 |
+
size will add correct vectors at the end following the position encoding algorithm, whereas reducing
|
| 893 |
+
the size will remove vectors from the end.
|
| 894 |
+
"""
|
| 895 |
+
self.distilbert.resize_position_embeddings(new_num_position_embeddings)
|
| 896 |
+
|
| 897 |
+
@auto_docstring
|
| 898 |
+
def forward(
|
| 899 |
+
self,
|
| 900 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 901 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 902 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 903 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 904 |
+
labels: Optional[torch.LongTensor] = None,
|
| 905 |
+
output_attentions: Optional[bool] = None,
|
| 906 |
+
output_hidden_states: Optional[bool] = None,
|
| 907 |
+
return_dict: Optional[bool] = None,
|
| 908 |
+
) -> Union[SequenceClassifierOutput, tuple[torch.Tensor, ...]]:
|
| 909 |
+
r"""
|
| 910 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 911 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 912 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 913 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 914 |
+
"""
|
| 915 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 916 |
+
|
| 917 |
+
distilbert_output = self.distilbert(
|
| 918 |
+
input_ids=input_ids,
|
| 919 |
+
attention_mask=attention_mask,
|
| 920 |
+
head_mask=head_mask,
|
| 921 |
+
inputs_embeds=inputs_embeds,
|
| 922 |
+
output_attentions=output_attentions,
|
| 923 |
+
output_hidden_states=output_hidden_states,
|
| 924 |
+
return_dict=return_dict,
|
| 925 |
+
)
|
| 926 |
+
hidden_state = distilbert_output[0] # (bs, seq_len, dim)
|
| 927 |
+
pooled_output = hidden_state[:, 0] # (bs, dim)
|
| 928 |
+
pooled_output = self.pre_classifier(pooled_output) # (bs, dim)
|
| 929 |
+
pooled_output = nn.ReLU()(pooled_output) # (bs, dim)
|
| 930 |
+
pooled_output = self.dropout(pooled_output) # (bs, dim)
|
| 931 |
+
logits = self.classifier(pooled_output) # (bs, num_labels)
|
| 932 |
+
|
| 933 |
+
loss = None
|
| 934 |
+
if labels is not None:
|
| 935 |
+
if self.config.problem_type is None:
|
| 936 |
+
if self.num_labels == 1:
|
| 937 |
+
self.config.problem_type = "regression"
|
| 938 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 939 |
+
self.config.problem_type = "single_label_classification"
|
| 940 |
+
else:
|
| 941 |
+
self.config.problem_type = "multi_label_classification"
|
| 942 |
+
|
| 943 |
+
if self.config.problem_type == "regression":
|
| 944 |
+
loss_fct = MSELoss()
|
| 945 |
+
if self.num_labels == 1:
|
| 946 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 947 |
+
else:
|
| 948 |
+
loss = loss_fct(logits, labels)
|
| 949 |
+
elif self.config.problem_type == "single_label_classification":
|
| 950 |
+
loss_fct = CrossEntropyLoss()
|
| 951 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 952 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 953 |
+
loss_fct = BCEWithLogitsLoss()
|
| 954 |
+
loss = loss_fct(logits, labels)
|
| 955 |
+
|
| 956 |
+
if not return_dict:
|
| 957 |
+
output = (logits,) + distilbert_output[1:]
|
| 958 |
+
return ((loss,) + output) if loss is not None else output
|
| 959 |
+
|
| 960 |
+
return SequenceClassifierOutput(
|
| 961 |
+
loss=loss,
|
| 962 |
+
logits=logits,
|
| 963 |
+
hidden_states=distilbert_output.hidden_states,
|
| 964 |
+
attentions=distilbert_output.attentions,
|
| 965 |
+
)
|
| 966 |
+
|
| 967 |
+
|
| 968 |
+
@auto_docstring
|
| 969 |
+
class DistilBertForQuestionAnswering(DistilBertPreTrainedModel):
|
| 970 |
+
def __init__(self, config: PretrainedConfig):
|
| 971 |
+
super().__init__(config)
|
| 972 |
+
|
| 973 |
+
self.distilbert = DistilBertModel(config)
|
| 974 |
+
self.qa_outputs = nn.Linear(config.dim, config.num_labels)
|
| 975 |
+
if config.num_labels != 2:
|
| 976 |
+
raise ValueError(f"config.num_labels should be 2, but it is {config.num_labels}")
|
| 977 |
+
|
| 978 |
+
self.dropout = nn.Dropout(config.qa_dropout)
|
| 979 |
+
|
| 980 |
+
# Initialize weights and apply final processing
|
| 981 |
+
self.post_init()
|
| 982 |
+
|
| 983 |
+
def get_position_embeddings(self) -> nn.Embedding:
|
| 984 |
+
"""
|
| 985 |
+
Returns the position embeddings
|
| 986 |
+
"""
|
| 987 |
+
return self.distilbert.get_position_embeddings()
|
| 988 |
+
|
| 989 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 990 |
+
"""
|
| 991 |
+
Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
|
| 992 |
+
|
| 993 |
+
Arguments:
|
| 994 |
+
new_num_position_embeddings (`int`):
|
| 995 |
+
The number of new position embedding matrix. If position embeddings are learned, increasing the size
|
| 996 |
+
will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
|
| 997 |
+
end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
|
| 998 |
+
size will add correct vectors at the end following the position encoding algorithm, whereas reducing
|
| 999 |
+
the size will remove vectors from the end.
|
| 1000 |
+
"""
|
| 1001 |
+
self.distilbert.resize_position_embeddings(new_num_position_embeddings)
|
| 1002 |
+
|
| 1003 |
+
@auto_docstring
|
| 1004 |
+
def forward(
|
| 1005 |
+
self,
|
| 1006 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1007 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1008 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1009 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1010 |
+
start_positions: Optional[torch.Tensor] = None,
|
| 1011 |
+
end_positions: Optional[torch.Tensor] = None,
|
| 1012 |
+
output_attentions: Optional[bool] = None,
|
| 1013 |
+
output_hidden_states: Optional[bool] = None,
|
| 1014 |
+
return_dict: Optional[bool] = None,
|
| 1015 |
+
) -> Union[QuestionAnsweringModelOutput, tuple[torch.Tensor, ...]]:
|
| 1016 |
+
r"""
|
| 1017 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`):
|
| 1018 |
+
Indices of input sequence tokens in the vocabulary.
|
| 1019 |
+
|
| 1020 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1021 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1022 |
+
|
| 1023 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1024 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, hidden_size)`, *optional*):
|
| 1025 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 1026 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 1027 |
+
model's internal embedding lookup matrix.
|
| 1028 |
+
"""
|
| 1029 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1030 |
+
|
| 1031 |
+
distilbert_output = self.distilbert(
|
| 1032 |
+
input_ids=input_ids,
|
| 1033 |
+
attention_mask=attention_mask,
|
| 1034 |
+
head_mask=head_mask,
|
| 1035 |
+
inputs_embeds=inputs_embeds,
|
| 1036 |
+
output_attentions=output_attentions,
|
| 1037 |
+
output_hidden_states=output_hidden_states,
|
| 1038 |
+
return_dict=return_dict,
|
| 1039 |
+
)
|
| 1040 |
+
hidden_states = distilbert_output[0] # (bs, max_query_len, dim)
|
| 1041 |
+
|
| 1042 |
+
hidden_states = self.dropout(hidden_states) # (bs, max_query_len, dim)
|
| 1043 |
+
logits = self.qa_outputs(hidden_states) # (bs, max_query_len, 2)
|
| 1044 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1045 |
+
start_logits = start_logits.squeeze(-1).contiguous() # (bs, max_query_len)
|
| 1046 |
+
end_logits = end_logits.squeeze(-1).contiguous() # (bs, max_query_len)
|
| 1047 |
+
|
| 1048 |
+
total_loss = None
|
| 1049 |
+
if start_positions is not None and end_positions is not None:
|
| 1050 |
+
# If we are on multi-GPU, split add a dimension
|
| 1051 |
+
if len(start_positions.size()) > 1:
|
| 1052 |
+
start_positions = start_positions.squeeze(-1)
|
| 1053 |
+
if len(end_positions.size()) > 1:
|
| 1054 |
+
end_positions = end_positions.squeeze(-1)
|
| 1055 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1056 |
+
ignored_index = start_logits.size(1)
|
| 1057 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 1058 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 1059 |
+
|
| 1060 |
+
loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
|
| 1061 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1062 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1063 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1064 |
+
|
| 1065 |
+
if not return_dict:
|
| 1066 |
+
output = (start_logits, end_logits) + distilbert_output[1:]
|
| 1067 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 1068 |
+
|
| 1069 |
+
return QuestionAnsweringModelOutput(
|
| 1070 |
+
loss=total_loss,
|
| 1071 |
+
start_logits=start_logits,
|
| 1072 |
+
end_logits=end_logits,
|
| 1073 |
+
hidden_states=distilbert_output.hidden_states,
|
| 1074 |
+
attentions=distilbert_output.attentions,
|
| 1075 |
+
)
|
| 1076 |
+
|
| 1077 |
+
|
| 1078 |
+
@auto_docstring
|
| 1079 |
+
class DistilBertForTokenClassification(DistilBertPreTrainedModel):
|
| 1080 |
+
def __init__(self, config: PretrainedConfig):
|
| 1081 |
+
super().__init__(config)
|
| 1082 |
+
self.num_labels = config.num_labels
|
| 1083 |
+
|
| 1084 |
+
self.distilbert = DistilBertModel(config)
|
| 1085 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 1086 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 1087 |
+
|
| 1088 |
+
# Initialize weights and apply final processing
|
| 1089 |
+
self.post_init()
|
| 1090 |
+
|
| 1091 |
+
def get_position_embeddings(self) -> nn.Embedding:
|
| 1092 |
+
"""
|
| 1093 |
+
Returns the position embeddings
|
| 1094 |
+
"""
|
| 1095 |
+
return self.distilbert.get_position_embeddings()
|
| 1096 |
+
|
| 1097 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 1098 |
+
"""
|
| 1099 |
+
Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
|
| 1100 |
+
|
| 1101 |
+
Arguments:
|
| 1102 |
+
new_num_position_embeddings (`int`):
|
| 1103 |
+
The number of new position embedding matrix. If position embeddings are learned, increasing the size
|
| 1104 |
+
will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
|
| 1105 |
+
end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
|
| 1106 |
+
size will add correct vectors at the end following the position encoding algorithm, whereas reducing
|
| 1107 |
+
the size will remove vectors from the end.
|
| 1108 |
+
"""
|
| 1109 |
+
self.distilbert.resize_position_embeddings(new_num_position_embeddings)
|
| 1110 |
+
|
| 1111 |
+
@auto_docstring
|
| 1112 |
+
def forward(
|
| 1113 |
+
self,
|
| 1114 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1115 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1116 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1117 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1118 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1119 |
+
output_attentions: Optional[bool] = None,
|
| 1120 |
+
output_hidden_states: Optional[bool] = None,
|
| 1121 |
+
return_dict: Optional[bool] = None,
|
| 1122 |
+
) -> Union[TokenClassifierOutput, tuple[torch.Tensor, ...]]:
|
| 1123 |
+
r"""
|
| 1124 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1125 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 1126 |
+
"""
|
| 1127 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1128 |
+
|
| 1129 |
+
outputs = self.distilbert(
|
| 1130 |
+
input_ids,
|
| 1131 |
+
attention_mask=attention_mask,
|
| 1132 |
+
head_mask=head_mask,
|
| 1133 |
+
inputs_embeds=inputs_embeds,
|
| 1134 |
+
output_attentions=output_attentions,
|
| 1135 |
+
output_hidden_states=output_hidden_states,
|
| 1136 |
+
return_dict=return_dict,
|
| 1137 |
+
)
|
| 1138 |
+
|
| 1139 |
+
sequence_output = outputs[0]
|
| 1140 |
+
|
| 1141 |
+
sequence_output = self.dropout(sequence_output)
|
| 1142 |
+
logits = self.classifier(sequence_output)
|
| 1143 |
+
|
| 1144 |
+
loss = None
|
| 1145 |
+
if labels is not None:
|
| 1146 |
+
loss_fct = CrossEntropyLoss()
|
| 1147 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1148 |
+
|
| 1149 |
+
if not return_dict:
|
| 1150 |
+
output = (logits,) + outputs[1:]
|
| 1151 |
+
return ((loss,) + output) if loss is not None else output
|
| 1152 |
+
|
| 1153 |
+
return TokenClassifierOutput(
|
| 1154 |
+
loss=loss,
|
| 1155 |
+
logits=logits,
|
| 1156 |
+
hidden_states=outputs.hidden_states,
|
| 1157 |
+
attentions=outputs.attentions,
|
| 1158 |
+
)
|
| 1159 |
+
|
| 1160 |
+
|
| 1161 |
+
@auto_docstring
|
| 1162 |
+
class DistilBertForMultipleChoice(DistilBertPreTrainedModel):
|
| 1163 |
+
def __init__(self, config: PretrainedConfig):
|
| 1164 |
+
super().__init__(config)
|
| 1165 |
+
|
| 1166 |
+
self.distilbert = DistilBertModel(config)
|
| 1167 |
+
self.pre_classifier = nn.Linear(config.dim, config.dim)
|
| 1168 |
+
self.classifier = nn.Linear(config.dim, 1)
|
| 1169 |
+
self.dropout = nn.Dropout(config.seq_classif_dropout)
|
| 1170 |
+
|
| 1171 |
+
# Initialize weights and apply final processing
|
| 1172 |
+
self.post_init()
|
| 1173 |
+
|
| 1174 |
+
def get_position_embeddings(self) -> nn.Embedding:
|
| 1175 |
+
"""
|
| 1176 |
+
Returns the position embeddings
|
| 1177 |
+
"""
|
| 1178 |
+
return self.distilbert.get_position_embeddings()
|
| 1179 |
+
|
| 1180 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 1181 |
+
"""
|
| 1182 |
+
Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
|
| 1183 |
+
|
| 1184 |
+
Arguments:
|
| 1185 |
+
new_num_position_embeddings (`int`)
|
| 1186 |
+
The number of new position embeddings. If position embeddings are learned, increasing the size will add
|
| 1187 |
+
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
|
| 1188 |
+
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
|
| 1189 |
+
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
|
| 1190 |
+
will remove vectors from the end.
|
| 1191 |
+
"""
|
| 1192 |
+
self.distilbert.resize_position_embeddings(new_num_position_embeddings)
|
| 1193 |
+
|
| 1194 |
+
@auto_docstring
|
| 1195 |
+
def forward(
|
| 1196 |
+
self,
|
| 1197 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1198 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1199 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1200 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1201 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1202 |
+
output_attentions: Optional[bool] = None,
|
| 1203 |
+
output_hidden_states: Optional[bool] = None,
|
| 1204 |
+
return_dict: Optional[bool] = None,
|
| 1205 |
+
) -> Union[MultipleChoiceModelOutput, tuple[torch.Tensor, ...]]:
|
| 1206 |
+
r"""
|
| 1207 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
|
| 1208 |
+
Indices of input sequence tokens in the vocabulary.
|
| 1209 |
+
|
| 1210 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1211 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1212 |
+
|
| 1213 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1214 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
|
| 1215 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 1216 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 1217 |
+
model's internal embedding lookup matrix.
|
| 1218 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1219 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
|
| 1220 |
+
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
|
| 1221 |
+
`input_ids` above)
|
| 1222 |
+
|
| 1223 |
+
Examples:
|
| 1224 |
+
|
| 1225 |
+
```python
|
| 1226 |
+
>>> from transformers import AutoTokenizer, DistilBertForMultipleChoice
|
| 1227 |
+
>>> import torch
|
| 1228 |
+
|
| 1229 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased")
|
| 1230 |
+
>>> model = DistilBertForMultipleChoice.from_pretrained("distilbert-base-cased")
|
| 1231 |
+
|
| 1232 |
+
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
|
| 1233 |
+
>>> choice0 = "It is eaten with a fork and a knife."
|
| 1234 |
+
>>> choice1 = "It is eaten while held in the hand."
|
| 1235 |
+
>>> labels = torch.tensor(0).unsqueeze(0) # choice0 is correct (according to Wikipedia ;)), batch size 1
|
| 1236 |
+
|
| 1237 |
+
>>> encoding = tokenizer([[prompt, choice0], [prompt, choice1]], return_tensors="pt", padding=True)
|
| 1238 |
+
>>> outputs = model(**{k: v.unsqueeze(0) for k, v in encoding.items()}, labels=labels) # batch size is 1
|
| 1239 |
+
|
| 1240 |
+
>>> # the linear classifier still needs to be trained
|
| 1241 |
+
>>> loss = outputs.loss
|
| 1242 |
+
>>> logits = outputs.logits
|
| 1243 |
+
```"""
|
| 1244 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1245 |
+
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
|
| 1246 |
+
|
| 1247 |
+
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
|
| 1248 |
+
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
|
| 1249 |
+
inputs_embeds = (
|
| 1250 |
+
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
|
| 1251 |
+
if inputs_embeds is not None
|
| 1252 |
+
else None
|
| 1253 |
+
)
|
| 1254 |
+
|
| 1255 |
+
outputs = self.distilbert(
|
| 1256 |
+
input_ids,
|
| 1257 |
+
attention_mask=attention_mask,
|
| 1258 |
+
head_mask=head_mask,
|
| 1259 |
+
inputs_embeds=inputs_embeds,
|
| 1260 |
+
output_attentions=output_attentions,
|
| 1261 |
+
output_hidden_states=output_hidden_states,
|
| 1262 |
+
return_dict=return_dict,
|
| 1263 |
+
)
|
| 1264 |
+
|
| 1265 |
+
hidden_state = outputs[0] # (bs * num_choices, seq_len, dim)
|
| 1266 |
+
pooled_output = hidden_state[:, 0] # (bs * num_choices, dim)
|
| 1267 |
+
pooled_output = self.pre_classifier(pooled_output) # (bs * num_choices, dim)
|
| 1268 |
+
pooled_output = nn.ReLU()(pooled_output) # (bs * num_choices, dim)
|
| 1269 |
+
pooled_output = self.dropout(pooled_output) # (bs * num_choices, dim)
|
| 1270 |
+
logits = self.classifier(pooled_output) # (bs * num_choices, 1)
|
| 1271 |
+
|
| 1272 |
+
reshaped_logits = logits.view(-1, num_choices) # (bs, num_choices)
|
| 1273 |
+
|
| 1274 |
+
loss = None
|
| 1275 |
+
if labels is not None:
|
| 1276 |
+
loss_fct = CrossEntropyLoss()
|
| 1277 |
+
loss = loss_fct(reshaped_logits, labels)
|
| 1278 |
+
|
| 1279 |
+
if not return_dict:
|
| 1280 |
+
output = (reshaped_logits,) + outputs[1:]
|
| 1281 |
+
return ((loss,) + output) if loss is not None else output
|
| 1282 |
+
|
| 1283 |
+
return MultipleChoiceModelOutput(
|
| 1284 |
+
loss=loss,
|
| 1285 |
+
logits=reshaped_logits,
|
| 1286 |
+
hidden_states=outputs.hidden_states,
|
| 1287 |
+
attentions=outputs.attentions,
|
| 1288 |
+
)
|
| 1289 |
+
|
| 1290 |
+
|
| 1291 |
+
__all__ = [
|
| 1292 |
+
"DistilBertForMaskedLM",
|
| 1293 |
+
"DistilBertForMultipleChoice",
|
| 1294 |
+
"DistilBertForQuestionAnswering",
|
| 1295 |
+
"DistilBertForSequenceClassification",
|
| 1296 |
+
"DistilBertForTokenClassification",
|
| 1297 |
+
"DistilBertModel",
|
| 1298 |
+
"DistilBertPreTrainedModel",
|
| 1299 |
+
]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/distilbert/modeling_flax_distilbert.py
ADDED
|
@@ -0,0 +1,906 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ebook, Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
from typing import Callable, Optional
|
| 18 |
+
|
| 19 |
+
import flax.linen as nn
|
| 20 |
+
import jax
|
| 21 |
+
import jax.numpy as jnp
|
| 22 |
+
import numpy as np
|
| 23 |
+
from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
|
| 24 |
+
from flax.traverse_util import flatten_dict, unflatten_dict
|
| 25 |
+
from jax import lax
|
| 26 |
+
|
| 27 |
+
from ...modeling_flax_outputs import (
|
| 28 |
+
FlaxBaseModelOutput,
|
| 29 |
+
FlaxMaskedLMOutput,
|
| 30 |
+
FlaxMultipleChoiceModelOutput,
|
| 31 |
+
FlaxQuestionAnsweringModelOutput,
|
| 32 |
+
FlaxSequenceClassifierOutput,
|
| 33 |
+
FlaxTokenClassifierOutput,
|
| 34 |
+
)
|
| 35 |
+
from ...modeling_flax_utils import ACT2FN, FlaxPreTrainedModel, append_call_sample_docstring, overwrite_call_docstring
|
| 36 |
+
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging
|
| 37 |
+
from .configuration_distilbert import DistilBertConfig
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
logger = logging.get_logger(__name__)
|
| 41 |
+
|
| 42 |
+
_CHECKPOINT_FOR_DOC = "distilbert-base-uncased"
|
| 43 |
+
_CONFIG_FOR_DOC = "DistilBertConfig"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
FLAX_DISTILBERT_START_DOCSTRING = r"""
|
| 47 |
+
|
| 48 |
+
This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 49 |
+
library implements for all its model (such as downloading, saving and converting weights from PyTorch models)
|
| 50 |
+
|
| 51 |
+
This model is also a
|
| 52 |
+
[flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html) subclass. Use it as
|
| 53 |
+
a regular Flax linen Module and refer to the Flax documentation for all matter related to general usage and
|
| 54 |
+
behavior.
|
| 55 |
+
|
| 56 |
+
Finally, this model supports inherent JAX features such as:
|
| 57 |
+
|
| 58 |
+
- [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
|
| 59 |
+
- [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
|
| 60 |
+
- [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
|
| 61 |
+
- [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
|
| 62 |
+
|
| 63 |
+
Parameters:
|
| 64 |
+
config ([`DistilBertConfig`]): Model configuration class with all the parameters of the model.
|
| 65 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 66 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
DISTILBERT_INPUTS_DOCSTRING = r"""
|
| 70 |
+
Args:
|
| 71 |
+
input_ids (`numpy.ndarray` of shape `({0})`):
|
| 72 |
+
Indices of input sequence tokens in the vocabulary.
|
| 73 |
+
|
| 74 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 75 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 76 |
+
|
| 77 |
+
[What are input IDs?](../glossary#input-ids)
|
| 78 |
+
attention_mask (`numpy.ndarray` of shape `({0})`, *optional*):
|
| 79 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 80 |
+
|
| 81 |
+
- 1 for tokens that are **not masked**,
|
| 82 |
+
- 0 for tokens that are **masked**.
|
| 83 |
+
|
| 84 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 85 |
+
output_attentions (`bool`, *optional*):
|
| 86 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 87 |
+
tensors for more detail.
|
| 88 |
+
output_hidden_states (`bool`, *optional*):
|
| 89 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 90 |
+
more detail.
|
| 91 |
+
return_dict (`bool`, *optional*):
|
| 92 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def get_angles(pos, i, d_model):
|
| 97 |
+
angle_rates = 1 / np.power(10000, (2 * (i // 2)) / np.float32(d_model))
|
| 98 |
+
return pos * angle_rates
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def positional_encoding(position, d_model):
|
| 102 |
+
# create the sinusoidal pattern for the positional encoding
|
| 103 |
+
angle_rads = get_angles(np.arange(position)[:, np.newaxis], np.arange(d_model)[np.newaxis, :], d_model)
|
| 104 |
+
|
| 105 |
+
# apply sin to even indices in the array; 2i
|
| 106 |
+
angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])
|
| 107 |
+
|
| 108 |
+
# apply cos to odd indices in the array; 2i+1
|
| 109 |
+
angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])
|
| 110 |
+
|
| 111 |
+
pos_encoding = angle_rads[np.newaxis, ...]
|
| 112 |
+
|
| 113 |
+
return jnp.array(pos_encoding)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class FlaxEmbeddings(nn.Module):
|
| 117 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 118 |
+
|
| 119 |
+
config: DistilBertConfig
|
| 120 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 121 |
+
|
| 122 |
+
def setup(self):
|
| 123 |
+
self.word_embeddings = nn.Embed(
|
| 124 |
+
self.config.vocab_size,
|
| 125 |
+
self.config.dim,
|
| 126 |
+
embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 127 |
+
)
|
| 128 |
+
if not self.config.sinusoidal_pos_embds:
|
| 129 |
+
self.position_embeddings = nn.Embed(
|
| 130 |
+
self.config.max_position_embeddings,
|
| 131 |
+
self.config.dim,
|
| 132 |
+
embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 133 |
+
)
|
| 134 |
+
else:
|
| 135 |
+
self.pos_encoding = positional_encoding(self.config.max_position_embeddings, self.config.dim)
|
| 136 |
+
self.LayerNorm = nn.LayerNorm(epsilon=1e-12, dtype=self.dtype)
|
| 137 |
+
self.dropout = nn.Dropout(rate=self.config.dropout)
|
| 138 |
+
|
| 139 |
+
def __call__(self, input_ids, deterministic: bool = True):
|
| 140 |
+
# Embed
|
| 141 |
+
batch_size, seq_length = input_ids.shape
|
| 142 |
+
inputs_embeds = self.word_embeddings(input_ids.astype("i4"))
|
| 143 |
+
if not self.config.sinusoidal_pos_embds:
|
| 144 |
+
position_ids = jnp.arange(seq_length).astype("i4")
|
| 145 |
+
position_ids = jnp.broadcast_to(position_ids, shape=(batch_size, seq_length))
|
| 146 |
+
position_embeds = self.position_embeddings(position_ids.astype("i4"))
|
| 147 |
+
else:
|
| 148 |
+
position_embeds = self.pos_encoding[:, :seq_length, :]
|
| 149 |
+
# explicitly cast the positions here, since self.embed_positions are not registered as parameters
|
| 150 |
+
position_embeds = position_embeds.astype(inputs_embeds.dtype)
|
| 151 |
+
|
| 152 |
+
# Sum all embeddings
|
| 153 |
+
hidden_states = inputs_embeds + position_embeds
|
| 154 |
+
|
| 155 |
+
# Layer Norm
|
| 156 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 157 |
+
hidden_states = self.dropout(hidden_states, deterministic=deterministic)
|
| 158 |
+
return hidden_states
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class FlaxMultiHeadSelfAttention(nn.Module):
|
| 162 |
+
config: DistilBertConfig
|
| 163 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 164 |
+
|
| 165 |
+
def setup(self):
|
| 166 |
+
self.n_heads = self.config.n_heads
|
| 167 |
+
self.dim = self.config.dim
|
| 168 |
+
self.dropout = nn.Dropout(rate=self.config.attention_dropout)
|
| 169 |
+
|
| 170 |
+
if not (self.dim % self.n_heads == 0):
|
| 171 |
+
raise ValueError(f"Hidden size {self.dim} not dividable by number of heads {self.n_heads}")
|
| 172 |
+
|
| 173 |
+
self.q_lin = nn.Dense(
|
| 174 |
+
self.dim,
|
| 175 |
+
dtype=self.dtype,
|
| 176 |
+
kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 177 |
+
)
|
| 178 |
+
self.k_lin = nn.Dense(
|
| 179 |
+
self.dim,
|
| 180 |
+
dtype=self.dtype,
|
| 181 |
+
kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 182 |
+
)
|
| 183 |
+
self.v_lin = nn.Dense(
|
| 184 |
+
self.dim,
|
| 185 |
+
dtype=self.dtype,
|
| 186 |
+
kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 187 |
+
)
|
| 188 |
+
self.out_lin = nn.Dense(
|
| 189 |
+
self.dim,
|
| 190 |
+
dtype=self.dtype,
|
| 191 |
+
kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
def __call__(
|
| 195 |
+
self,
|
| 196 |
+
query,
|
| 197 |
+
key,
|
| 198 |
+
value,
|
| 199 |
+
mask,
|
| 200 |
+
deterministic: bool = True,
|
| 201 |
+
output_attentions: bool = False,
|
| 202 |
+
):
|
| 203 |
+
bs, q_len, dim = query.shape
|
| 204 |
+
k_len = key.shape[1]
|
| 205 |
+
# assert dim == self.dim, f'Dimensions do not match: {dim} input vs {self.dim} configured'
|
| 206 |
+
# assert key.size() == value.size()
|
| 207 |
+
|
| 208 |
+
dim_per_head = self.dim // self.n_heads
|
| 209 |
+
|
| 210 |
+
mask_reshp = (bs, 1, 1, k_len)
|
| 211 |
+
|
| 212 |
+
def shape(x):
|
| 213 |
+
"""separate heads"""
|
| 214 |
+
return x.reshape(bs, -1, self.n_heads, dim_per_head).transpose(0, 2, 1, 3)
|
| 215 |
+
|
| 216 |
+
def unshape(x):
|
| 217 |
+
"""group heads"""
|
| 218 |
+
return x.transpose(0, 2, 1, 3).reshape(bs, -1, self.n_heads * dim_per_head)
|
| 219 |
+
|
| 220 |
+
q = shape(self.q_lin(query)) # (bs, n_heads, q_len, dim_per_head)
|
| 221 |
+
k = shape(self.k_lin(key)) # (bs, n_heads, k_len, dim_per_head)
|
| 222 |
+
v = shape(self.v_lin(value)) # (bs, n_heads, k_len, dim_per_head)
|
| 223 |
+
|
| 224 |
+
q = q / math.sqrt(dim_per_head) # (bs, n_heads, q_len, dim_per_head)
|
| 225 |
+
scores = jnp.matmul(q, k.transpose(0, 1, 3, 2)) # (bs, n_heads, q_len, k_len)
|
| 226 |
+
mask = jnp.reshape(mask, mask_reshp)
|
| 227 |
+
|
| 228 |
+
mask = mask.astype(scores.dtype)
|
| 229 |
+
scores = scores - 1e30 * (1.0 - mask)
|
| 230 |
+
|
| 231 |
+
weights = nn.softmax(scores, axis=-1) # (bs, n_heads, q_len, k_len)
|
| 232 |
+
weights = self.dropout(weights, deterministic=deterministic)
|
| 233 |
+
|
| 234 |
+
context = jnp.matmul(weights, v) # (bs, n_heads, q_len, dim_per_head)
|
| 235 |
+
context = unshape(context) # (bs, q_len, dim)
|
| 236 |
+
context = self.out_lin(context) # (bs, q_len, dim)
|
| 237 |
+
|
| 238 |
+
if output_attentions:
|
| 239 |
+
return (context, weights)
|
| 240 |
+
else:
|
| 241 |
+
return (context,)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
class FlaxFFN(nn.Module):
|
| 245 |
+
config: DistilBertConfig
|
| 246 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 247 |
+
|
| 248 |
+
def setup(self):
|
| 249 |
+
self.dropout = nn.Dropout(rate=self.config.dropout)
|
| 250 |
+
self.chunk_size_feed_forward = self.config.chunk_size_feed_forward
|
| 251 |
+
self.seq_len_dim = 1
|
| 252 |
+
self.lin1 = nn.Dense(
|
| 253 |
+
self.config.hidden_dim,
|
| 254 |
+
dtype=self.dtype,
|
| 255 |
+
kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 256 |
+
)
|
| 257 |
+
self.lin2 = nn.Dense(
|
| 258 |
+
self.config.dim,
|
| 259 |
+
dtype=self.dtype,
|
| 260 |
+
kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
self.activation = ACT2FN[self.config.activation]
|
| 264 |
+
|
| 265 |
+
def __call__(self, hidden_states, deterministic: bool = True):
|
| 266 |
+
hidden_states = self.lin1(hidden_states)
|
| 267 |
+
hidden_states = self.activation(hidden_states)
|
| 268 |
+
hidden_states = self.lin2(hidden_states)
|
| 269 |
+
hidden_states = self.dropout(hidden_states, deterministic=deterministic)
|
| 270 |
+
return hidden_states
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
class FlaxTransformerBlock(nn.Module):
|
| 274 |
+
config: DistilBertConfig
|
| 275 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 276 |
+
|
| 277 |
+
def setup(self):
|
| 278 |
+
assert self.config.dim % self.config.n_heads == 0, (
|
| 279 |
+
f"Hidden size {self.config.dim} not dividable by number of heads {self.config.n_heads}"
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
self.attention = FlaxMultiHeadSelfAttention(self.config, dtype=self.dtype)
|
| 283 |
+
self.sa_layer_norm = nn.LayerNorm(epsilon=1e-12, dtype=self.dtype)
|
| 284 |
+
|
| 285 |
+
self.ffn = FlaxFFN(self.config, dtype=self.dtype)
|
| 286 |
+
self.output_layer_norm = nn.LayerNorm(epsilon=1e-12, dtype=self.dtype)
|
| 287 |
+
|
| 288 |
+
def __call__(
|
| 289 |
+
self,
|
| 290 |
+
hidden_states,
|
| 291 |
+
attn_mask,
|
| 292 |
+
output_attentions: bool = False,
|
| 293 |
+
deterministic: bool = True,
|
| 294 |
+
):
|
| 295 |
+
# Self-Attention
|
| 296 |
+
sa_output = self.attention(
|
| 297 |
+
query=hidden_states,
|
| 298 |
+
key=hidden_states,
|
| 299 |
+
value=hidden_states,
|
| 300 |
+
mask=attn_mask,
|
| 301 |
+
output_attentions=output_attentions,
|
| 302 |
+
deterministic=deterministic,
|
| 303 |
+
)
|
| 304 |
+
if output_attentions:
|
| 305 |
+
sa_output, sa_weights = sa_output
|
| 306 |
+
else:
|
| 307 |
+
assert type(sa_output) is tuple
|
| 308 |
+
sa_output = sa_output[0]
|
| 309 |
+
sa_output = self.sa_layer_norm(sa_output + hidden_states)
|
| 310 |
+
|
| 311 |
+
# Feed Forward Network
|
| 312 |
+
ffn_output = self.ffn(sa_output, deterministic=deterministic)
|
| 313 |
+
ffn_output = self.output_layer_norm(ffn_output + sa_output)
|
| 314 |
+
output = (ffn_output,)
|
| 315 |
+
if output_attentions:
|
| 316 |
+
output = (sa_weights,) + output
|
| 317 |
+
return output
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
class FlaxTransformer(nn.Module):
|
| 321 |
+
config: DistilBertConfig
|
| 322 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 323 |
+
|
| 324 |
+
def setup(self):
|
| 325 |
+
self.layers = [
|
| 326 |
+
FlaxTransformerBlock(self.config, name=str(i), dtype=self.dtype) for i in range(self.config.n_layers)
|
| 327 |
+
]
|
| 328 |
+
|
| 329 |
+
def __call__(
|
| 330 |
+
self,
|
| 331 |
+
hidden_states,
|
| 332 |
+
attention_mask,
|
| 333 |
+
output_attentions: bool = False,
|
| 334 |
+
output_hidden_states: bool = False,
|
| 335 |
+
deterministic: bool = True,
|
| 336 |
+
return_dict: bool = False,
|
| 337 |
+
):
|
| 338 |
+
all_hidden_states = () if output_hidden_states else None
|
| 339 |
+
all_attentions = () if output_attentions else None
|
| 340 |
+
|
| 341 |
+
for layer_module in self.layers:
|
| 342 |
+
if output_hidden_states:
|
| 343 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 344 |
+
|
| 345 |
+
layer_outputs = layer_module(
|
| 346 |
+
hidden_states=hidden_states,
|
| 347 |
+
attn_mask=attention_mask,
|
| 348 |
+
output_attentions=output_attentions,
|
| 349 |
+
deterministic=deterministic,
|
| 350 |
+
)
|
| 351 |
+
hidden_states = layer_outputs[-1]
|
| 352 |
+
|
| 353 |
+
if output_attentions:
|
| 354 |
+
assert len(layer_outputs) == 2
|
| 355 |
+
attentions = layer_outputs[0]
|
| 356 |
+
all_attentions = all_attentions + (attentions,)
|
| 357 |
+
else:
|
| 358 |
+
assert len(layer_outputs) == 1
|
| 359 |
+
|
| 360 |
+
# Add last layer
|
| 361 |
+
if output_hidden_states:
|
| 362 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 363 |
+
|
| 364 |
+
if not return_dict:
|
| 365 |
+
return tuple(v for v in [hidden_states, all_attentions, all_hidden_states] if v is not None)
|
| 366 |
+
return FlaxBaseModelOutput(
|
| 367 |
+
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
class FlaxTransformerEncoder(nn.Module):
|
| 372 |
+
config: DistilBertConfig
|
| 373 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 374 |
+
|
| 375 |
+
def setup(self):
|
| 376 |
+
self.layer = FlaxTransformer(self.config, dtype=self.dtype)
|
| 377 |
+
|
| 378 |
+
def __call__(
|
| 379 |
+
self,
|
| 380 |
+
hidden_states,
|
| 381 |
+
attention_mask,
|
| 382 |
+
output_attentions: bool = False,
|
| 383 |
+
output_hidden_states: bool = False,
|
| 384 |
+
deterministic: bool = True,
|
| 385 |
+
return_dict: bool = False,
|
| 386 |
+
):
|
| 387 |
+
return self.layer(
|
| 388 |
+
hidden_states=hidden_states,
|
| 389 |
+
attention_mask=attention_mask,
|
| 390 |
+
output_attentions=output_attentions,
|
| 391 |
+
output_hidden_states=output_hidden_states,
|
| 392 |
+
deterministic=deterministic,
|
| 393 |
+
return_dict=return_dict,
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
class FlaxDistilBertLMDecoder(nn.Module):
|
| 398 |
+
config: DistilBertConfig
|
| 399 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 400 |
+
bias_init: Callable[..., np.ndarray] = jax.nn.initializers.zeros
|
| 401 |
+
|
| 402 |
+
def setup(self):
|
| 403 |
+
self.bias = self.param("bias", self.bias_init, (self.config.vocab_size,))
|
| 404 |
+
|
| 405 |
+
def __call__(self, inputs, kernel):
|
| 406 |
+
inputs = jnp.asarray(inputs, self.dtype)
|
| 407 |
+
kernel = jnp.asarray(kernel, self.dtype)
|
| 408 |
+
y = lax.dot_general(inputs, kernel, (((inputs.ndim - 1,), (0,)), ((), ())))
|
| 409 |
+
bias = jnp.asarray(self.bias, self.dtype)
|
| 410 |
+
y = y + bias
|
| 411 |
+
return y
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
class FlaxDistilBertPreTrainedModel(FlaxPreTrainedModel):
|
| 415 |
+
"""
|
| 416 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 417 |
+
models.
|
| 418 |
+
"""
|
| 419 |
+
|
| 420 |
+
config_class = DistilBertConfig
|
| 421 |
+
base_model_prefix = "distilbert"
|
| 422 |
+
module_class: nn.Module = None
|
| 423 |
+
|
| 424 |
+
def __init__(
|
| 425 |
+
self,
|
| 426 |
+
config: DistilBertConfig,
|
| 427 |
+
input_shape: tuple = (1, 1),
|
| 428 |
+
seed: int = 0,
|
| 429 |
+
dtype: jnp.dtype = jnp.float32,
|
| 430 |
+
_do_init: bool = True,
|
| 431 |
+
**kwargs,
|
| 432 |
+
):
|
| 433 |
+
module = self.module_class(config=config, dtype=dtype, **kwargs)
|
| 434 |
+
super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
|
| 435 |
+
|
| 436 |
+
def init_weights(self, rng: jax.random.PRNGKey, input_shape: tuple, params: FrozenDict = None) -> FrozenDict:
|
| 437 |
+
# init input tensors
|
| 438 |
+
input_ids = jnp.zeros(input_shape, dtype="i4")
|
| 439 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 440 |
+
|
| 441 |
+
params_rng, dropout_rng = jax.random.split(rng)
|
| 442 |
+
rngs = {"params": params_rng, "dropout": dropout_rng}
|
| 443 |
+
|
| 444 |
+
random_params = self.module.init(rngs, input_ids, attention_mask, return_dict=False)["params"]
|
| 445 |
+
|
| 446 |
+
if params is not None:
|
| 447 |
+
random_params = flatten_dict(unfreeze(random_params))
|
| 448 |
+
params = flatten_dict(unfreeze(params))
|
| 449 |
+
for missing_key in self._missing_keys:
|
| 450 |
+
params[missing_key] = random_params[missing_key]
|
| 451 |
+
self._missing_keys = set()
|
| 452 |
+
return freeze(unflatten_dict(params))
|
| 453 |
+
else:
|
| 454 |
+
return random_params
|
| 455 |
+
|
| 456 |
+
@add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 457 |
+
def __call__(
|
| 458 |
+
self,
|
| 459 |
+
input_ids,
|
| 460 |
+
attention_mask=None,
|
| 461 |
+
head_mask=None,
|
| 462 |
+
params: Optional[dict] = None,
|
| 463 |
+
dropout_rng: jax.random.PRNGKey = None,
|
| 464 |
+
train: bool = False,
|
| 465 |
+
output_attentions: Optional[bool] = None,
|
| 466 |
+
output_hidden_states: Optional[bool] = None,
|
| 467 |
+
return_dict: Optional[bool] = None,
|
| 468 |
+
):
|
| 469 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 470 |
+
output_hidden_states = (
|
| 471 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 472 |
+
)
|
| 473 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 474 |
+
|
| 475 |
+
if attention_mask is None:
|
| 476 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 477 |
+
|
| 478 |
+
# Handle any PRNG if needed
|
| 479 |
+
rngs = {}
|
| 480 |
+
if dropout_rng is not None:
|
| 481 |
+
rngs["dropout"] = dropout_rng
|
| 482 |
+
|
| 483 |
+
return self.module.apply(
|
| 484 |
+
{"params": params or self.params},
|
| 485 |
+
jnp.array(input_ids, dtype="i4"),
|
| 486 |
+
jnp.array(attention_mask, dtype="i4"),
|
| 487 |
+
not train,
|
| 488 |
+
output_attentions,
|
| 489 |
+
output_hidden_states,
|
| 490 |
+
return_dict,
|
| 491 |
+
rngs=rngs,
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
class FlaxDistilBertModule(nn.Module):
|
| 496 |
+
config: DistilBertConfig
|
| 497 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 498 |
+
|
| 499 |
+
def setup(self):
|
| 500 |
+
self.embeddings = FlaxEmbeddings(self.config, dtype=self.dtype)
|
| 501 |
+
self.transformer = FlaxTransformerEncoder(self.config, dtype=self.dtype)
|
| 502 |
+
|
| 503 |
+
def __call__(
|
| 504 |
+
self,
|
| 505 |
+
input_ids,
|
| 506 |
+
attention_mask,
|
| 507 |
+
deterministic: bool = True,
|
| 508 |
+
output_attentions: bool = False,
|
| 509 |
+
output_hidden_states: bool = False,
|
| 510 |
+
return_dict: bool = True,
|
| 511 |
+
):
|
| 512 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 513 |
+
output_hidden_states = (
|
| 514 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 515 |
+
)
|
| 516 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 517 |
+
|
| 518 |
+
input_embeds = self.embeddings(input_ids, deterministic=deterministic)
|
| 519 |
+
return self.transformer(
|
| 520 |
+
hidden_states=input_embeds,
|
| 521 |
+
attention_mask=attention_mask,
|
| 522 |
+
deterministic=deterministic,
|
| 523 |
+
output_attentions=output_attentions,
|
| 524 |
+
output_hidden_states=output_hidden_states,
|
| 525 |
+
return_dict=return_dict,
|
| 526 |
+
)
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
@add_start_docstrings(
|
| 530 |
+
"The bare DistilBert Model transformer outputting raw hidden-states without any specific head on top.",
|
| 531 |
+
FLAX_DISTILBERT_START_DOCSTRING,
|
| 532 |
+
)
|
| 533 |
+
class FlaxDistilBertModel(FlaxDistilBertPreTrainedModel):
|
| 534 |
+
module_class = FlaxDistilBertModule
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
append_call_sample_docstring(FlaxDistilBertModel, _CHECKPOINT_FOR_DOC, None, _CONFIG_FOR_DOC)
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
class FlaxDistilBertForMaskedLMModule(nn.Module):
|
| 541 |
+
config: DistilBertConfig
|
| 542 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 543 |
+
|
| 544 |
+
def setup(self):
|
| 545 |
+
self.distilbert = FlaxDistilBertModule(self.config, dtype=self.dtype)
|
| 546 |
+
self.vocab_transform = nn.Dense(
|
| 547 |
+
self.config.dim,
|
| 548 |
+
dtype=self.dtype,
|
| 549 |
+
kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 550 |
+
)
|
| 551 |
+
self.vocab_layer_norm = nn.LayerNorm(epsilon=1e-12, dtype=self.dtype)
|
| 552 |
+
if self.config.tie_word_embeddings:
|
| 553 |
+
self.vocab_projector = FlaxDistilBertLMDecoder(
|
| 554 |
+
self.config,
|
| 555 |
+
dtype=self.dtype,
|
| 556 |
+
)
|
| 557 |
+
else:
|
| 558 |
+
self.vocab_projector = nn.Dense(
|
| 559 |
+
self.config.vocab_size,
|
| 560 |
+
dtype=self.dtype,
|
| 561 |
+
kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 562 |
+
)
|
| 563 |
+
|
| 564 |
+
def __call__(
|
| 565 |
+
self,
|
| 566 |
+
input_ids,
|
| 567 |
+
attention_mask,
|
| 568 |
+
deterministic: bool = True,
|
| 569 |
+
output_attentions: bool = False,
|
| 570 |
+
output_hidden_states: bool = False,
|
| 571 |
+
return_dict: bool = True,
|
| 572 |
+
):
|
| 573 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 574 |
+
|
| 575 |
+
dlbrt_output = self.distilbert(
|
| 576 |
+
input_ids=input_ids,
|
| 577 |
+
attention_mask=attention_mask,
|
| 578 |
+
output_attentions=output_attentions,
|
| 579 |
+
output_hidden_states=output_hidden_states,
|
| 580 |
+
deterministic=deterministic,
|
| 581 |
+
return_dict=return_dict,
|
| 582 |
+
)
|
| 583 |
+
hidden_states = dlbrt_output[0]
|
| 584 |
+
prediction_logits = self.vocab_transform(hidden_states)
|
| 585 |
+
prediction_logits = ACT2FN[self.config.activation](prediction_logits)
|
| 586 |
+
prediction_logits = self.vocab_layer_norm(prediction_logits)
|
| 587 |
+
|
| 588 |
+
if self.config.tie_word_embeddings:
|
| 589 |
+
shared_embedding = self.distilbert.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
|
| 590 |
+
prediction_logits = self.vocab_projector(prediction_logits, shared_embedding.T)
|
| 591 |
+
else:
|
| 592 |
+
prediction_logits = self.vocab_projector(prediction_logits)
|
| 593 |
+
|
| 594 |
+
if not return_dict:
|
| 595 |
+
output = (prediction_logits,) + dlbrt_output[1:]
|
| 596 |
+
return output
|
| 597 |
+
|
| 598 |
+
return FlaxMaskedLMOutput(
|
| 599 |
+
logits=prediction_logits,
|
| 600 |
+
hidden_states=dlbrt_output.hidden_states,
|
| 601 |
+
attentions=dlbrt_output.attentions,
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
@add_start_docstrings("""DistilBert Model with a `language modeling` head on top.""", FLAX_DISTILBERT_START_DOCSTRING)
|
| 606 |
+
class FlaxDistilBertForMaskedLM(FlaxDistilBertPreTrainedModel):
|
| 607 |
+
module_class = FlaxDistilBertForMaskedLMModule
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
append_call_sample_docstring(FlaxDistilBertForMaskedLM, _CHECKPOINT_FOR_DOC, FlaxMaskedLMOutput, _CONFIG_FOR_DOC)
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
class FlaxDistilBertForSequenceClassificationModule(nn.Module):
|
| 614 |
+
config: DistilBertConfig
|
| 615 |
+
dtype: jnp.dtype = jnp.float32
|
| 616 |
+
|
| 617 |
+
def setup(self):
|
| 618 |
+
self.distilbert = FlaxDistilBertModule(config=self.config, dtype=self.dtype)
|
| 619 |
+
self.pre_classifier = nn.Dense(
|
| 620 |
+
self.config.dim,
|
| 621 |
+
dtype=self.dtype,
|
| 622 |
+
kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 623 |
+
)
|
| 624 |
+
self.dropout = nn.Dropout(rate=self.config.seq_classif_dropout)
|
| 625 |
+
self.classifier = nn.Dense(
|
| 626 |
+
self.config.num_labels,
|
| 627 |
+
dtype=self.dtype,
|
| 628 |
+
)
|
| 629 |
+
|
| 630 |
+
def __call__(
|
| 631 |
+
self,
|
| 632 |
+
input_ids,
|
| 633 |
+
attention_mask,
|
| 634 |
+
deterministic: bool = True,
|
| 635 |
+
output_attentions: bool = False,
|
| 636 |
+
output_hidden_states: bool = False,
|
| 637 |
+
return_dict: bool = True,
|
| 638 |
+
):
|
| 639 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 640 |
+
# Model
|
| 641 |
+
distilbert_output = self.distilbert(
|
| 642 |
+
input_ids,
|
| 643 |
+
attention_mask,
|
| 644 |
+
deterministic=deterministic,
|
| 645 |
+
output_attentions=output_attentions,
|
| 646 |
+
output_hidden_states=output_hidden_states,
|
| 647 |
+
return_dict=return_dict,
|
| 648 |
+
)
|
| 649 |
+
hidden_state = distilbert_output[0] # (bs, seq_len, dim)
|
| 650 |
+
pooled_output = hidden_state[:, 0] # (bs, dim)
|
| 651 |
+
pooled_output = self.pre_classifier(pooled_output) # (bs, dim)
|
| 652 |
+
pooled_output = ACT2FN["relu"](pooled_output)
|
| 653 |
+
pooled_output = self.dropout(pooled_output, deterministic=deterministic)
|
| 654 |
+
logits = self.classifier(pooled_output) # (bs, dim)
|
| 655 |
+
|
| 656 |
+
if not return_dict:
|
| 657 |
+
return (logits,) + distilbert_output[1:]
|
| 658 |
+
|
| 659 |
+
return FlaxSequenceClassifierOutput(
|
| 660 |
+
logits=logits,
|
| 661 |
+
hidden_states=distilbert_output.hidden_states,
|
| 662 |
+
attentions=distilbert_output.attentions,
|
| 663 |
+
)
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
@add_start_docstrings(
|
| 667 |
+
"""
|
| 668 |
+
DistilBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
|
| 669 |
+
pooled output) e.g. for GLUE tasks.
|
| 670 |
+
""",
|
| 671 |
+
FLAX_DISTILBERT_START_DOCSTRING,
|
| 672 |
+
)
|
| 673 |
+
class FlaxDistilBertForSequenceClassification(FlaxDistilBertPreTrainedModel):
|
| 674 |
+
module_class = FlaxDistilBertForSequenceClassificationModule
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
append_call_sample_docstring(
|
| 678 |
+
FlaxDistilBertForSequenceClassification,
|
| 679 |
+
_CHECKPOINT_FOR_DOC,
|
| 680 |
+
FlaxSequenceClassifierOutput,
|
| 681 |
+
_CONFIG_FOR_DOC,
|
| 682 |
+
)
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
class FlaxDistilBertForMultipleChoiceModule(nn.Module):
|
| 686 |
+
config: DistilBertConfig
|
| 687 |
+
dtype: jnp.dtype = jnp.float32
|
| 688 |
+
|
| 689 |
+
def setup(self):
|
| 690 |
+
self.distilbert = FlaxDistilBertModule(config=self.config, dtype=self.dtype)
|
| 691 |
+
self.pre_classifier = nn.Dense(
|
| 692 |
+
self.config.dim,
|
| 693 |
+
dtype=self.dtype,
|
| 694 |
+
kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 695 |
+
)
|
| 696 |
+
self.dropout = nn.Dropout(rate=self.config.seq_classif_dropout)
|
| 697 |
+
self.classifier = nn.Dense(
|
| 698 |
+
1,
|
| 699 |
+
dtype=self.dtype,
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
def __call__(
|
| 703 |
+
self,
|
| 704 |
+
input_ids,
|
| 705 |
+
attention_mask,
|
| 706 |
+
deterministic: bool = True,
|
| 707 |
+
output_attentions: bool = False,
|
| 708 |
+
output_hidden_states: bool = False,
|
| 709 |
+
return_dict: bool = True,
|
| 710 |
+
):
|
| 711 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 712 |
+
num_choices = input_ids.shape[1]
|
| 713 |
+
input_ids = input_ids.reshape(-1, input_ids.shape[-1]) if input_ids is not None else None
|
| 714 |
+
attention_mask = attention_mask.reshape(-1, attention_mask.shape[-1]) if attention_mask is not None else None
|
| 715 |
+
|
| 716 |
+
# Model
|
| 717 |
+
outputs = self.distilbert(
|
| 718 |
+
input_ids,
|
| 719 |
+
attention_mask,
|
| 720 |
+
deterministic=deterministic,
|
| 721 |
+
output_attentions=output_attentions,
|
| 722 |
+
output_hidden_states=output_hidden_states,
|
| 723 |
+
return_dict=return_dict,
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
hidden_state = outputs[0]
|
| 727 |
+
pooled_output = hidden_state[:, 0]
|
| 728 |
+
pooled_output = self.pre_classifier(pooled_output)
|
| 729 |
+
pooled_output = ACT2FN["relu"](pooled_output)
|
| 730 |
+
pooled_output = self.dropout(pooled_output, deterministic=deterministic)
|
| 731 |
+
logits = self.classifier(pooled_output)
|
| 732 |
+
|
| 733 |
+
reshaped_logits = logits.reshape(-1, num_choices)
|
| 734 |
+
|
| 735 |
+
if not return_dict:
|
| 736 |
+
return (reshaped_logits,) + outputs[2:]
|
| 737 |
+
|
| 738 |
+
return FlaxMultipleChoiceModelOutput(
|
| 739 |
+
logits=reshaped_logits,
|
| 740 |
+
hidden_states=outputs.hidden_states,
|
| 741 |
+
attentions=outputs.attentions,
|
| 742 |
+
)
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
@add_start_docstrings(
|
| 746 |
+
"""
|
| 747 |
+
DistilBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
|
| 748 |
+
a softmax) e.g. for RocStories/SWAG tasks.
|
| 749 |
+
""",
|
| 750 |
+
FLAX_DISTILBERT_START_DOCSTRING,
|
| 751 |
+
)
|
| 752 |
+
class FlaxDistilBertForMultipleChoice(FlaxDistilBertPreTrainedModel):
|
| 753 |
+
module_class = FlaxDistilBertForMultipleChoiceModule
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
overwrite_call_docstring(
|
| 757 |
+
FlaxDistilBertForMultipleChoice, DISTILBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
|
| 758 |
+
)
|
| 759 |
+
append_call_sample_docstring(
|
| 760 |
+
FlaxDistilBertForMultipleChoice,
|
| 761 |
+
_CHECKPOINT_FOR_DOC,
|
| 762 |
+
FlaxMultipleChoiceModelOutput,
|
| 763 |
+
_CONFIG_FOR_DOC,
|
| 764 |
+
)
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
class FlaxDistilBertForTokenClassificationModule(nn.Module):
|
| 768 |
+
config: DistilBertConfig
|
| 769 |
+
dtype: jnp.dtype = jnp.float32
|
| 770 |
+
|
| 771 |
+
def setup(self):
|
| 772 |
+
self.distilbert = FlaxDistilBertModule(config=self.config, dtype=self.dtype)
|
| 773 |
+
self.dropout = nn.Dropout(rate=self.config.dropout)
|
| 774 |
+
self.classifier = nn.Dense(self.config.num_labels, dtype=self.dtype)
|
| 775 |
+
|
| 776 |
+
def __call__(
|
| 777 |
+
self,
|
| 778 |
+
input_ids,
|
| 779 |
+
attention_mask,
|
| 780 |
+
deterministic: bool = True,
|
| 781 |
+
output_attentions: bool = False,
|
| 782 |
+
output_hidden_states: bool = False,
|
| 783 |
+
return_dict: bool = True,
|
| 784 |
+
):
|
| 785 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 786 |
+
# Model
|
| 787 |
+
outputs = self.distilbert(
|
| 788 |
+
input_ids,
|
| 789 |
+
attention_mask,
|
| 790 |
+
deterministic=deterministic,
|
| 791 |
+
output_attentions=output_attentions,
|
| 792 |
+
output_hidden_states=output_hidden_states,
|
| 793 |
+
return_dict=return_dict,
|
| 794 |
+
)
|
| 795 |
+
|
| 796 |
+
hidden_states = outputs[0]
|
| 797 |
+
hidden_states = self.dropout(hidden_states, deterministic=deterministic)
|
| 798 |
+
logits = self.classifier(hidden_states)
|
| 799 |
+
|
| 800 |
+
if not return_dict:
|
| 801 |
+
return (logits,) + outputs[1:]
|
| 802 |
+
|
| 803 |
+
return FlaxTokenClassifierOutput(
|
| 804 |
+
logits=logits,
|
| 805 |
+
hidden_states=outputs.hidden_states,
|
| 806 |
+
attentions=outputs.attentions,
|
| 807 |
+
)
|
| 808 |
+
|
| 809 |
+
|
| 810 |
+
@add_start_docstrings(
|
| 811 |
+
"""
|
| 812 |
+
DistilBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
|
| 813 |
+
for Named-Entity-Recognition (NER) tasks.
|
| 814 |
+
""",
|
| 815 |
+
FLAX_DISTILBERT_START_DOCSTRING,
|
| 816 |
+
)
|
| 817 |
+
class FlaxDistilBertForTokenClassification(FlaxDistilBertPreTrainedModel):
|
| 818 |
+
module_class = FlaxDistilBertForTokenClassificationModule
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
append_call_sample_docstring(
|
| 822 |
+
FlaxDistilBertForTokenClassification,
|
| 823 |
+
_CHECKPOINT_FOR_DOC,
|
| 824 |
+
FlaxTokenClassifierOutput,
|
| 825 |
+
_CONFIG_FOR_DOC,
|
| 826 |
+
)
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
class FlaxDistilBertForQuestionAnsweringModule(nn.Module):
|
| 830 |
+
config: DistilBertConfig
|
| 831 |
+
dtype: jnp.dtype = jnp.float32
|
| 832 |
+
|
| 833 |
+
def setup(self):
|
| 834 |
+
self.distilbert = FlaxDistilBertModule(config=self.config, dtype=self.dtype)
|
| 835 |
+
self.qa_outputs = nn.Dense(self.config.num_labels, dtype=self.dtype)
|
| 836 |
+
assert self.config.num_labels == 2
|
| 837 |
+
self.dropout = nn.Dropout(rate=self.config.qa_dropout)
|
| 838 |
+
|
| 839 |
+
def __call__(
|
| 840 |
+
self,
|
| 841 |
+
input_ids,
|
| 842 |
+
attention_mask,
|
| 843 |
+
deterministic: bool = True,
|
| 844 |
+
output_attentions: bool = False,
|
| 845 |
+
output_hidden_states: bool = False,
|
| 846 |
+
return_dict: bool = True,
|
| 847 |
+
):
|
| 848 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 849 |
+
|
| 850 |
+
# Model
|
| 851 |
+
distilbert_output = self.distilbert(
|
| 852 |
+
input_ids,
|
| 853 |
+
attention_mask,
|
| 854 |
+
deterministic=deterministic,
|
| 855 |
+
output_attentions=output_attentions,
|
| 856 |
+
output_hidden_states=output_hidden_states,
|
| 857 |
+
return_dict=return_dict,
|
| 858 |
+
)
|
| 859 |
+
|
| 860 |
+
hidden_states = distilbert_output[0]
|
| 861 |
+
|
| 862 |
+
hidden_states = self.dropout(hidden_states, deterministic=deterministic)
|
| 863 |
+
logits = self.qa_outputs(hidden_states)
|
| 864 |
+
start_logits, end_logits = jnp.split(logits, self.config.num_labels, axis=-1)
|
| 865 |
+
start_logits = start_logits.squeeze(-1)
|
| 866 |
+
end_logits = end_logits.squeeze(-1)
|
| 867 |
+
|
| 868 |
+
if not return_dict:
|
| 869 |
+
return (start_logits, end_logits) + distilbert_output[1:]
|
| 870 |
+
|
| 871 |
+
return FlaxQuestionAnsweringModelOutput(
|
| 872 |
+
start_logits=start_logits,
|
| 873 |
+
end_logits=end_logits,
|
| 874 |
+
hidden_states=distilbert_output.hidden_states,
|
| 875 |
+
attentions=distilbert_output.attentions,
|
| 876 |
+
)
|
| 877 |
+
|
| 878 |
+
|
| 879 |
+
@add_start_docstrings(
|
| 880 |
+
"""
|
| 881 |
+
DistilBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
|
| 882 |
+
linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 883 |
+
""",
|
| 884 |
+
FLAX_DISTILBERT_START_DOCSTRING,
|
| 885 |
+
)
|
| 886 |
+
class FlaxDistilBertForQuestionAnswering(FlaxDistilBertPreTrainedModel):
|
| 887 |
+
module_class = FlaxDistilBertForQuestionAnsweringModule
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
append_call_sample_docstring(
|
| 891 |
+
FlaxDistilBertForQuestionAnswering,
|
| 892 |
+
_CHECKPOINT_FOR_DOC,
|
| 893 |
+
FlaxQuestionAnsweringModelOutput,
|
| 894 |
+
_CONFIG_FOR_DOC,
|
| 895 |
+
)
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
__all__ = [
|
| 899 |
+
"FlaxDistilBertForMaskedLM",
|
| 900 |
+
"FlaxDistilBertForMultipleChoice",
|
| 901 |
+
"FlaxDistilBertForQuestionAnswering",
|
| 902 |
+
"FlaxDistilBertForSequenceClassification",
|
| 903 |
+
"FlaxDistilBertForTokenClassification",
|
| 904 |
+
"FlaxDistilBertModel",
|
| 905 |
+
"FlaxDistilBertPreTrainedModel",
|
| 906 |
+
]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/distilbert/modeling_tf_distilbert.py
ADDED
|
@@ -0,0 +1,1146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
TF 2.0 DistilBERT model
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import warnings
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
import tensorflow as tf
|
| 25 |
+
|
| 26 |
+
from ...activations_tf import get_tf_activation
|
| 27 |
+
from ...modeling_tf_outputs import (
|
| 28 |
+
TFBaseModelOutput,
|
| 29 |
+
TFMaskedLMOutput,
|
| 30 |
+
TFMultipleChoiceModelOutput,
|
| 31 |
+
TFQuestionAnsweringModelOutput,
|
| 32 |
+
TFSequenceClassifierOutput,
|
| 33 |
+
TFTokenClassifierOutput,
|
| 34 |
+
)
|
| 35 |
+
from ...modeling_tf_utils import (
|
| 36 |
+
TFMaskedLanguageModelingLoss,
|
| 37 |
+
TFModelInputType,
|
| 38 |
+
TFMultipleChoiceLoss,
|
| 39 |
+
TFPreTrainedModel,
|
| 40 |
+
TFQuestionAnsweringLoss,
|
| 41 |
+
TFSequenceClassificationLoss,
|
| 42 |
+
TFTokenClassificationLoss,
|
| 43 |
+
get_initializer,
|
| 44 |
+
keras,
|
| 45 |
+
keras_serializable,
|
| 46 |
+
unpack_inputs,
|
| 47 |
+
)
|
| 48 |
+
from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
|
| 49 |
+
from ...utils import (
|
| 50 |
+
add_code_sample_docstrings,
|
| 51 |
+
add_start_docstrings,
|
| 52 |
+
add_start_docstrings_to_model_forward,
|
| 53 |
+
logging,
|
| 54 |
+
)
|
| 55 |
+
from .configuration_distilbert import DistilBertConfig
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
logger = logging.get_logger(__name__)
|
| 59 |
+
|
| 60 |
+
_CHECKPOINT_FOR_DOC = "distilbert-base-uncased"
|
| 61 |
+
_CONFIG_FOR_DOC = "DistilBertConfig"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class TFEmbeddings(keras.layers.Layer):
|
| 65 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 66 |
+
|
| 67 |
+
def __init__(self, config, **kwargs):
|
| 68 |
+
super().__init__(**kwargs)
|
| 69 |
+
self.config = config
|
| 70 |
+
self.dim = config.dim
|
| 71 |
+
self.initializer_range = config.initializer_range
|
| 72 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 73 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=1e-12, name="LayerNorm")
|
| 74 |
+
self.dropout = keras.layers.Dropout(rate=config.dropout)
|
| 75 |
+
|
| 76 |
+
def build(self, input_shape=None):
|
| 77 |
+
with tf.name_scope("word_embeddings"):
|
| 78 |
+
self.weight = self.add_weight(
|
| 79 |
+
name="weight",
|
| 80 |
+
shape=[self.config.vocab_size, self.dim],
|
| 81 |
+
initializer=get_initializer(initializer_range=self.initializer_range),
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
with tf.name_scope("position_embeddings"):
|
| 85 |
+
self.position_embeddings = self.add_weight(
|
| 86 |
+
name="embeddings",
|
| 87 |
+
shape=[self.max_position_embeddings, self.dim],
|
| 88 |
+
initializer=get_initializer(initializer_range=self.initializer_range),
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
if self.built:
|
| 92 |
+
return
|
| 93 |
+
self.built = True
|
| 94 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 95 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 96 |
+
self.LayerNorm.build([None, None, self.config.dim])
|
| 97 |
+
|
| 98 |
+
def call(self, input_ids=None, position_ids=None, inputs_embeds=None, training=False):
|
| 99 |
+
"""
|
| 100 |
+
Applies embedding based on inputs tensor.
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
final_embeddings (`tf.Tensor`): output embedding tensor.
|
| 104 |
+
"""
|
| 105 |
+
assert not (input_ids is None and inputs_embeds is None)
|
| 106 |
+
|
| 107 |
+
if input_ids is not None:
|
| 108 |
+
check_embeddings_within_bounds(input_ids, self.config.vocab_size)
|
| 109 |
+
inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
|
| 110 |
+
|
| 111 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 112 |
+
|
| 113 |
+
if position_ids is None:
|
| 114 |
+
position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
|
| 115 |
+
|
| 116 |
+
position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
|
| 117 |
+
final_embeddings = inputs_embeds + position_embeds
|
| 118 |
+
final_embeddings = self.LayerNorm(inputs=final_embeddings)
|
| 119 |
+
final_embeddings = self.dropout(inputs=final_embeddings, training=training)
|
| 120 |
+
|
| 121 |
+
return final_embeddings
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class TFMultiHeadSelfAttention(keras.layers.Layer):
|
| 125 |
+
def __init__(self, config, **kwargs):
|
| 126 |
+
super().__init__(**kwargs)
|
| 127 |
+
|
| 128 |
+
self.n_heads = config.n_heads
|
| 129 |
+
self.dim = config.dim
|
| 130 |
+
self.dropout = keras.layers.Dropout(config.attention_dropout)
|
| 131 |
+
self.output_attentions = config.output_attentions
|
| 132 |
+
|
| 133 |
+
assert self.dim % self.n_heads == 0, f"Hidden size {self.dim} not dividable by number of heads {self.n_heads}"
|
| 134 |
+
|
| 135 |
+
self.q_lin = keras.layers.Dense(
|
| 136 |
+
config.dim, kernel_initializer=get_initializer(config.initializer_range), name="q_lin"
|
| 137 |
+
)
|
| 138 |
+
self.k_lin = keras.layers.Dense(
|
| 139 |
+
config.dim, kernel_initializer=get_initializer(config.initializer_range), name="k_lin"
|
| 140 |
+
)
|
| 141 |
+
self.v_lin = keras.layers.Dense(
|
| 142 |
+
config.dim, kernel_initializer=get_initializer(config.initializer_range), name="v_lin"
|
| 143 |
+
)
|
| 144 |
+
self.out_lin = keras.layers.Dense(
|
| 145 |
+
config.dim, kernel_initializer=get_initializer(config.initializer_range), name="out_lin"
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
self.pruned_heads = set()
|
| 149 |
+
self.config = config
|
| 150 |
+
|
| 151 |
+
def prune_heads(self, heads):
|
| 152 |
+
raise NotImplementedError
|
| 153 |
+
|
| 154 |
+
def call(self, query, key, value, mask, head_mask, output_attentions, training=False):
|
| 155 |
+
"""
|
| 156 |
+
Parameters:
|
| 157 |
+
query: tf.Tensor(bs, seq_length, dim)
|
| 158 |
+
key: tf.Tensor(bs, seq_length, dim)
|
| 159 |
+
value: tf.Tensor(bs, seq_length, dim)
|
| 160 |
+
mask: tf.Tensor(bs, seq_length)
|
| 161 |
+
|
| 162 |
+
Returns:
|
| 163 |
+
weights: tf.Tensor(bs, n_heads, seq_length, seq_length) Attention weights context: tf.Tensor(bs,
|
| 164 |
+
seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
|
| 165 |
+
"""
|
| 166 |
+
bs, q_length, dim = shape_list(query)
|
| 167 |
+
k_length = shape_list(key)[1]
|
| 168 |
+
# assert dim == self.dim, f'Dimensions do not match: {dim} input vs {self.dim} configured'
|
| 169 |
+
# assert key.size() == value.size()
|
| 170 |
+
dim_per_head = int(self.dim / self.n_heads)
|
| 171 |
+
dim_per_head = tf.cast(dim_per_head, dtype=tf.int32)
|
| 172 |
+
mask_reshape = [bs, 1, 1, k_length]
|
| 173 |
+
|
| 174 |
+
def shape(x):
|
| 175 |
+
"""separate heads"""
|
| 176 |
+
return tf.transpose(tf.reshape(x, (bs, -1, self.n_heads, dim_per_head)), perm=(0, 2, 1, 3))
|
| 177 |
+
|
| 178 |
+
def unshape(x):
|
| 179 |
+
"""group heads"""
|
| 180 |
+
return tf.reshape(tf.transpose(x, perm=(0, 2, 1, 3)), (bs, -1, self.n_heads * dim_per_head))
|
| 181 |
+
|
| 182 |
+
q = shape(self.q_lin(query)) # (bs, n_heads, q_length, dim_per_head)
|
| 183 |
+
k = shape(self.k_lin(key)) # (bs, n_heads, k_length, dim_per_head)
|
| 184 |
+
v = shape(self.v_lin(value)) # (bs, n_heads, k_length, dim_per_head)
|
| 185 |
+
q = tf.cast(q, dtype=tf.float32)
|
| 186 |
+
q = tf.multiply(q, tf.math.rsqrt(tf.cast(dim_per_head, dtype=tf.float32)))
|
| 187 |
+
k = tf.cast(k, dtype=q.dtype)
|
| 188 |
+
scores = tf.matmul(q, k, transpose_b=True) # (bs, n_heads, q_length, k_length)
|
| 189 |
+
mask = tf.reshape(mask, mask_reshape) # (bs, n_heads, qlen, klen)
|
| 190 |
+
# scores.masked_fill_(mask, -float('inf')) # (bs, n_heads, q_length, k_length)
|
| 191 |
+
|
| 192 |
+
mask = tf.cast(mask, dtype=scores.dtype)
|
| 193 |
+
scores = scores - 1e30 * (1.0 - mask)
|
| 194 |
+
weights = stable_softmax(scores, axis=-1) # (bs, n_heads, qlen, klen)
|
| 195 |
+
weights = self.dropout(weights, training=training) # (bs, n_heads, qlen, klen)
|
| 196 |
+
|
| 197 |
+
# Mask heads if we want to
|
| 198 |
+
if head_mask is not None:
|
| 199 |
+
weights = weights * head_mask
|
| 200 |
+
|
| 201 |
+
context = tf.matmul(weights, v) # (bs, n_heads, qlen, dim_per_head)
|
| 202 |
+
context = unshape(context) # (bs, q_length, dim)
|
| 203 |
+
context = self.out_lin(context) # (bs, q_length, dim)
|
| 204 |
+
|
| 205 |
+
if output_attentions:
|
| 206 |
+
return (context, weights)
|
| 207 |
+
else:
|
| 208 |
+
return (context,)
|
| 209 |
+
|
| 210 |
+
def build(self, input_shape=None):
|
| 211 |
+
if self.built:
|
| 212 |
+
return
|
| 213 |
+
self.built = True
|
| 214 |
+
if getattr(self, "q_lin", None) is not None:
|
| 215 |
+
with tf.name_scope(self.q_lin.name):
|
| 216 |
+
self.q_lin.build([None, None, self.config.dim])
|
| 217 |
+
if getattr(self, "k_lin", None) is not None:
|
| 218 |
+
with tf.name_scope(self.k_lin.name):
|
| 219 |
+
self.k_lin.build([None, None, self.config.dim])
|
| 220 |
+
if getattr(self, "v_lin", None) is not None:
|
| 221 |
+
with tf.name_scope(self.v_lin.name):
|
| 222 |
+
self.v_lin.build([None, None, self.config.dim])
|
| 223 |
+
if getattr(self, "out_lin", None) is not None:
|
| 224 |
+
with tf.name_scope(self.out_lin.name):
|
| 225 |
+
self.out_lin.build([None, None, self.config.dim])
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class TFFFN(keras.layers.Layer):
|
| 229 |
+
def __init__(self, config, **kwargs):
|
| 230 |
+
super().__init__(**kwargs)
|
| 231 |
+
self.dropout = keras.layers.Dropout(config.dropout)
|
| 232 |
+
self.lin1 = keras.layers.Dense(
|
| 233 |
+
config.hidden_dim, kernel_initializer=get_initializer(config.initializer_range), name="lin1"
|
| 234 |
+
)
|
| 235 |
+
self.lin2 = keras.layers.Dense(
|
| 236 |
+
config.dim, kernel_initializer=get_initializer(config.initializer_range), name="lin2"
|
| 237 |
+
)
|
| 238 |
+
self.activation = get_tf_activation(config.activation)
|
| 239 |
+
self.config = config
|
| 240 |
+
|
| 241 |
+
def call(self, input, training=False):
|
| 242 |
+
x = self.lin1(input)
|
| 243 |
+
x = self.activation(x)
|
| 244 |
+
x = self.lin2(x)
|
| 245 |
+
x = self.dropout(x, training=training)
|
| 246 |
+
return x
|
| 247 |
+
|
| 248 |
+
def build(self, input_shape=None):
|
| 249 |
+
if self.built:
|
| 250 |
+
return
|
| 251 |
+
self.built = True
|
| 252 |
+
if getattr(self, "lin1", None) is not None:
|
| 253 |
+
with tf.name_scope(self.lin1.name):
|
| 254 |
+
self.lin1.build([None, None, self.config.dim])
|
| 255 |
+
if getattr(self, "lin2", None) is not None:
|
| 256 |
+
with tf.name_scope(self.lin2.name):
|
| 257 |
+
self.lin2.build([None, None, self.config.hidden_dim])
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class TFTransformerBlock(keras.layers.Layer):
|
| 261 |
+
def __init__(self, config, **kwargs):
|
| 262 |
+
super().__init__(**kwargs)
|
| 263 |
+
|
| 264 |
+
self.n_heads = config.n_heads
|
| 265 |
+
self.dim = config.dim
|
| 266 |
+
self.hidden_dim = config.hidden_dim
|
| 267 |
+
self.dropout = keras.layers.Dropout(config.dropout)
|
| 268 |
+
self.activation = config.activation
|
| 269 |
+
self.output_attentions = config.output_attentions
|
| 270 |
+
|
| 271 |
+
assert config.dim % config.n_heads == 0, (
|
| 272 |
+
f"Hidden size {config.dim} not dividable by number of heads {config.n_heads}"
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
self.attention = TFMultiHeadSelfAttention(config, name="attention")
|
| 276 |
+
self.sa_layer_norm = keras.layers.LayerNormalization(epsilon=1e-12, name="sa_layer_norm")
|
| 277 |
+
|
| 278 |
+
self.ffn = TFFFN(config, name="ffn")
|
| 279 |
+
self.output_layer_norm = keras.layers.LayerNormalization(epsilon=1e-12, name="output_layer_norm")
|
| 280 |
+
self.config = config
|
| 281 |
+
|
| 282 |
+
def call(self, x, attn_mask, head_mask, output_attentions, training=False): # removed: src_enc=None, src_len=None
|
| 283 |
+
"""
|
| 284 |
+
Parameters:
|
| 285 |
+
x: tf.Tensor(bs, seq_length, dim)
|
| 286 |
+
attn_mask: tf.Tensor(bs, seq_length)
|
| 287 |
+
|
| 288 |
+
Outputs: sa_weights: tf.Tensor(bs, n_heads, seq_length, seq_length) The attention weights ffn_output:
|
| 289 |
+
tf.Tensor(bs, seq_length, dim) The output of the transformer block contextualization.
|
| 290 |
+
"""
|
| 291 |
+
# Self-Attention
|
| 292 |
+
sa_output = self.attention(x, x, x, attn_mask, head_mask, output_attentions, training=training)
|
| 293 |
+
if output_attentions:
|
| 294 |
+
sa_output, sa_weights = sa_output # (bs, seq_length, dim), (bs, n_heads, seq_length, seq_length)
|
| 295 |
+
else: # To handle these `output_attentions` or `output_hidden_states` cases returning tuples
|
| 296 |
+
# assert type(sa_output) == tuple
|
| 297 |
+
sa_output = sa_output[0]
|
| 298 |
+
sa_output = self.sa_layer_norm(sa_output + x) # (bs, seq_length, dim)
|
| 299 |
+
|
| 300 |
+
# Feed Forward Network
|
| 301 |
+
ffn_output = self.ffn(sa_output, training=training) # (bs, seq_length, dim)
|
| 302 |
+
ffn_output = self.output_layer_norm(ffn_output + sa_output) # (bs, seq_length, dim)
|
| 303 |
+
|
| 304 |
+
output = (ffn_output,)
|
| 305 |
+
if output_attentions:
|
| 306 |
+
output = (sa_weights,) + output
|
| 307 |
+
return output
|
| 308 |
+
|
| 309 |
+
def build(self, input_shape=None):
|
| 310 |
+
if self.built:
|
| 311 |
+
return
|
| 312 |
+
self.built = True
|
| 313 |
+
if getattr(self, "attention", None) is not None:
|
| 314 |
+
with tf.name_scope(self.attention.name):
|
| 315 |
+
self.attention.build(None)
|
| 316 |
+
if getattr(self, "sa_layer_norm", None) is not None:
|
| 317 |
+
with tf.name_scope(self.sa_layer_norm.name):
|
| 318 |
+
self.sa_layer_norm.build([None, None, self.config.dim])
|
| 319 |
+
if getattr(self, "ffn", None) is not None:
|
| 320 |
+
with tf.name_scope(self.ffn.name):
|
| 321 |
+
self.ffn.build(None)
|
| 322 |
+
if getattr(self, "output_layer_norm", None) is not None:
|
| 323 |
+
with tf.name_scope(self.output_layer_norm.name):
|
| 324 |
+
self.output_layer_norm.build([None, None, self.config.dim])
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
class TFTransformer(keras.layers.Layer):
|
| 328 |
+
def __init__(self, config, **kwargs):
|
| 329 |
+
super().__init__(**kwargs)
|
| 330 |
+
self.n_layers = config.n_layers
|
| 331 |
+
self.output_hidden_states = config.output_hidden_states
|
| 332 |
+
self.output_attentions = config.output_attentions
|
| 333 |
+
|
| 334 |
+
self.layer = [TFTransformerBlock(config, name=f"layer_._{i}") for i in range(config.n_layers)]
|
| 335 |
+
|
| 336 |
+
def call(self, x, attn_mask, head_mask, output_attentions, output_hidden_states, return_dict, training=False):
|
| 337 |
+
# docstyle-ignore
|
| 338 |
+
"""
|
| 339 |
+
Parameters:
|
| 340 |
+
x: tf.Tensor(bs, seq_length, dim) Input sequence embedded.
|
| 341 |
+
attn_mask: tf.Tensor(bs, seq_length) Attention mask on the sequence.
|
| 342 |
+
|
| 343 |
+
Returns:
|
| 344 |
+
hidden_state: tf.Tensor(bs, seq_length, dim)
|
| 345 |
+
Sequence of hidden states in the last (top) layer
|
| 346 |
+
all_hidden_states: tuple[tf.Tensor(bs, seq_length, dim)]
|
| 347 |
+
Tuple of length n_layers with the hidden states from each layer.
|
| 348 |
+
Optional: only if output_hidden_states=True
|
| 349 |
+
all_attentions: tuple[tf.Tensor(bs, n_heads, seq_length, seq_length)]
|
| 350 |
+
Tuple of length n_layers with the attention weights from each layer
|
| 351 |
+
Optional: only if output_attentions=True
|
| 352 |
+
"""
|
| 353 |
+
all_hidden_states = () if output_hidden_states else None
|
| 354 |
+
all_attentions = () if output_attentions else None
|
| 355 |
+
|
| 356 |
+
hidden_state = x
|
| 357 |
+
for i, layer_module in enumerate(self.layer):
|
| 358 |
+
if output_hidden_states:
|
| 359 |
+
all_hidden_states = all_hidden_states + (hidden_state,)
|
| 360 |
+
|
| 361 |
+
layer_outputs = layer_module(hidden_state, attn_mask, head_mask[i], output_attentions, training=training)
|
| 362 |
+
hidden_state = layer_outputs[-1]
|
| 363 |
+
|
| 364 |
+
if output_attentions:
|
| 365 |
+
assert len(layer_outputs) == 2
|
| 366 |
+
attentions = layer_outputs[0]
|
| 367 |
+
all_attentions = all_attentions + (attentions,)
|
| 368 |
+
else:
|
| 369 |
+
assert len(layer_outputs) == 1, f"Incorrect number of outputs {len(layer_outputs)} instead of 1"
|
| 370 |
+
|
| 371 |
+
# Add last layer
|
| 372 |
+
if output_hidden_states:
|
| 373 |
+
all_hidden_states = all_hidden_states + (hidden_state,)
|
| 374 |
+
|
| 375 |
+
if not return_dict:
|
| 376 |
+
return tuple(v for v in [hidden_state, all_hidden_states, all_attentions] if v is not None)
|
| 377 |
+
return TFBaseModelOutput(
|
| 378 |
+
last_hidden_state=hidden_state, hidden_states=all_hidden_states, attentions=all_attentions
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
def build(self, input_shape=None):
|
| 382 |
+
if self.built:
|
| 383 |
+
return
|
| 384 |
+
self.built = True
|
| 385 |
+
if getattr(self, "layer", None) is not None:
|
| 386 |
+
for layer in self.layer:
|
| 387 |
+
with tf.name_scope(layer.name):
|
| 388 |
+
layer.build(None)
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
@keras_serializable
|
| 392 |
+
class TFDistilBertMainLayer(keras.layers.Layer):
|
| 393 |
+
config_class = DistilBertConfig
|
| 394 |
+
|
| 395 |
+
def __init__(self, config, **kwargs):
|
| 396 |
+
super().__init__(**kwargs)
|
| 397 |
+
|
| 398 |
+
self.config = config
|
| 399 |
+
self.num_hidden_layers = config.num_hidden_layers
|
| 400 |
+
self.output_attentions = config.output_attentions
|
| 401 |
+
self.output_hidden_states = config.output_hidden_states
|
| 402 |
+
self.return_dict = config.use_return_dict
|
| 403 |
+
|
| 404 |
+
self.embeddings = TFEmbeddings(config, name="embeddings") # Embeddings
|
| 405 |
+
self.transformer = TFTransformer(config, name="transformer") # Encoder
|
| 406 |
+
|
| 407 |
+
def get_input_embeddings(self):
|
| 408 |
+
return self.embeddings
|
| 409 |
+
|
| 410 |
+
def set_input_embeddings(self, value):
|
| 411 |
+
self.embeddings.weight = value
|
| 412 |
+
self.embeddings.vocab_size = value.shape[0]
|
| 413 |
+
|
| 414 |
+
def _prune_heads(self, heads_to_prune):
|
| 415 |
+
raise NotImplementedError
|
| 416 |
+
|
| 417 |
+
@unpack_inputs
|
| 418 |
+
def call(
|
| 419 |
+
self,
|
| 420 |
+
input_ids=None,
|
| 421 |
+
attention_mask=None,
|
| 422 |
+
head_mask=None,
|
| 423 |
+
inputs_embeds=None,
|
| 424 |
+
output_attentions=None,
|
| 425 |
+
output_hidden_states=None,
|
| 426 |
+
return_dict=None,
|
| 427 |
+
training=False,
|
| 428 |
+
):
|
| 429 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 430 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 431 |
+
elif input_ids is not None:
|
| 432 |
+
input_shape = shape_list(input_ids)
|
| 433 |
+
elif inputs_embeds is not None:
|
| 434 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 435 |
+
else:
|
| 436 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 437 |
+
|
| 438 |
+
if attention_mask is None:
|
| 439 |
+
attention_mask = tf.ones(input_shape) # (bs, seq_length)
|
| 440 |
+
|
| 441 |
+
attention_mask = tf.cast(attention_mask, dtype=tf.float32)
|
| 442 |
+
|
| 443 |
+
# Prepare head mask if needed
|
| 444 |
+
# 1.0 in head_mask indicate we keep the head
|
| 445 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 446 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 447 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 448 |
+
if head_mask is not None:
|
| 449 |
+
raise NotImplementedError
|
| 450 |
+
else:
|
| 451 |
+
head_mask = [None] * self.num_hidden_layers
|
| 452 |
+
|
| 453 |
+
embedding_output = self.embeddings(input_ids, inputs_embeds=inputs_embeds) # (bs, seq_length, dim)
|
| 454 |
+
tfmr_output = self.transformer(
|
| 455 |
+
embedding_output,
|
| 456 |
+
attention_mask,
|
| 457 |
+
head_mask,
|
| 458 |
+
output_attentions,
|
| 459 |
+
output_hidden_states,
|
| 460 |
+
return_dict,
|
| 461 |
+
training=training,
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
return tfmr_output # last-layer hidden-state, (all hidden_states), (all attentions)
|
| 465 |
+
|
| 466 |
+
def build(self, input_shape=None):
|
| 467 |
+
if self.built:
|
| 468 |
+
return
|
| 469 |
+
self.built = True
|
| 470 |
+
if getattr(self, "embeddings", None) is not None:
|
| 471 |
+
with tf.name_scope(self.embeddings.name):
|
| 472 |
+
self.embeddings.build(None)
|
| 473 |
+
if getattr(self, "transformer", None) is not None:
|
| 474 |
+
with tf.name_scope(self.transformer.name):
|
| 475 |
+
self.transformer.build(None)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
# INTERFACE FOR ENCODER AND TASK SPECIFIC MODEL #
|
| 479 |
+
class TFDistilBertPreTrainedModel(TFPreTrainedModel):
|
| 480 |
+
"""
|
| 481 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 482 |
+
models.
|
| 483 |
+
"""
|
| 484 |
+
|
| 485 |
+
config_class = DistilBertConfig
|
| 486 |
+
base_model_prefix = "distilbert"
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
DISTILBERT_START_DOCSTRING = r"""
|
| 490 |
+
|
| 491 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 492 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 493 |
+
etc.)
|
| 494 |
+
|
| 495 |
+
This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 496 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 497 |
+
behavior.
|
| 498 |
+
|
| 499 |
+
<Tip>
|
| 500 |
+
|
| 501 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
| 502 |
+
|
| 503 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 504 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
| 505 |
+
|
| 506 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
| 507 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
| 508 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
| 509 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
| 510 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
| 511 |
+
positional argument:
|
| 512 |
+
|
| 513 |
+
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
|
| 514 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
| 515 |
+
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
|
| 516 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
| 517 |
+
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
|
| 518 |
+
|
| 519 |
+
Note that when creating models and layers with
|
| 520 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
| 521 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
| 522 |
+
|
| 523 |
+
</Tip>
|
| 524 |
+
|
| 525 |
+
Parameters:
|
| 526 |
+
config ([`DistilBertConfig`]): Model configuration class with all the parameters of the model.
|
| 527 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 528 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 529 |
+
"""
|
| 530 |
+
|
| 531 |
+
DISTILBERT_INPUTS_DOCSTRING = r"""
|
| 532 |
+
Args:
|
| 533 |
+
input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
|
| 534 |
+
Indices of input sequence tokens in the vocabulary.
|
| 535 |
+
|
| 536 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
|
| 537 |
+
[`PreTrainedTokenizer.encode`] for details.
|
| 538 |
+
|
| 539 |
+
[What are input IDs?](../glossary#input-ids)
|
| 540 |
+
attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
|
| 541 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 542 |
+
|
| 543 |
+
- 1 for tokens that are **not masked**,
|
| 544 |
+
- 0 for tokens that are **masked**.
|
| 545 |
+
|
| 546 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 547 |
+
head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 548 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 549 |
+
|
| 550 |
+
- 1 indicates the head is **not masked**,
|
| 551 |
+
- 0 indicates the head is **masked**.
|
| 552 |
+
|
| 553 |
+
inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
|
| 554 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 555 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 556 |
+
model's internal embedding lookup matrix.
|
| 557 |
+
output_attentions (`bool`, *optional*):
|
| 558 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 559 |
+
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
|
| 560 |
+
config will be used instead.
|
| 561 |
+
output_hidden_states (`bool`, *optional*):
|
| 562 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 563 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 564 |
+
used instead.
|
| 565 |
+
return_dict (`bool`, *optional*):
|
| 566 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 567 |
+
eager mode, in graph mode the value will always be set to True.
|
| 568 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 569 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 570 |
+
behaviors between training and evaluation).
|
| 571 |
+
"""
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
@add_start_docstrings(
|
| 575 |
+
"The bare DistilBERT encoder/transformer outputting raw hidden-states without any specific head on top.",
|
| 576 |
+
DISTILBERT_START_DOCSTRING,
|
| 577 |
+
)
|
| 578 |
+
class TFDistilBertModel(TFDistilBertPreTrainedModel):
|
| 579 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 580 |
+
super().__init__(config, *inputs, **kwargs)
|
| 581 |
+
self.distilbert = TFDistilBertMainLayer(config, name="distilbert") # Embeddings
|
| 582 |
+
|
| 583 |
+
@unpack_inputs
|
| 584 |
+
@add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 585 |
+
@add_code_sample_docstrings(
|
| 586 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 587 |
+
output_type=TFBaseModelOutput,
|
| 588 |
+
config_class=_CONFIG_FOR_DOC,
|
| 589 |
+
)
|
| 590 |
+
def call(
|
| 591 |
+
self,
|
| 592 |
+
input_ids: TFModelInputType | None = None,
|
| 593 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 594 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 595 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 596 |
+
output_attentions: bool | None = None,
|
| 597 |
+
output_hidden_states: bool | None = None,
|
| 598 |
+
return_dict: bool | None = None,
|
| 599 |
+
training: bool | None = False,
|
| 600 |
+
) -> TFBaseModelOutput | tuple[tf.Tensor]:
|
| 601 |
+
outputs = self.distilbert(
|
| 602 |
+
input_ids=input_ids,
|
| 603 |
+
attention_mask=attention_mask,
|
| 604 |
+
head_mask=head_mask,
|
| 605 |
+
inputs_embeds=inputs_embeds,
|
| 606 |
+
output_attentions=output_attentions,
|
| 607 |
+
output_hidden_states=output_hidden_states,
|
| 608 |
+
return_dict=return_dict,
|
| 609 |
+
training=training,
|
| 610 |
+
)
|
| 611 |
+
return outputs
|
| 612 |
+
|
| 613 |
+
def build(self, input_shape=None):
|
| 614 |
+
if self.built:
|
| 615 |
+
return
|
| 616 |
+
self.built = True
|
| 617 |
+
if getattr(self, "distilbert", None) is not None:
|
| 618 |
+
with tf.name_scope(self.distilbert.name):
|
| 619 |
+
self.distilbert.build(None)
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
class TFDistilBertLMHead(keras.layers.Layer):
|
| 623 |
+
def __init__(self, config, input_embeddings, **kwargs):
|
| 624 |
+
super().__init__(**kwargs)
|
| 625 |
+
|
| 626 |
+
self.config = config
|
| 627 |
+
self.dim = config.dim
|
| 628 |
+
|
| 629 |
+
# The output weights are the same as the input embeddings, but there is
|
| 630 |
+
# an output-only bias for each token.
|
| 631 |
+
self.input_embeddings = input_embeddings
|
| 632 |
+
|
| 633 |
+
def build(self, input_shape):
|
| 634 |
+
self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
|
| 635 |
+
|
| 636 |
+
super().build(input_shape)
|
| 637 |
+
|
| 638 |
+
def get_output_embeddings(self):
|
| 639 |
+
return self.input_embeddings
|
| 640 |
+
|
| 641 |
+
def set_output_embeddings(self, value):
|
| 642 |
+
self.input_embeddings.weight = value
|
| 643 |
+
self.input_embeddings.vocab_size = shape_list(value)[0]
|
| 644 |
+
|
| 645 |
+
def get_bias(self):
|
| 646 |
+
return {"bias": self.bias}
|
| 647 |
+
|
| 648 |
+
def set_bias(self, value):
|
| 649 |
+
self.bias = value["bias"]
|
| 650 |
+
self.config.vocab_size = shape_list(value["bias"])[0]
|
| 651 |
+
|
| 652 |
+
def call(self, hidden_states):
|
| 653 |
+
seq_length = shape_list(tensor=hidden_states)[1]
|
| 654 |
+
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.dim])
|
| 655 |
+
hidden_states = tf.matmul(a=hidden_states, b=self.input_embeddings.weight, transpose_b=True)
|
| 656 |
+
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
|
| 657 |
+
hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
|
| 658 |
+
|
| 659 |
+
return hidden_states
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
@add_start_docstrings(
|
| 663 |
+
"""DistilBert Model with a `masked language modeling` head on top.""",
|
| 664 |
+
DISTILBERT_START_DOCSTRING,
|
| 665 |
+
)
|
| 666 |
+
class TFDistilBertForMaskedLM(TFDistilBertPreTrainedModel, TFMaskedLanguageModelingLoss):
|
| 667 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 668 |
+
super().__init__(config, *inputs, **kwargs)
|
| 669 |
+
self.config = config
|
| 670 |
+
|
| 671 |
+
self.distilbert = TFDistilBertMainLayer(config, name="distilbert")
|
| 672 |
+
self.vocab_transform = keras.layers.Dense(
|
| 673 |
+
config.dim, kernel_initializer=get_initializer(config.initializer_range), name="vocab_transform"
|
| 674 |
+
)
|
| 675 |
+
self.act = get_tf_activation(config.activation)
|
| 676 |
+
self.vocab_layer_norm = keras.layers.LayerNormalization(epsilon=1e-12, name="vocab_layer_norm")
|
| 677 |
+
self.vocab_projector = TFDistilBertLMHead(config, self.distilbert.embeddings, name="vocab_projector")
|
| 678 |
+
|
| 679 |
+
def get_lm_head(self):
|
| 680 |
+
return self.vocab_projector
|
| 681 |
+
|
| 682 |
+
def get_prefix_bias_name(self):
|
| 683 |
+
warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
|
| 684 |
+
return self.name + "/" + self.vocab_projector.name
|
| 685 |
+
|
| 686 |
+
@unpack_inputs
|
| 687 |
+
@add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 688 |
+
@add_code_sample_docstrings(
|
| 689 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 690 |
+
output_type=TFMaskedLMOutput,
|
| 691 |
+
config_class=_CONFIG_FOR_DOC,
|
| 692 |
+
)
|
| 693 |
+
def call(
|
| 694 |
+
self,
|
| 695 |
+
input_ids: TFModelInputType | None = None,
|
| 696 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 697 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 698 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 699 |
+
output_attentions: bool | None = None,
|
| 700 |
+
output_hidden_states: bool | None = None,
|
| 701 |
+
return_dict: bool | None = None,
|
| 702 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 703 |
+
training: bool | None = False,
|
| 704 |
+
) -> TFMaskedLMOutput | tuple[tf.Tensor]:
|
| 705 |
+
r"""
|
| 706 |
+
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 707 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 708 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 709 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 710 |
+
"""
|
| 711 |
+
distilbert_output = self.distilbert(
|
| 712 |
+
input_ids=input_ids,
|
| 713 |
+
attention_mask=attention_mask,
|
| 714 |
+
head_mask=head_mask,
|
| 715 |
+
inputs_embeds=inputs_embeds,
|
| 716 |
+
output_attentions=output_attentions,
|
| 717 |
+
output_hidden_states=output_hidden_states,
|
| 718 |
+
return_dict=return_dict,
|
| 719 |
+
training=training,
|
| 720 |
+
)
|
| 721 |
+
hidden_states = distilbert_output[0] # (bs, seq_length, dim)
|
| 722 |
+
prediction_logits = self.vocab_transform(hidden_states) # (bs, seq_length, dim)
|
| 723 |
+
prediction_logits = self.act(prediction_logits) # (bs, seq_length, dim)
|
| 724 |
+
prediction_logits = self.vocab_layer_norm(prediction_logits) # (bs, seq_length, dim)
|
| 725 |
+
prediction_logits = self.vocab_projector(prediction_logits)
|
| 726 |
+
|
| 727 |
+
loss = None if labels is None else self.hf_compute_loss(labels, prediction_logits)
|
| 728 |
+
|
| 729 |
+
if not return_dict:
|
| 730 |
+
output = (prediction_logits,) + distilbert_output[1:]
|
| 731 |
+
return ((loss,) + output) if loss is not None else output
|
| 732 |
+
|
| 733 |
+
return TFMaskedLMOutput(
|
| 734 |
+
loss=loss,
|
| 735 |
+
logits=prediction_logits,
|
| 736 |
+
hidden_states=distilbert_output.hidden_states,
|
| 737 |
+
attentions=distilbert_output.attentions,
|
| 738 |
+
)
|
| 739 |
+
|
| 740 |
+
def build(self, input_shape=None):
|
| 741 |
+
if self.built:
|
| 742 |
+
return
|
| 743 |
+
self.built = True
|
| 744 |
+
if getattr(self, "distilbert", None) is not None:
|
| 745 |
+
with tf.name_scope(self.distilbert.name):
|
| 746 |
+
self.distilbert.build(None)
|
| 747 |
+
if getattr(self, "vocab_transform", None) is not None:
|
| 748 |
+
with tf.name_scope(self.vocab_transform.name):
|
| 749 |
+
self.vocab_transform.build([None, None, self.config.dim])
|
| 750 |
+
if getattr(self, "vocab_layer_norm", None) is not None:
|
| 751 |
+
with tf.name_scope(self.vocab_layer_norm.name):
|
| 752 |
+
self.vocab_layer_norm.build([None, None, self.config.dim])
|
| 753 |
+
if getattr(self, "vocab_projector", None) is not None:
|
| 754 |
+
with tf.name_scope(self.vocab_projector.name):
|
| 755 |
+
self.vocab_projector.build(None)
|
| 756 |
+
|
| 757 |
+
|
| 758 |
+
@add_start_docstrings(
|
| 759 |
+
"""
|
| 760 |
+
DistilBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
|
| 761 |
+
pooled output) e.g. for GLUE tasks.
|
| 762 |
+
""",
|
| 763 |
+
DISTILBERT_START_DOCSTRING,
|
| 764 |
+
)
|
| 765 |
+
class TFDistilBertForSequenceClassification(TFDistilBertPreTrainedModel, TFSequenceClassificationLoss):
|
| 766 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 767 |
+
super().__init__(config, *inputs, **kwargs)
|
| 768 |
+
self.num_labels = config.num_labels
|
| 769 |
+
|
| 770 |
+
self.distilbert = TFDistilBertMainLayer(config, name="distilbert")
|
| 771 |
+
self.pre_classifier = keras.layers.Dense(
|
| 772 |
+
config.dim,
|
| 773 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 774 |
+
activation="relu",
|
| 775 |
+
name="pre_classifier",
|
| 776 |
+
)
|
| 777 |
+
self.classifier = keras.layers.Dense(
|
| 778 |
+
config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
|
| 779 |
+
)
|
| 780 |
+
self.dropout = keras.layers.Dropout(config.seq_classif_dropout)
|
| 781 |
+
self.config = config
|
| 782 |
+
|
| 783 |
+
@unpack_inputs
|
| 784 |
+
@add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 785 |
+
@add_code_sample_docstrings(
|
| 786 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 787 |
+
output_type=TFSequenceClassifierOutput,
|
| 788 |
+
config_class=_CONFIG_FOR_DOC,
|
| 789 |
+
)
|
| 790 |
+
def call(
|
| 791 |
+
self,
|
| 792 |
+
input_ids: TFModelInputType | None = None,
|
| 793 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 794 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 795 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 796 |
+
output_attentions: bool | None = None,
|
| 797 |
+
output_hidden_states: bool | None = None,
|
| 798 |
+
return_dict: bool | None = None,
|
| 799 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 800 |
+
training: bool | None = False,
|
| 801 |
+
) -> TFSequenceClassifierOutput | tuple[tf.Tensor]:
|
| 802 |
+
r"""
|
| 803 |
+
labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 804 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 805 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 806 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 807 |
+
"""
|
| 808 |
+
distilbert_output = self.distilbert(
|
| 809 |
+
input_ids=input_ids,
|
| 810 |
+
attention_mask=attention_mask,
|
| 811 |
+
head_mask=head_mask,
|
| 812 |
+
inputs_embeds=inputs_embeds,
|
| 813 |
+
output_attentions=output_attentions,
|
| 814 |
+
output_hidden_states=output_hidden_states,
|
| 815 |
+
return_dict=return_dict,
|
| 816 |
+
training=training,
|
| 817 |
+
)
|
| 818 |
+
hidden_state = distilbert_output[0] # (bs, seq_len, dim)
|
| 819 |
+
pooled_output = hidden_state[:, 0] # (bs, dim)
|
| 820 |
+
pooled_output = self.pre_classifier(pooled_output) # (bs, dim)
|
| 821 |
+
pooled_output = self.dropout(pooled_output, training=training) # (bs, dim)
|
| 822 |
+
logits = self.classifier(pooled_output) # (bs, dim)
|
| 823 |
+
|
| 824 |
+
loss = None if labels is None else self.hf_compute_loss(labels, logits)
|
| 825 |
+
|
| 826 |
+
if not return_dict:
|
| 827 |
+
output = (logits,) + distilbert_output[1:]
|
| 828 |
+
return ((loss,) + output) if loss is not None else output
|
| 829 |
+
|
| 830 |
+
return TFSequenceClassifierOutput(
|
| 831 |
+
loss=loss,
|
| 832 |
+
logits=logits,
|
| 833 |
+
hidden_states=distilbert_output.hidden_states,
|
| 834 |
+
attentions=distilbert_output.attentions,
|
| 835 |
+
)
|
| 836 |
+
|
| 837 |
+
def build(self, input_shape=None):
|
| 838 |
+
if self.built:
|
| 839 |
+
return
|
| 840 |
+
self.built = True
|
| 841 |
+
if getattr(self, "distilbert", None) is not None:
|
| 842 |
+
with tf.name_scope(self.distilbert.name):
|
| 843 |
+
self.distilbert.build(None)
|
| 844 |
+
if getattr(self, "pre_classifier", None) is not None:
|
| 845 |
+
with tf.name_scope(self.pre_classifier.name):
|
| 846 |
+
self.pre_classifier.build([None, None, self.config.dim])
|
| 847 |
+
if getattr(self, "classifier", None) is not None:
|
| 848 |
+
with tf.name_scope(self.classifier.name):
|
| 849 |
+
self.classifier.build([None, None, self.config.dim])
|
| 850 |
+
|
| 851 |
+
|
| 852 |
+
@add_start_docstrings(
|
| 853 |
+
"""
|
| 854 |
+
DistilBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
|
| 855 |
+
for Named-Entity-Recognition (NER) tasks.
|
| 856 |
+
""",
|
| 857 |
+
DISTILBERT_START_DOCSTRING,
|
| 858 |
+
)
|
| 859 |
+
class TFDistilBertForTokenClassification(TFDistilBertPreTrainedModel, TFTokenClassificationLoss):
|
| 860 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 861 |
+
super().__init__(config, *inputs, **kwargs)
|
| 862 |
+
self.num_labels = config.num_labels
|
| 863 |
+
|
| 864 |
+
self.distilbert = TFDistilBertMainLayer(config, name="distilbert")
|
| 865 |
+
self.dropout = keras.layers.Dropout(config.dropout)
|
| 866 |
+
self.classifier = keras.layers.Dense(
|
| 867 |
+
config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
|
| 868 |
+
)
|
| 869 |
+
self.config = config
|
| 870 |
+
|
| 871 |
+
@unpack_inputs
|
| 872 |
+
@add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 873 |
+
@add_code_sample_docstrings(
|
| 874 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 875 |
+
output_type=TFTokenClassifierOutput,
|
| 876 |
+
config_class=_CONFIG_FOR_DOC,
|
| 877 |
+
)
|
| 878 |
+
def call(
|
| 879 |
+
self,
|
| 880 |
+
input_ids: TFModelInputType | None = None,
|
| 881 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 882 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 883 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 884 |
+
output_attentions: bool | None = None,
|
| 885 |
+
output_hidden_states: bool | None = None,
|
| 886 |
+
return_dict: bool | None = None,
|
| 887 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 888 |
+
training: bool | None = False,
|
| 889 |
+
) -> TFTokenClassifierOutput | tuple[tf.Tensor]:
|
| 890 |
+
r"""
|
| 891 |
+
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 892 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 893 |
+
"""
|
| 894 |
+
outputs = self.distilbert(
|
| 895 |
+
input_ids=input_ids,
|
| 896 |
+
attention_mask=attention_mask,
|
| 897 |
+
head_mask=head_mask,
|
| 898 |
+
inputs_embeds=inputs_embeds,
|
| 899 |
+
output_attentions=output_attentions,
|
| 900 |
+
output_hidden_states=output_hidden_states,
|
| 901 |
+
return_dict=return_dict,
|
| 902 |
+
training=training,
|
| 903 |
+
)
|
| 904 |
+
sequence_output = outputs[0]
|
| 905 |
+
sequence_output = self.dropout(sequence_output, training=training)
|
| 906 |
+
logits = self.classifier(sequence_output)
|
| 907 |
+
loss = None if labels is None else self.hf_compute_loss(labels, logits)
|
| 908 |
+
|
| 909 |
+
if not return_dict:
|
| 910 |
+
output = (logits,) + outputs[1:]
|
| 911 |
+
return ((loss,) + output) if loss is not None else output
|
| 912 |
+
|
| 913 |
+
return TFTokenClassifierOutput(
|
| 914 |
+
loss=loss,
|
| 915 |
+
logits=logits,
|
| 916 |
+
hidden_states=outputs.hidden_states,
|
| 917 |
+
attentions=outputs.attentions,
|
| 918 |
+
)
|
| 919 |
+
|
| 920 |
+
def build(self, input_shape=None):
|
| 921 |
+
if self.built:
|
| 922 |
+
return
|
| 923 |
+
self.built = True
|
| 924 |
+
if getattr(self, "distilbert", None) is not None:
|
| 925 |
+
with tf.name_scope(self.distilbert.name):
|
| 926 |
+
self.distilbert.build(None)
|
| 927 |
+
if getattr(self, "classifier", None) is not None:
|
| 928 |
+
with tf.name_scope(self.classifier.name):
|
| 929 |
+
self.classifier.build([None, None, self.config.hidden_size])
|
| 930 |
+
|
| 931 |
+
|
| 932 |
+
@add_start_docstrings(
|
| 933 |
+
"""
|
| 934 |
+
DistilBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
|
| 935 |
+
a softmax) e.g. for RocStories/SWAG tasks.
|
| 936 |
+
""",
|
| 937 |
+
DISTILBERT_START_DOCSTRING,
|
| 938 |
+
)
|
| 939 |
+
class TFDistilBertForMultipleChoice(TFDistilBertPreTrainedModel, TFMultipleChoiceLoss):
|
| 940 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 941 |
+
super().__init__(config, *inputs, **kwargs)
|
| 942 |
+
|
| 943 |
+
self.distilbert = TFDistilBertMainLayer(config, name="distilbert")
|
| 944 |
+
self.dropout = keras.layers.Dropout(config.seq_classif_dropout)
|
| 945 |
+
self.pre_classifier = keras.layers.Dense(
|
| 946 |
+
config.dim,
|
| 947 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 948 |
+
activation="relu",
|
| 949 |
+
name="pre_classifier",
|
| 950 |
+
)
|
| 951 |
+
self.classifier = keras.layers.Dense(
|
| 952 |
+
1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
|
| 953 |
+
)
|
| 954 |
+
self.config = config
|
| 955 |
+
|
| 956 |
+
@unpack_inputs
|
| 957 |
+
@add_start_docstrings_to_model_forward(
|
| 958 |
+
DISTILBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
|
| 959 |
+
)
|
| 960 |
+
@add_code_sample_docstrings(
|
| 961 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 962 |
+
output_type=TFMultipleChoiceModelOutput,
|
| 963 |
+
config_class=_CONFIG_FOR_DOC,
|
| 964 |
+
)
|
| 965 |
+
def call(
|
| 966 |
+
self,
|
| 967 |
+
input_ids: TFModelInputType | None = None,
|
| 968 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 969 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 970 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 971 |
+
output_attentions: bool | None = None,
|
| 972 |
+
output_hidden_states: bool | None = None,
|
| 973 |
+
return_dict: bool | None = None,
|
| 974 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 975 |
+
training: bool | None = False,
|
| 976 |
+
) -> TFMultipleChoiceModelOutput | tuple[tf.Tensor]:
|
| 977 |
+
r"""
|
| 978 |
+
labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 979 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
|
| 980 |
+
where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
|
| 981 |
+
"""
|
| 982 |
+
if input_ids is not None:
|
| 983 |
+
num_choices = shape_list(input_ids)[1]
|
| 984 |
+
seq_length = shape_list(input_ids)[2]
|
| 985 |
+
else:
|
| 986 |
+
num_choices = shape_list(inputs_embeds)[1]
|
| 987 |
+
seq_length = shape_list(inputs_embeds)[2]
|
| 988 |
+
|
| 989 |
+
flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
|
| 990 |
+
flat_attention_mask = tf.reshape(attention_mask, (-1, seq_length)) if attention_mask is not None else None
|
| 991 |
+
flat_inputs_embeds = (
|
| 992 |
+
tf.reshape(inputs_embeds, (-1, seq_length, shape_list(inputs_embeds)[3]))
|
| 993 |
+
if inputs_embeds is not None
|
| 994 |
+
else None
|
| 995 |
+
)
|
| 996 |
+
distilbert_output = self.distilbert(
|
| 997 |
+
flat_input_ids,
|
| 998 |
+
flat_attention_mask,
|
| 999 |
+
head_mask,
|
| 1000 |
+
flat_inputs_embeds,
|
| 1001 |
+
output_attentions,
|
| 1002 |
+
output_hidden_states,
|
| 1003 |
+
return_dict=return_dict,
|
| 1004 |
+
training=training,
|
| 1005 |
+
)
|
| 1006 |
+
hidden_state = distilbert_output[0] # (bs, seq_len, dim)
|
| 1007 |
+
pooled_output = hidden_state[:, 0] # (bs, dim)
|
| 1008 |
+
pooled_output = self.pre_classifier(pooled_output) # (bs, dim)
|
| 1009 |
+
pooled_output = self.dropout(pooled_output, training=training) # (bs, dim)
|
| 1010 |
+
logits = self.classifier(pooled_output)
|
| 1011 |
+
reshaped_logits = tf.reshape(logits, (-1, num_choices))
|
| 1012 |
+
|
| 1013 |
+
loss = None if labels is None else self.hf_compute_loss(labels, reshaped_logits)
|
| 1014 |
+
|
| 1015 |
+
if not return_dict:
|
| 1016 |
+
output = (reshaped_logits,) + distilbert_output[1:]
|
| 1017 |
+
return ((loss,) + output) if loss is not None else output
|
| 1018 |
+
|
| 1019 |
+
return TFMultipleChoiceModelOutput(
|
| 1020 |
+
loss=loss,
|
| 1021 |
+
logits=reshaped_logits,
|
| 1022 |
+
hidden_states=distilbert_output.hidden_states,
|
| 1023 |
+
attentions=distilbert_output.attentions,
|
| 1024 |
+
)
|
| 1025 |
+
|
| 1026 |
+
def build(self, input_shape=None):
|
| 1027 |
+
if self.built:
|
| 1028 |
+
return
|
| 1029 |
+
self.built = True
|
| 1030 |
+
if getattr(self, "distilbert", None) is not None:
|
| 1031 |
+
with tf.name_scope(self.distilbert.name):
|
| 1032 |
+
self.distilbert.build(None)
|
| 1033 |
+
if getattr(self, "pre_classifier", None) is not None:
|
| 1034 |
+
with tf.name_scope(self.pre_classifier.name):
|
| 1035 |
+
self.pre_classifier.build([None, None, self.config.dim])
|
| 1036 |
+
if getattr(self, "classifier", None) is not None:
|
| 1037 |
+
with tf.name_scope(self.classifier.name):
|
| 1038 |
+
self.classifier.build([None, None, self.config.dim])
|
| 1039 |
+
|
| 1040 |
+
|
| 1041 |
+
@add_start_docstrings(
|
| 1042 |
+
"""
|
| 1043 |
+
DistilBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
|
| 1044 |
+
linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1045 |
+
""",
|
| 1046 |
+
DISTILBERT_START_DOCSTRING,
|
| 1047 |
+
)
|
| 1048 |
+
class TFDistilBertForQuestionAnswering(TFDistilBertPreTrainedModel, TFQuestionAnsweringLoss):
|
| 1049 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 1050 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1051 |
+
|
| 1052 |
+
self.distilbert = TFDistilBertMainLayer(config, name="distilbert")
|
| 1053 |
+
self.qa_outputs = keras.layers.Dense(
|
| 1054 |
+
config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
|
| 1055 |
+
)
|
| 1056 |
+
assert config.num_labels == 2, f"Incorrect number of labels {config.num_labels} instead of 2"
|
| 1057 |
+
self.dropout = keras.layers.Dropout(config.qa_dropout)
|
| 1058 |
+
self.config = config
|
| 1059 |
+
|
| 1060 |
+
@unpack_inputs
|
| 1061 |
+
@add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1062 |
+
@add_code_sample_docstrings(
|
| 1063 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1064 |
+
output_type=TFQuestionAnsweringModelOutput,
|
| 1065 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1066 |
+
)
|
| 1067 |
+
def call(
|
| 1068 |
+
self,
|
| 1069 |
+
input_ids: TFModelInputType | None = None,
|
| 1070 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1071 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1072 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1073 |
+
output_attentions: bool | None = None,
|
| 1074 |
+
output_hidden_states: bool | None = None,
|
| 1075 |
+
return_dict: bool | None = None,
|
| 1076 |
+
start_positions: np.ndarray | tf.Tensor | None = None,
|
| 1077 |
+
end_positions: np.ndarray | tf.Tensor | None = None,
|
| 1078 |
+
training: bool | None = False,
|
| 1079 |
+
) -> TFQuestionAnsweringModelOutput | tuple[tf.Tensor]:
|
| 1080 |
+
r"""
|
| 1081 |
+
start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1082 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1083 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1084 |
+
are not taken into account for computing the loss.
|
| 1085 |
+
end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1086 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1087 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1088 |
+
are not taken into account for computing the loss.
|
| 1089 |
+
"""
|
| 1090 |
+
distilbert_output = self.distilbert(
|
| 1091 |
+
input_ids=input_ids,
|
| 1092 |
+
attention_mask=attention_mask,
|
| 1093 |
+
head_mask=head_mask,
|
| 1094 |
+
inputs_embeds=inputs_embeds,
|
| 1095 |
+
output_attentions=output_attentions,
|
| 1096 |
+
output_hidden_states=output_hidden_states,
|
| 1097 |
+
return_dict=return_dict,
|
| 1098 |
+
training=training,
|
| 1099 |
+
)
|
| 1100 |
+
hidden_states = distilbert_output[0] # (bs, max_query_len, dim)
|
| 1101 |
+
hidden_states = self.dropout(hidden_states, training=training) # (bs, max_query_len, dim)
|
| 1102 |
+
logits = self.qa_outputs(hidden_states) # (bs, max_query_len, 2)
|
| 1103 |
+
start_logits, end_logits = tf.split(logits, 2, axis=-1)
|
| 1104 |
+
start_logits = tf.squeeze(start_logits, axis=-1)
|
| 1105 |
+
end_logits = tf.squeeze(end_logits, axis=-1)
|
| 1106 |
+
|
| 1107 |
+
loss = None
|
| 1108 |
+
if start_positions is not None and end_positions is not None:
|
| 1109 |
+
labels = {"start_position": start_positions}
|
| 1110 |
+
labels["end_position"] = end_positions
|
| 1111 |
+
loss = self.hf_compute_loss(labels, (start_logits, end_logits))
|
| 1112 |
+
|
| 1113 |
+
if not return_dict:
|
| 1114 |
+
output = (start_logits, end_logits) + distilbert_output[1:]
|
| 1115 |
+
return ((loss,) + output) if loss is not None else output
|
| 1116 |
+
|
| 1117 |
+
return TFQuestionAnsweringModelOutput(
|
| 1118 |
+
loss=loss,
|
| 1119 |
+
start_logits=start_logits,
|
| 1120 |
+
end_logits=end_logits,
|
| 1121 |
+
hidden_states=distilbert_output.hidden_states,
|
| 1122 |
+
attentions=distilbert_output.attentions,
|
| 1123 |
+
)
|
| 1124 |
+
|
| 1125 |
+
def build(self, input_shape=None):
|
| 1126 |
+
if self.built:
|
| 1127 |
+
return
|
| 1128 |
+
self.built = True
|
| 1129 |
+
if getattr(self, "distilbert", None) is not None:
|
| 1130 |
+
with tf.name_scope(self.distilbert.name):
|
| 1131 |
+
self.distilbert.build(None)
|
| 1132 |
+
if getattr(self, "qa_outputs", None) is not None:
|
| 1133 |
+
with tf.name_scope(self.qa_outputs.name):
|
| 1134 |
+
self.qa_outputs.build([None, None, self.config.dim])
|
| 1135 |
+
|
| 1136 |
+
|
| 1137 |
+
__all__ = [
|
| 1138 |
+
"TFDistilBertForMaskedLM",
|
| 1139 |
+
"TFDistilBertForMultipleChoice",
|
| 1140 |
+
"TFDistilBertForQuestionAnswering",
|
| 1141 |
+
"TFDistilBertForSequenceClassification",
|
| 1142 |
+
"TFDistilBertForTokenClassification",
|
| 1143 |
+
"TFDistilBertMainLayer",
|
| 1144 |
+
"TFDistilBertModel",
|
| 1145 |
+
"TFDistilBertPreTrainedModel",
|
| 1146 |
+
]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/distilbert/tokenization_distilbert.py
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization classes for DistilBERT."""
|
| 16 |
+
|
| 17 |
+
import collections
|
| 18 |
+
import os
|
| 19 |
+
import unicodedata
|
| 20 |
+
from typing import Optional
|
| 21 |
+
|
| 22 |
+
from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
|
| 23 |
+
from ...utils import logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Copied from transformers.models.bert.tokenization_bert.load_vocab
|
| 32 |
+
def load_vocab(vocab_file):
|
| 33 |
+
"""Loads a vocabulary file into a dictionary."""
|
| 34 |
+
vocab = collections.OrderedDict()
|
| 35 |
+
with open(vocab_file, "r", encoding="utf-8") as reader:
|
| 36 |
+
tokens = reader.readlines()
|
| 37 |
+
for index, token in enumerate(tokens):
|
| 38 |
+
token = token.rstrip("\n")
|
| 39 |
+
vocab[token] = index
|
| 40 |
+
return vocab
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# Copied from transformers.models.bert.tokenization_bert.whitespace_tokenize
|
| 44 |
+
def whitespace_tokenize(text):
|
| 45 |
+
"""Runs basic whitespace cleaning and splitting on a piece of text."""
|
| 46 |
+
text = text.strip()
|
| 47 |
+
if not text:
|
| 48 |
+
return []
|
| 49 |
+
tokens = text.split()
|
| 50 |
+
return tokens
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class DistilBertTokenizer(PreTrainedTokenizer):
|
| 54 |
+
r"""
|
| 55 |
+
Construct a DistilBERT tokenizer. Based on WordPiece.
|
| 56 |
+
|
| 57 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 58 |
+
this superclass for more information regarding those methods.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
vocab_file (`str`):
|
| 62 |
+
File containing the vocabulary.
|
| 63 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 64 |
+
Whether or not to lowercase the input when tokenizing.
|
| 65 |
+
do_basic_tokenize (`bool`, *optional*, defaults to `True`):
|
| 66 |
+
Whether or not to do basic tokenization before WordPiece.
|
| 67 |
+
never_split (`Iterable`, *optional*):
|
| 68 |
+
Collection of tokens which will never be split during tokenization. Only has an effect when
|
| 69 |
+
`do_basic_tokenize=True`
|
| 70 |
+
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
|
| 71 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 72 |
+
token instead.
|
| 73 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 74 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 75 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 76 |
+
token of a sequence built with special tokens.
|
| 77 |
+
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
|
| 78 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 79 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 80 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 81 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 82 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 83 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 84 |
+
modeling. This is the token which the model will try to predict.
|
| 85 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 86 |
+
Whether or not to tokenize Chinese characters.
|
| 87 |
+
|
| 88 |
+
This should likely be deactivated for Japanese (see this
|
| 89 |
+
[issue](https://github.com/huggingface/transformers/issues/328)).
|
| 90 |
+
strip_accents (`bool`, *optional*):
|
| 91 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 92 |
+
value for `lowercase` (as in the original BERT).
|
| 93 |
+
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
|
| 94 |
+
Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
|
| 95 |
+
extra spaces.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 99 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 100 |
+
|
| 101 |
+
def __init__(
|
| 102 |
+
self,
|
| 103 |
+
vocab_file,
|
| 104 |
+
do_lower_case=True,
|
| 105 |
+
do_basic_tokenize=True,
|
| 106 |
+
never_split=None,
|
| 107 |
+
unk_token="[UNK]",
|
| 108 |
+
sep_token="[SEP]",
|
| 109 |
+
pad_token="[PAD]",
|
| 110 |
+
cls_token="[CLS]",
|
| 111 |
+
mask_token="[MASK]",
|
| 112 |
+
tokenize_chinese_chars=True,
|
| 113 |
+
strip_accents=None,
|
| 114 |
+
clean_up_tokenization_spaces=True,
|
| 115 |
+
**kwargs,
|
| 116 |
+
):
|
| 117 |
+
if not os.path.isfile(vocab_file):
|
| 118 |
+
raise ValueError(
|
| 119 |
+
f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
|
| 120 |
+
" model use `tokenizer = DistilBertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
|
| 121 |
+
)
|
| 122 |
+
self.vocab = load_vocab(vocab_file)
|
| 123 |
+
self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
|
| 124 |
+
self.do_basic_tokenize = do_basic_tokenize
|
| 125 |
+
if do_basic_tokenize:
|
| 126 |
+
self.basic_tokenizer = BasicTokenizer(
|
| 127 |
+
do_lower_case=do_lower_case,
|
| 128 |
+
never_split=never_split,
|
| 129 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 130 |
+
strip_accents=strip_accents,
|
| 131 |
+
)
|
| 132 |
+
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
|
| 133 |
+
|
| 134 |
+
super().__init__(
|
| 135 |
+
do_lower_case=do_lower_case,
|
| 136 |
+
do_basic_tokenize=do_basic_tokenize,
|
| 137 |
+
never_split=never_split,
|
| 138 |
+
unk_token=unk_token,
|
| 139 |
+
sep_token=sep_token,
|
| 140 |
+
pad_token=pad_token,
|
| 141 |
+
cls_token=cls_token,
|
| 142 |
+
mask_token=mask_token,
|
| 143 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 144 |
+
strip_accents=strip_accents,
|
| 145 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 146 |
+
**kwargs,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
@property
|
| 150 |
+
# Copied from transformers.models.bert.tokenization_bert.BertTokenizer.do_lower_case
|
| 151 |
+
def do_lower_case(self):
|
| 152 |
+
return self.basic_tokenizer.do_lower_case
|
| 153 |
+
|
| 154 |
+
@property
|
| 155 |
+
# Copied from transformers.models.bert.tokenization_bert.BertTokenizer.vocab_size
|
| 156 |
+
def vocab_size(self):
|
| 157 |
+
return len(self.vocab)
|
| 158 |
+
|
| 159 |
+
# Copied from transformers.models.bert.tokenization_bert.BertTokenizer.get_vocab
|
| 160 |
+
def get_vocab(self):
|
| 161 |
+
return dict(self.vocab, **self.added_tokens_encoder)
|
| 162 |
+
|
| 163 |
+
# Copied from transformers.models.bert.tokenization_bert.BertTokenizer._tokenize
|
| 164 |
+
def _tokenize(self, text, split_special_tokens=False):
|
| 165 |
+
split_tokens = []
|
| 166 |
+
if self.do_basic_tokenize:
|
| 167 |
+
for token in self.basic_tokenizer.tokenize(
|
| 168 |
+
text, never_split=self.all_special_tokens if not split_special_tokens else None
|
| 169 |
+
):
|
| 170 |
+
# If the token is part of the never_split set
|
| 171 |
+
if token in self.basic_tokenizer.never_split:
|
| 172 |
+
split_tokens.append(token)
|
| 173 |
+
else:
|
| 174 |
+
split_tokens += self.wordpiece_tokenizer.tokenize(token)
|
| 175 |
+
else:
|
| 176 |
+
split_tokens = self.wordpiece_tokenizer.tokenize(text)
|
| 177 |
+
return split_tokens
|
| 178 |
+
|
| 179 |
+
# Copied from transformers.models.bert.tokenization_bert.BertTokenizer._convert_token_to_id
|
| 180 |
+
def _convert_token_to_id(self, token):
|
| 181 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 182 |
+
return self.vocab.get(token, self.vocab.get(self.unk_token))
|
| 183 |
+
|
| 184 |
+
# Copied from transformers.models.bert.tokenization_bert.BertTokenizer._convert_id_to_token
|
| 185 |
+
def _convert_id_to_token(self, index):
|
| 186 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 187 |
+
return self.ids_to_tokens.get(index, self.unk_token)
|
| 188 |
+
|
| 189 |
+
# Copied from transformers.models.bert.tokenization_bert.BertTokenizer.convert_tokens_to_string
|
| 190 |
+
def convert_tokens_to_string(self, tokens):
|
| 191 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 192 |
+
out_string = " ".join(tokens).replace(" ##", "").strip()
|
| 193 |
+
return out_string
|
| 194 |
+
|
| 195 |
+
# Copied from transformers.models.bert.tokenization_bert.BertTokenizer.build_inputs_with_special_tokens
|
| 196 |
+
def build_inputs_with_special_tokens(
|
| 197 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
|
| 198 |
+
) -> list[int]:
|
| 199 |
+
"""
|
| 200 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 201 |
+
adding special tokens. A BERT sequence has the following format:
|
| 202 |
+
|
| 203 |
+
- single sequence: `[CLS] X [SEP]`
|
| 204 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 205 |
+
|
| 206 |
+
Args:
|
| 207 |
+
token_ids_0 (`List[int]`):
|
| 208 |
+
List of IDs to which the special tokens will be added.
|
| 209 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 210 |
+
Optional second list of IDs for sequence pairs.
|
| 211 |
+
|
| 212 |
+
Returns:
|
| 213 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 214 |
+
"""
|
| 215 |
+
if token_ids_1 is None:
|
| 216 |
+
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
| 217 |
+
cls = [self.cls_token_id]
|
| 218 |
+
sep = [self.sep_token_id]
|
| 219 |
+
return cls + token_ids_0 + sep + token_ids_1 + sep
|
| 220 |
+
|
| 221 |
+
# Copied from transformers.models.bert.tokenization_bert.BertTokenizer.get_special_tokens_mask
|
| 222 |
+
def get_special_tokens_mask(
|
| 223 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
|
| 224 |
+
) -> list[int]:
|
| 225 |
+
"""
|
| 226 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 227 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 228 |
+
|
| 229 |
+
Args:
|
| 230 |
+
token_ids_0 (`List[int]`):
|
| 231 |
+
List of IDs.
|
| 232 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 233 |
+
Optional second list of IDs for sequence pairs.
|
| 234 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 235 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 236 |
+
|
| 237 |
+
Returns:
|
| 238 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 239 |
+
"""
|
| 240 |
+
|
| 241 |
+
if already_has_special_tokens:
|
| 242 |
+
return super().get_special_tokens_mask(
|
| 243 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
if token_ids_1 is not None:
|
| 247 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
|
| 248 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
| 249 |
+
|
| 250 |
+
# Copied from transformers.models.bert.tokenization_bert.BertTokenizer.save_vocabulary
|
| 251 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 252 |
+
index = 0
|
| 253 |
+
if os.path.isdir(save_directory):
|
| 254 |
+
vocab_file = os.path.join(
|
| 255 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 256 |
+
)
|
| 257 |
+
else:
|
| 258 |
+
vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
|
| 259 |
+
with open(vocab_file, "w", encoding="utf-8") as writer:
|
| 260 |
+
for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
|
| 261 |
+
if index != token_index:
|
| 262 |
+
logger.warning(
|
| 263 |
+
f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
|
| 264 |
+
" Please check that the vocabulary is not corrupted!"
|
| 265 |
+
)
|
| 266 |
+
index = token_index
|
| 267 |
+
writer.write(token + "\n")
|
| 268 |
+
index += 1
|
| 269 |
+
return (vocab_file,)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
# Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
|
| 273 |
+
class BasicTokenizer:
|
| 274 |
+
"""
|
| 275 |
+
Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
|
| 276 |
+
|
| 277 |
+
Args:
|
| 278 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 279 |
+
Whether or not to lowercase the input when tokenizing.
|
| 280 |
+
never_split (`Iterable`, *optional*):
|
| 281 |
+
Collection of tokens which will never be split during tokenization. Only has an effect when
|
| 282 |
+
`do_basic_tokenize=True`
|
| 283 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 284 |
+
Whether or not to tokenize Chinese characters.
|
| 285 |
+
|
| 286 |
+
This should likely be deactivated for Japanese (see this
|
| 287 |
+
[issue](https://github.com/huggingface/transformers/issues/328)).
|
| 288 |
+
strip_accents (`bool`, *optional*):
|
| 289 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 290 |
+
value for `lowercase` (as in the original BERT).
|
| 291 |
+
do_split_on_punc (`bool`, *optional*, defaults to `True`):
|
| 292 |
+
In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
|
| 293 |
+
the full context of the words, such as contractions.
|
| 294 |
+
"""
|
| 295 |
+
|
| 296 |
+
def __init__(
|
| 297 |
+
self,
|
| 298 |
+
do_lower_case=True,
|
| 299 |
+
never_split=None,
|
| 300 |
+
tokenize_chinese_chars=True,
|
| 301 |
+
strip_accents=None,
|
| 302 |
+
do_split_on_punc=True,
|
| 303 |
+
):
|
| 304 |
+
if never_split is None:
|
| 305 |
+
never_split = []
|
| 306 |
+
self.do_lower_case = do_lower_case
|
| 307 |
+
self.never_split = set(never_split)
|
| 308 |
+
self.tokenize_chinese_chars = tokenize_chinese_chars
|
| 309 |
+
self.strip_accents = strip_accents
|
| 310 |
+
self.do_split_on_punc = do_split_on_punc
|
| 311 |
+
|
| 312 |
+
def tokenize(self, text, never_split=None):
|
| 313 |
+
"""
|
| 314 |
+
Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
|
| 315 |
+
|
| 316 |
+
Args:
|
| 317 |
+
never_split (`List[str]`, *optional*)
|
| 318 |
+
Kept for backward compatibility purposes. Now implemented directly at the base class level (see
|
| 319 |
+
[`PreTrainedTokenizer.tokenize`]) List of token not to split.
|
| 320 |
+
"""
|
| 321 |
+
# union() returns a new set by concatenating the two sets.
|
| 322 |
+
never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
|
| 323 |
+
text = self._clean_text(text)
|
| 324 |
+
|
| 325 |
+
# This was added on November 1st, 2018 for the multilingual and Chinese
|
| 326 |
+
# models. This is also applied to the English models now, but it doesn't
|
| 327 |
+
# matter since the English models were not trained on any Chinese data
|
| 328 |
+
# and generally don't have any Chinese data in them (there are Chinese
|
| 329 |
+
# characters in the vocabulary because Wikipedia does have some Chinese
|
| 330 |
+
# words in the English Wikipedia.).
|
| 331 |
+
if self.tokenize_chinese_chars:
|
| 332 |
+
text = self._tokenize_chinese_chars(text)
|
| 333 |
+
# prevents treating the same character with different unicode codepoints as different characters
|
| 334 |
+
unicode_normalized_text = unicodedata.normalize("NFC", text)
|
| 335 |
+
orig_tokens = whitespace_tokenize(unicode_normalized_text)
|
| 336 |
+
split_tokens = []
|
| 337 |
+
for token in orig_tokens:
|
| 338 |
+
if token not in never_split:
|
| 339 |
+
if self.do_lower_case:
|
| 340 |
+
token = token.lower()
|
| 341 |
+
if self.strip_accents is not False:
|
| 342 |
+
token = self._run_strip_accents(token)
|
| 343 |
+
elif self.strip_accents:
|
| 344 |
+
token = self._run_strip_accents(token)
|
| 345 |
+
split_tokens.extend(self._run_split_on_punc(token, never_split))
|
| 346 |
+
|
| 347 |
+
output_tokens = whitespace_tokenize(" ".join(split_tokens))
|
| 348 |
+
return output_tokens
|
| 349 |
+
|
| 350 |
+
def _run_strip_accents(self, text):
|
| 351 |
+
"""Strips accents from a piece of text."""
|
| 352 |
+
text = unicodedata.normalize("NFD", text)
|
| 353 |
+
output = []
|
| 354 |
+
for char in text:
|
| 355 |
+
cat = unicodedata.category(char)
|
| 356 |
+
if cat == "Mn":
|
| 357 |
+
continue
|
| 358 |
+
output.append(char)
|
| 359 |
+
return "".join(output)
|
| 360 |
+
|
| 361 |
+
def _run_split_on_punc(self, text, never_split=None):
|
| 362 |
+
"""Splits punctuation on a piece of text."""
|
| 363 |
+
if not self.do_split_on_punc or (never_split is not None and text in never_split):
|
| 364 |
+
return [text]
|
| 365 |
+
chars = list(text)
|
| 366 |
+
i = 0
|
| 367 |
+
start_new_word = True
|
| 368 |
+
output = []
|
| 369 |
+
while i < len(chars):
|
| 370 |
+
char = chars[i]
|
| 371 |
+
if _is_punctuation(char):
|
| 372 |
+
output.append([char])
|
| 373 |
+
start_new_word = True
|
| 374 |
+
else:
|
| 375 |
+
if start_new_word:
|
| 376 |
+
output.append([])
|
| 377 |
+
start_new_word = False
|
| 378 |
+
output[-1].append(char)
|
| 379 |
+
i += 1
|
| 380 |
+
|
| 381 |
+
return ["".join(x) for x in output]
|
| 382 |
+
|
| 383 |
+
def _tokenize_chinese_chars(self, text):
|
| 384 |
+
"""Adds whitespace around any CJK character."""
|
| 385 |
+
output = []
|
| 386 |
+
for char in text:
|
| 387 |
+
cp = ord(char)
|
| 388 |
+
if self._is_chinese_char(cp):
|
| 389 |
+
output.append(" ")
|
| 390 |
+
output.append(char)
|
| 391 |
+
output.append(" ")
|
| 392 |
+
else:
|
| 393 |
+
output.append(char)
|
| 394 |
+
return "".join(output)
|
| 395 |
+
|
| 396 |
+
def _is_chinese_char(self, cp):
|
| 397 |
+
"""Checks whether CP is the codepoint of a CJK character."""
|
| 398 |
+
# This defines a "chinese character" as anything in the CJK Unicode block:
|
| 399 |
+
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
|
| 400 |
+
#
|
| 401 |
+
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
|
| 402 |
+
# despite its name. The modern Korean Hangul alphabet is a different block,
|
| 403 |
+
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
|
| 404 |
+
# space-separated words, so they are not treated specially and handled
|
| 405 |
+
# like the all of the other languages.
|
| 406 |
+
if (
|
| 407 |
+
(cp >= 0x4E00 and cp <= 0x9FFF)
|
| 408 |
+
or (cp >= 0x3400 and cp <= 0x4DBF)
|
| 409 |
+
or (cp >= 0x20000 and cp <= 0x2A6DF)
|
| 410 |
+
or (cp >= 0x2A700 and cp <= 0x2B73F)
|
| 411 |
+
or (cp >= 0x2B740 and cp <= 0x2B81F)
|
| 412 |
+
or (cp >= 0x2B820 and cp <= 0x2CEAF)
|
| 413 |
+
or (cp >= 0xF900 and cp <= 0xFAFF)
|
| 414 |
+
or (cp >= 0x2F800 and cp <= 0x2FA1F)
|
| 415 |
+
):
|
| 416 |
+
return True
|
| 417 |
+
|
| 418 |
+
return False
|
| 419 |
+
|
| 420 |
+
def _clean_text(self, text):
|
| 421 |
+
"""Performs invalid character removal and whitespace cleanup on text."""
|
| 422 |
+
output = []
|
| 423 |
+
for char in text:
|
| 424 |
+
cp = ord(char)
|
| 425 |
+
if cp == 0 or cp == 0xFFFD or _is_control(char):
|
| 426 |
+
continue
|
| 427 |
+
if _is_whitespace(char):
|
| 428 |
+
output.append(" ")
|
| 429 |
+
else:
|
| 430 |
+
output.append(char)
|
| 431 |
+
return "".join(output)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
# Copied from transformers.models.bert.tokenization_bert.WordpieceTokenizer
|
| 435 |
+
class WordpieceTokenizer:
|
| 436 |
+
"""Runs WordPiece tokenization."""
|
| 437 |
+
|
| 438 |
+
def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
|
| 439 |
+
self.vocab = vocab
|
| 440 |
+
self.unk_token = unk_token
|
| 441 |
+
self.max_input_chars_per_word = max_input_chars_per_word
|
| 442 |
+
|
| 443 |
+
def tokenize(self, text):
|
| 444 |
+
"""
|
| 445 |
+
Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
|
| 446 |
+
tokenization using the given vocabulary.
|
| 447 |
+
|
| 448 |
+
For example, `input = "unaffable"` will return as output `["un", "##aff", "##able"]`.
|
| 449 |
+
|
| 450 |
+
Args:
|
| 451 |
+
text: A single token or whitespace separated tokens. This should have
|
| 452 |
+
already been passed through *BasicTokenizer*.
|
| 453 |
+
|
| 454 |
+
Returns:
|
| 455 |
+
A list of wordpiece tokens.
|
| 456 |
+
"""
|
| 457 |
+
|
| 458 |
+
output_tokens = []
|
| 459 |
+
for token in whitespace_tokenize(text):
|
| 460 |
+
chars = list(token)
|
| 461 |
+
if len(chars) > self.max_input_chars_per_word:
|
| 462 |
+
output_tokens.append(self.unk_token)
|
| 463 |
+
continue
|
| 464 |
+
|
| 465 |
+
is_bad = False
|
| 466 |
+
start = 0
|
| 467 |
+
sub_tokens = []
|
| 468 |
+
while start < len(chars):
|
| 469 |
+
end = len(chars)
|
| 470 |
+
cur_substr = None
|
| 471 |
+
while start < end:
|
| 472 |
+
substr = "".join(chars[start:end])
|
| 473 |
+
if start > 0:
|
| 474 |
+
substr = "##" + substr
|
| 475 |
+
if substr in self.vocab:
|
| 476 |
+
cur_substr = substr
|
| 477 |
+
break
|
| 478 |
+
end -= 1
|
| 479 |
+
if cur_substr is None:
|
| 480 |
+
is_bad = True
|
| 481 |
+
break
|
| 482 |
+
sub_tokens.append(cur_substr)
|
| 483 |
+
start = end
|
| 484 |
+
|
| 485 |
+
if is_bad:
|
| 486 |
+
output_tokens.append(self.unk_token)
|
| 487 |
+
else:
|
| 488 |
+
output_tokens.extend(sub_tokens)
|
| 489 |
+
return output_tokens
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
__all__ = ["DistilBertTokenizer"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/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
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization classes for DistilBERT."""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
from typing import Optional
|
| 19 |
+
|
| 20 |
+
from tokenizers import normalizers
|
| 21 |
+
|
| 22 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
| 23 |
+
from ...utils import logging
|
| 24 |
+
from .tokenization_distilbert import DistilBertTokenizer
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class DistilBertTokenizerFast(PreTrainedTokenizerFast):
|
| 33 |
+
r"""
|
| 34 |
+
Construct a "fast" DistilBERT tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
|
| 35 |
+
|
| 36 |
+
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
|
| 37 |
+
refer to this superclass for more information regarding those methods.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
vocab_file (`str`):
|
| 41 |
+
File containing the vocabulary.
|
| 42 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 43 |
+
Whether or not to lowercase the input when tokenizing.
|
| 44 |
+
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
|
| 45 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 46 |
+
token instead.
|
| 47 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 48 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 49 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 50 |
+
token of a sequence built with special tokens.
|
| 51 |
+
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
|
| 52 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 53 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 54 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 55 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 56 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 57 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 58 |
+
modeling. This is the token which the model will try to predict.
|
| 59 |
+
clean_text (`bool`, *optional*, defaults to `True`):
|
| 60 |
+
Whether or not to clean the text before tokenization by removing any control characters and replacing all
|
| 61 |
+
whitespaces by the classic one.
|
| 62 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 63 |
+
Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
|
| 64 |
+
issue](https://github.com/huggingface/transformers/issues/328)).
|
| 65 |
+
strip_accents (`bool`, *optional*):
|
| 66 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 67 |
+
value for `lowercase` (as in the original BERT).
|
| 68 |
+
wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
|
| 69 |
+
The prefix for subwords.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 73 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 74 |
+
slow_tokenizer_class = DistilBertTokenizer
|
| 75 |
+
|
| 76 |
+
def __init__(
|
| 77 |
+
self,
|
| 78 |
+
vocab_file=None,
|
| 79 |
+
tokenizer_file=None,
|
| 80 |
+
do_lower_case=True,
|
| 81 |
+
unk_token="[UNK]",
|
| 82 |
+
sep_token="[SEP]",
|
| 83 |
+
pad_token="[PAD]",
|
| 84 |
+
cls_token="[CLS]",
|
| 85 |
+
mask_token="[MASK]",
|
| 86 |
+
tokenize_chinese_chars=True,
|
| 87 |
+
strip_accents=None,
|
| 88 |
+
**kwargs,
|
| 89 |
+
):
|
| 90 |
+
super().__init__(
|
| 91 |
+
vocab_file,
|
| 92 |
+
tokenizer_file=tokenizer_file,
|
| 93 |
+
do_lower_case=do_lower_case,
|
| 94 |
+
unk_token=unk_token,
|
| 95 |
+
sep_token=sep_token,
|
| 96 |
+
pad_token=pad_token,
|
| 97 |
+
cls_token=cls_token,
|
| 98 |
+
mask_token=mask_token,
|
| 99 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 100 |
+
strip_accents=strip_accents,
|
| 101 |
+
**kwargs,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
|
| 105 |
+
if (
|
| 106 |
+
normalizer_state.get("lowercase", do_lower_case) != do_lower_case
|
| 107 |
+
or normalizer_state.get("strip_accents", strip_accents) != strip_accents
|
| 108 |
+
or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
|
| 109 |
+
):
|
| 110 |
+
normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
|
| 111 |
+
normalizer_state["lowercase"] = do_lower_case
|
| 112 |
+
normalizer_state["strip_accents"] = strip_accents
|
| 113 |
+
normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
|
| 114 |
+
self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
|
| 115 |
+
|
| 116 |
+
self.do_lower_case = do_lower_case
|
| 117 |
+
|
| 118 |
+
# Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast.build_inputs_with_special_tokens
|
| 119 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
| 120 |
+
"""
|
| 121 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 122 |
+
adding special tokens. A BERT sequence has the following format:
|
| 123 |
+
|
| 124 |
+
- single sequence: `[CLS] X [SEP]`
|
| 125 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 126 |
+
|
| 127 |
+
Args:
|
| 128 |
+
token_ids_0 (`List[int]`):
|
| 129 |
+
List of IDs to which the special tokens will be added.
|
| 130 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 131 |
+
Optional second list of IDs for sequence pairs.
|
| 132 |
+
|
| 133 |
+
Returns:
|
| 134 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 135 |
+
"""
|
| 136 |
+
output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
| 137 |
+
|
| 138 |
+
if token_ids_1 is not None:
|
| 139 |
+
output += token_ids_1 + [self.sep_token_id]
|
| 140 |
+
|
| 141 |
+
return output
|
| 142 |
+
|
| 143 |
+
# Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast.save_vocabulary
|
| 144 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 145 |
+
files = self._tokenizer.model.save(save_directory, name=filename_prefix)
|
| 146 |
+
return tuple(files)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
__all__ = ["DistilBertTokenizerFast"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dit/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dit/convert_dit_unilm_to_pytorch.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert DiT checkpoints from the unilm repository."""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import json
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
import requests
|
| 22 |
+
import torch
|
| 23 |
+
from huggingface_hub import hf_hub_download
|
| 24 |
+
from PIL import Image
|
| 25 |
+
|
| 26 |
+
from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor
|
| 27 |
+
from transformers.image_utils import PILImageResampling
|
| 28 |
+
from transformers.utils import logging
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
logging.set_verbosity_info()
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# here we list all keys to be renamed (original name on the left, our name on the right)
|
| 36 |
+
def create_rename_keys(config, has_lm_head=False, is_semantic=False):
|
| 37 |
+
prefix = "backbone." if is_semantic else ""
|
| 38 |
+
|
| 39 |
+
rename_keys = []
|
| 40 |
+
for i in range(config.num_hidden_layers):
|
| 41 |
+
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
|
| 42 |
+
rename_keys.append((f"{prefix}blocks.{i}.norm1.weight", f"beit.encoder.layer.{i}.layernorm_before.weight"))
|
| 43 |
+
rename_keys.append((f"{prefix}blocks.{i}.norm1.bias", f"beit.encoder.layer.{i}.layernorm_before.bias"))
|
| 44 |
+
rename_keys.append(
|
| 45 |
+
(f"{prefix}blocks.{i}.attn.proj.weight", f"beit.encoder.layer.{i}.attention.output.dense.weight")
|
| 46 |
+
)
|
| 47 |
+
rename_keys.append(
|
| 48 |
+
(f"{prefix}blocks.{i}.attn.proj.bias", f"beit.encoder.layer.{i}.attention.output.dense.bias")
|
| 49 |
+
)
|
| 50 |
+
rename_keys.append((f"{prefix}blocks.{i}.norm2.weight", f"beit.encoder.layer.{i}.layernorm_after.weight"))
|
| 51 |
+
rename_keys.append((f"{prefix}blocks.{i}.norm2.bias", f"beit.encoder.layer.{i}.layernorm_after.bias"))
|
| 52 |
+
rename_keys.append((f"{prefix}blocks.{i}.mlp.fc1.weight", f"beit.encoder.layer.{i}.intermediate.dense.weight"))
|
| 53 |
+
rename_keys.append((f"{prefix}blocks.{i}.mlp.fc1.bias", f"beit.encoder.layer.{i}.intermediate.dense.bias"))
|
| 54 |
+
rename_keys.append((f"{prefix}blocks.{i}.mlp.fc2.weight", f"beit.encoder.layer.{i}.output.dense.weight"))
|
| 55 |
+
rename_keys.append((f"{prefix}blocks.{i}.mlp.fc2.bias", f"beit.encoder.layer.{i}.output.dense.bias"))
|
| 56 |
+
|
| 57 |
+
# projection layer + position embeddings
|
| 58 |
+
rename_keys.extend(
|
| 59 |
+
[
|
| 60 |
+
(f"{prefix}cls_token", "beit.embeddings.cls_token"),
|
| 61 |
+
(f"{prefix}patch_embed.proj.weight", "beit.embeddings.patch_embeddings.projection.weight"),
|
| 62 |
+
(f"{prefix}patch_embed.proj.bias", "beit.embeddings.patch_embeddings.projection.bias"),
|
| 63 |
+
(f"{prefix}pos_embed", "beit.embeddings.position_embeddings"),
|
| 64 |
+
]
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
if has_lm_head:
|
| 68 |
+
# mask token + layernorm
|
| 69 |
+
rename_keys.extend(
|
| 70 |
+
[
|
| 71 |
+
("mask_token", "beit.embeddings.mask_token"),
|
| 72 |
+
("norm.weight", "layernorm.weight"),
|
| 73 |
+
("norm.bias", "layernorm.bias"),
|
| 74 |
+
]
|
| 75 |
+
)
|
| 76 |
+
else:
|
| 77 |
+
# layernorm + classification head
|
| 78 |
+
rename_keys.extend(
|
| 79 |
+
[
|
| 80 |
+
("fc_norm.weight", "beit.pooler.layernorm.weight"),
|
| 81 |
+
("fc_norm.bias", "beit.pooler.layernorm.bias"),
|
| 82 |
+
("head.weight", "classifier.weight"),
|
| 83 |
+
("head.bias", "classifier.bias"),
|
| 84 |
+
]
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
return rename_keys
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
# we split up the matrix of each encoder layer into queries, keys and values
|
| 91 |
+
def read_in_q_k_v(state_dict, config, has_lm_head=False, is_semantic=False):
|
| 92 |
+
for i in range(config.num_hidden_layers):
|
| 93 |
+
prefix = "backbone." if is_semantic else ""
|
| 94 |
+
# queries, keys and values
|
| 95 |
+
in_proj_weight = state_dict.pop(f"{prefix}blocks.{i}.attn.qkv.weight")
|
| 96 |
+
q_bias = state_dict.pop(f"{prefix}blocks.{i}.attn.q_bias")
|
| 97 |
+
v_bias = state_dict.pop(f"{prefix}blocks.{i}.attn.v_bias")
|
| 98 |
+
|
| 99 |
+
state_dict[f"beit.encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[
|
| 100 |
+
: config.hidden_size, :
|
| 101 |
+
]
|
| 102 |
+
state_dict[f"beit.encoder.layer.{i}.attention.attention.query.bias"] = q_bias
|
| 103 |
+
state_dict[f"beit.encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[
|
| 104 |
+
config.hidden_size : config.hidden_size * 2, :
|
| 105 |
+
]
|
| 106 |
+
state_dict[f"beit.encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[
|
| 107 |
+
-config.hidden_size :, :
|
| 108 |
+
]
|
| 109 |
+
state_dict[f"beit.encoder.layer.{i}.attention.attention.value.bias"] = v_bias
|
| 110 |
+
|
| 111 |
+
# gamma_1 and gamma_2
|
| 112 |
+
# we call them lambda because otherwise they are renamed when using .from_pretrained
|
| 113 |
+
gamma_1 = state_dict.pop(f"{prefix}blocks.{i}.gamma_1")
|
| 114 |
+
gamma_2 = state_dict.pop(f"{prefix}blocks.{i}.gamma_2")
|
| 115 |
+
|
| 116 |
+
state_dict[f"beit.encoder.layer.{i}.lambda_1"] = gamma_1
|
| 117 |
+
state_dict[f"beit.encoder.layer.{i}.lambda_2"] = gamma_2
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def rename_key(dct, old, new):
|
| 121 |
+
val = dct.pop(old)
|
| 122 |
+
dct[new] = val
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# We will verify our results on an image of cute cats
|
| 126 |
+
def prepare_img():
|
| 127 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 128 |
+
im = Image.open(requests.get(url, stream=True).raw)
|
| 129 |
+
return im
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@torch.no_grad()
|
| 133 |
+
def convert_dit_checkpoint(checkpoint_url, pytorch_dump_folder_path, push_to_hub=False):
|
| 134 |
+
"""
|
| 135 |
+
Copy/paste/tweak model's weights to our BEiT structure.
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
# define default BEiT configuration
|
| 139 |
+
has_lm_head = "rvlcdip" not in checkpoint_url
|
| 140 |
+
config = BeitConfig(use_absolute_position_embeddings=True, use_mask_token=has_lm_head)
|
| 141 |
+
|
| 142 |
+
# size of the architecture
|
| 143 |
+
if "large" in checkpoint_url or "dit-l" in checkpoint_url:
|
| 144 |
+
config.hidden_size = 1024
|
| 145 |
+
config.intermediate_size = 4096
|
| 146 |
+
config.num_hidden_layers = 24
|
| 147 |
+
config.num_attention_heads = 16
|
| 148 |
+
|
| 149 |
+
# labels
|
| 150 |
+
if "rvlcdip" in checkpoint_url:
|
| 151 |
+
config.num_labels = 16
|
| 152 |
+
repo_id = "huggingface/label-files"
|
| 153 |
+
filename = "rvlcdip-id2label.json"
|
| 154 |
+
id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
|
| 155 |
+
id2label = {int(k): v for k, v in id2label.items()}
|
| 156 |
+
config.id2label = id2label
|
| 157 |
+
config.label2id = {v: k for k, v in id2label.items()}
|
| 158 |
+
|
| 159 |
+
# load state_dict of original model, remove and rename some keys
|
| 160 |
+
state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")["model"]
|
| 161 |
+
|
| 162 |
+
rename_keys = create_rename_keys(config, has_lm_head=has_lm_head)
|
| 163 |
+
for src, dest in rename_keys:
|
| 164 |
+
rename_key(state_dict, src, dest)
|
| 165 |
+
read_in_q_k_v(state_dict, config, has_lm_head=has_lm_head)
|
| 166 |
+
|
| 167 |
+
# load HuggingFace model
|
| 168 |
+
model = BeitForMaskedImageModeling(config) if has_lm_head else BeitForImageClassification(config)
|
| 169 |
+
model.eval()
|
| 170 |
+
model.load_state_dict(state_dict)
|
| 171 |
+
|
| 172 |
+
# Check outputs on an image
|
| 173 |
+
image_processor = BeitImageProcessor(
|
| 174 |
+
size=config.image_size, resample=PILImageResampling.BILINEAR, do_center_crop=False
|
| 175 |
+
)
|
| 176 |
+
image = prepare_img()
|
| 177 |
+
|
| 178 |
+
encoding = image_processor(images=image, return_tensors="pt")
|
| 179 |
+
pixel_values = encoding["pixel_values"]
|
| 180 |
+
|
| 181 |
+
outputs = model(pixel_values)
|
| 182 |
+
logits = outputs.logits
|
| 183 |
+
|
| 184 |
+
# verify logits
|
| 185 |
+
expected_shape = [1, 16] if "rvlcdip" in checkpoint_url else [1, 196, 8192]
|
| 186 |
+
assert logits.shape == torch.Size(expected_shape), "Shape of logits not as expected"
|
| 187 |
+
|
| 188 |
+
Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
|
| 189 |
+
print(f"Saving model to {pytorch_dump_folder_path}")
|
| 190 |
+
model.save_pretrained(pytorch_dump_folder_path)
|
| 191 |
+
print(f"Saving image processor to {pytorch_dump_folder_path}")
|
| 192 |
+
image_processor.save_pretrained(pytorch_dump_folder_path)
|
| 193 |
+
|
| 194 |
+
if push_to_hub:
|
| 195 |
+
if has_lm_head:
|
| 196 |
+
model_name = "dit-base" if "base" in checkpoint_url else "dit-large"
|
| 197 |
+
else:
|
| 198 |
+
model_name = "dit-base-finetuned-rvlcdip" if "dit-b" in checkpoint_url else "dit-large-finetuned-rvlcdip"
|
| 199 |
+
image_processor.push_to_hub(
|
| 200 |
+
repo_path_or_name=Path(pytorch_dump_folder_path, model_name),
|
| 201 |
+
organization="nielsr",
|
| 202 |
+
commit_message="Add image processor",
|
| 203 |
+
use_temp_dir=True,
|
| 204 |
+
)
|
| 205 |
+
model.push_to_hub(
|
| 206 |
+
repo_path_or_name=Path(pytorch_dump_folder_path, model_name),
|
| 207 |
+
organization="nielsr",
|
| 208 |
+
commit_message="Add model",
|
| 209 |
+
use_temp_dir=True,
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
if __name__ == "__main__":
|
| 214 |
+
parser = argparse.ArgumentParser()
|
| 215 |
+
|
| 216 |
+
parser.add_argument(
|
| 217 |
+
"--checkpoint_url",
|
| 218 |
+
default="https://layoutlm.blob.core.windows.net/dit/dit-pts/dit-base-224-p16-500k-62d53a.pth",
|
| 219 |
+
type=str,
|
| 220 |
+
help="URL to the original PyTorch checkpoint (.pth file).",
|
| 221 |
+
)
|
| 222 |
+
parser.add_argument(
|
| 223 |
+
"--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model."
|
| 224 |
+
)
|
| 225 |
+
parser.add_argument(
|
| 226 |
+
"--push_to_hub",
|
| 227 |
+
action="store_true",
|
| 228 |
+
)
|
| 229 |
+
args = parser.parse_args()
|
| 230 |
+
convert_dit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/doge/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 Jingze Shi and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
from typing import TYPE_CHECKING
|
| 16 |
+
|
| 17 |
+
from ...utils import _LazyModule
|
| 18 |
+
from ...utils.import_utils import define_import_structure
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING:
|
| 22 |
+
from .configuration_doge import *
|
| 23 |
+
from .modeling_doge 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__)
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/doge/configuration_doge.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/doge/modular_doge.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_doge.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 Jingze Shi and the HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
# The Doge family of small language models is trained by SmallDoge Team.
|
| 11 |
+
#
|
| 12 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 13 |
+
# you may not use this file except in compliance with the License.
|
| 14 |
+
# You may obtain a copy of the License at
|
| 15 |
+
#
|
| 16 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 17 |
+
#
|
| 18 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 19 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 20 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 21 |
+
# See the License for the specific language governing permissions and
|
| 22 |
+
# limitations under the License.
|
| 23 |
+
from ...configuration_utils import PretrainedConfig
|
| 24 |
+
from ...modeling_rope_utils import rope_config_validation
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class DogeConfig(PretrainedConfig):
|
| 28 |
+
r"""
|
| 29 |
+
This is the configuration class to store the configuration of a [`DogeModel`]. It is used to instantiate an Doge
|
| 30 |
+
model according to the specified arguments, defining the model architecture like [SmallDoge/Doge-320M](https://huggingface.co/SmallDoge/Doge-320M).
|
| 31 |
+
|
| 32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 33 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
vocab_size (`int`, *optional*, defaults to 32768):
|
| 37 |
+
Vocabulary size of the Doge2 model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`DogeModel`]
|
| 38 |
+
hidden_size (`int`, *optional*, defaults to 1024):
|
| 39 |
+
Dimension of the hidden representations.
|
| 40 |
+
intermediate_size (`int`, *optional*, defaults to 2048):
|
| 41 |
+
Dimension of the MLP representations.
|
| 42 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
| 43 |
+
Number of hidden layers in the Transformer decoder.
|
| 44 |
+
hidden_dropout (`float`, *optional*, defaults to 0.0):
|
| 45 |
+
Dropout probability for each sequence transformation and state transformation module.
|
| 46 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 47 |
+
The non-linear activation function (function or string) in the decoder.
|
| 48 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 49 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 50 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 51 |
+
The epsilon used by the rms normalization layers.
|
| 52 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 53 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 54 |
+
relevant if `config.is_decoder=True`.
|
| 55 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 56 |
+
Whether the model's input and output word embeddings should be tied.
|
| 57 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
| 58 |
+
The maximum sequence length that this model might ever be used with.
|
| 59 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
| 60 |
+
The base period of the RoPE embeddings.
|
| 61 |
+
rope_scaling (`Dict`, *optional*):
|
| 62 |
+
Dictionary containing the scaling configuration for the RoPE embeddings.
|
| 63 |
+
NOTE: if you apply new rope type and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value accordingly.
|
| 64 |
+
Doge family of small models use `{ 'rope_type': 'dynamic', 'factor': 4.0, 'original_max_position_embeddings': 2048 }` as the default value.
|
| 65 |
+
Expected contents:
|
| 66 |
+
`rope_type` (`str`):
|
| 67 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope', 'llama3'], with 'default' being the original RoPE implementation.
|
| 68 |
+
`factor` (`float`, *optional*):
|
| 69 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings.
|
| 70 |
+
In most scaling types, a `factor` of x will enable the model to handle sequences of length x * original maximum pre-trained length.
|
| 71 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
| 72 |
+
Used with 'dynamic', 'longrope' and 'llama3'.
|
| 73 |
+
The original max position embeddings used during pretraining.
|
| 74 |
+
`attention_factor` (`float`, *optional*):
|
| 75 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
| 76 |
+
computation.
|
| 77 |
+
If unspecified, it defaults to value recommended by the implementation, using the `factor` field to infer the suggested value.
|
| 78 |
+
`beta_fast` (`float`, *optional*):
|
| 79 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
| 80 |
+
ramp function. If unspecified, it defaults to 32.
|
| 81 |
+
`beta_slow` (`float`, *optional*):
|
| 82 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
| 83 |
+
ramp function. If unspecified, it defaults to 1.
|
| 84 |
+
`short_factor` (`List[float]`, *optional*):
|
| 85 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<`original_max_position_embeddings`).
|
| 86 |
+
Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2
|
| 87 |
+
`long_factor` (`List[float]`, *optional*):
|
| 88 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<`original_max_position_embeddings`).
|
| 89 |
+
Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2
|
| 90 |
+
`low_freq_factor` (`float`, *optional*):
|
| 91 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
| 92 |
+
`high_freq_factor` (`float`, *optional*):
|
| 93 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
| 94 |
+
num_attention_heads (`int`, *optional*, defaults to 8):
|
| 95 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 96 |
+
num_key_value_heads (`int`, *optional*):
|
| 97 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention.
|
| 98 |
+
If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 99 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used.
|
| 100 |
+
When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group.
|
| 101 |
+
For more details checkout [this paper](https://arxiv.org/pdf/2305.13245.pdf).
|
| 102 |
+
If it is not specified, will default to `num_attention_heads`.
|
| 103 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
| 104 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
| 105 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 106 |
+
The dropout ratio for the attention probabilities.
|
| 107 |
+
mlp_bias (`bool`, *optional*, defaults to `False`):
|
| 108 |
+
Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
|
| 109 |
+
sliding_window (`int`, *optional*):
|
| 110 |
+
Sliding window attention window size. If not specified, will default to `None`.
|
| 111 |
+
keep_window_size (`int`, *optional*, defaults to 2048):
|
| 112 |
+
The window size of tokens that are not dynamically masked, and dynamic masking is only performed when the sequence length exceeds this value.
|
| 113 |
+
is_moe (`bool`, *optional*, defaults to `False`):
|
| 114 |
+
Whether to use the Cross Domain Mixture of Experts, if `True`, the MoE will inherit the MLP to initialize.
|
| 115 |
+
num_experts (`int`, *optional*, defaults to 16384):
|
| 116 |
+
Number of routed experts in the model. This is only used when `is_moe=True`.
|
| 117 |
+
num_experts_per_tok (`int`, *optional*, defaults to 64):
|
| 118 |
+
Number of selected experts to route per-token.
|
| 119 |
+
norm_topk_prob (`bool`, *optional*, defaults to `False`):
|
| 120 |
+
Whether to normalize the topk probabilities.
|
| 121 |
+
output_router_logits (`bool`, *optional*, defaults to `False`):
|
| 122 |
+
Whether or not the router logits should be returned by the model. Enabling this will also
|
| 123 |
+
allow the model to output the auxiliary loss, including load balancing loss and router z-loss.
|
| 124 |
+
router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
|
| 125 |
+
The aux loss factor for the total loss.
|
| 126 |
+
|
| 127 |
+
```python
|
| 128 |
+
>>> from transformers import DogeConfig, DogeModel
|
| 129 |
+
|
| 130 |
+
>>> # Initializing a Doge-320M style configuration
|
| 131 |
+
>>> configuration = DogeConfig()
|
| 132 |
+
|
| 133 |
+
>>> # Initializing a model from the Doge-320M style configuration
|
| 134 |
+
>>> model = DogeModel(configuration)
|
| 135 |
+
|
| 136 |
+
>>> # Accessing the model configuration
|
| 137 |
+
>>> configuration = model.config
|
| 138 |
+
```"""
|
| 139 |
+
|
| 140 |
+
model_type = "doge"
|
| 141 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 142 |
+
# Default tensor parallel plan for base model `DogeModel`
|
| 143 |
+
base_model_tp_plan = {
|
| 144 |
+
"layers.*.self_attn.q_proj": "colwise",
|
| 145 |
+
"layers.*.self_attn.k_proj": "colwise",
|
| 146 |
+
"layers.*.self_attn.v_proj": "colwise",
|
| 147 |
+
"layers.*.self_attn.dt_proj": "rowwise",
|
| 148 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
| 149 |
+
"layers.*.input_layernorm.weight": "sequence_parallel",
|
| 150 |
+
"layers.*.input_residual.weight": "sequence_parallel",
|
| 151 |
+
"layers.*.post_attention_layernorm.weight": "sequence_parallel",
|
| 152 |
+
"layers.*.post_attention_residual.weight": "sequence_parallel",
|
| 153 |
+
"norm.weight": "sequence_parallel",
|
| 154 |
+
"layers.*.mlp.gate_proj": "colwise",
|
| 155 |
+
"layers.*.mlp.up_proj": "colwise",
|
| 156 |
+
"layers.*.mlp.down_proj": "rowwise",
|
| 157 |
+
"layers.*.mlp.router_gate": "colwise_rep",
|
| 158 |
+
"layers.*.mlp.down_embed": "rowwise_rep",
|
| 159 |
+
"layers.*.mlp.up_embed": "rowwise_rep",
|
| 160 |
+
}
|
| 161 |
+
base_model_pp_plan = {
|
| 162 |
+
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
| 163 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
| 164 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
def __init__(
|
| 168 |
+
self,
|
| 169 |
+
vocab_size=32768,
|
| 170 |
+
hidden_size=1024,
|
| 171 |
+
intermediate_size=2048,
|
| 172 |
+
num_hidden_layers=32,
|
| 173 |
+
hidden_dropout=0.0,
|
| 174 |
+
hidden_act="silu",
|
| 175 |
+
initializer_range=0.02,
|
| 176 |
+
rms_norm_eps=1e-06,
|
| 177 |
+
use_cache=True,
|
| 178 |
+
tie_word_embeddings=False,
|
| 179 |
+
max_position_embeddings=2048,
|
| 180 |
+
rope_theta=10000.0,
|
| 181 |
+
rope_scaling=None,
|
| 182 |
+
num_attention_heads=8,
|
| 183 |
+
num_key_value_heads=None,
|
| 184 |
+
attention_bias=False,
|
| 185 |
+
attention_dropout=0.0,
|
| 186 |
+
mlp_bias=False,
|
| 187 |
+
sliding_window=None,
|
| 188 |
+
keep_window_size=2048,
|
| 189 |
+
is_moe=False,
|
| 190 |
+
num_experts=16384,
|
| 191 |
+
num_experts_per_tok=64,
|
| 192 |
+
norm_topk_prob=False,
|
| 193 |
+
output_router_logits=False,
|
| 194 |
+
router_aux_loss_coef=0.001,
|
| 195 |
+
**kwargs,
|
| 196 |
+
):
|
| 197 |
+
self.vocab_size = vocab_size
|
| 198 |
+
self.hidden_size = hidden_size
|
| 199 |
+
self.intermediate_size = intermediate_size
|
| 200 |
+
self.num_hidden_layers = num_hidden_layers
|
| 201 |
+
|
| 202 |
+
self.hidden_dropout = hidden_dropout
|
| 203 |
+
self.hidden_act = hidden_act
|
| 204 |
+
self.initializer_range = initializer_range
|
| 205 |
+
self.rms_norm_eps = rms_norm_eps
|
| 206 |
+
self.use_cache = use_cache
|
| 207 |
+
|
| 208 |
+
self.max_position_embeddings = max_position_embeddings
|
| 209 |
+
self.rope_theta = rope_theta
|
| 210 |
+
self.rope_scaling = rope_scaling
|
| 211 |
+
self.num_attention_heads = num_attention_heads
|
| 212 |
+
self.num_key_value_heads = num_key_value_heads
|
| 213 |
+
self.attention_bias = attention_bias
|
| 214 |
+
self.attention_dropout = attention_dropout
|
| 215 |
+
self.mlp_bias = mlp_bias
|
| 216 |
+
self.sliding_window = sliding_window
|
| 217 |
+
self.keep_window_size = keep_window_size
|
| 218 |
+
self.is_moe = is_moe
|
| 219 |
+
self.num_experts = num_experts
|
| 220 |
+
self.num_experts_per_tok = num_experts_per_tok
|
| 221 |
+
self.norm_topk_prob = norm_topk_prob
|
| 222 |
+
self.output_router_logits = output_router_logits
|
| 223 |
+
self.router_aux_loss_coef = router_aux_loss_coef
|
| 224 |
+
|
| 225 |
+
# Validate the correctness of rotary position embeddings parameters
|
| 226 |
+
# BC: if there is a 'type' field, copy it it to 'rope_type'.
|
| 227 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
| 228 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
| 229 |
+
rope_config_validation(self)
|
| 230 |
+
|
| 231 |
+
# for backward compatibility
|
| 232 |
+
if num_key_value_heads is None:
|
| 233 |
+
self.num_key_value_heads = num_attention_heads
|
| 234 |
+
|
| 235 |
+
super().__init__(
|
| 236 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 237 |
+
**kwargs,
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
__all__ = ["DogeConfig"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/doge/convert_doge_weights_to_hf.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from safetensors.torch import load_file
|
| 8 |
+
|
| 9 |
+
from transformers import DogeConfig, DogeForCausalLM
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# fmt: off
|
| 13 |
+
# `None` means we drop the key
|
| 14 |
+
STATE_DICT_MAPPING = {
|
| 15 |
+
# CausalLM keys
|
| 16 |
+
r"^lm_head.weight": r"lm_head.weight",
|
| 17 |
+
|
| 18 |
+
# Model keys
|
| 19 |
+
r"^model.word_embed.weight": r"model.embed_tokens.weight",
|
| 20 |
+
r"^model.rotary_emb.rotary_emb": r"model.rotary_emb.rotary_emb",
|
| 21 |
+
r"^model.final_layernorm.weight": r"model.norm.weight",
|
| 22 |
+
|
| 23 |
+
# Layers keys
|
| 24 |
+
r"^model.layers.(\d+).pre_layernorm.weight": r"model.layers.\1.input_layernorm.weight",
|
| 25 |
+
r"^model.layers.(\d+).pre_residual.weight": r"model.layers.\1.input_residual",
|
| 26 |
+
r"^model.layers.(\d+).post_layernorm.weight": r"model.layers.\1.post_attention_layernorm.weight",
|
| 27 |
+
r"^model.layers.(\d+).post_residual.weight": r"model.layers.\1.post_attention_residual",
|
| 28 |
+
|
| 29 |
+
# Attention keys
|
| 30 |
+
r"^model.layers.(\d+).self_attn.q_proj.weight": r"model.layers.\1.self_attn.q_proj.weight",
|
| 31 |
+
r"^model.layers.(\d+).self_attn.k_proj.weight": r"model.layers.\1.self_attn.k_proj.weight",
|
| 32 |
+
r"^model.layers.(\d+).self_attn.v_proj.weight": r"model.layers.\1.self_attn.v_proj.weight",
|
| 33 |
+
r"^model.layers.(\d+).self_attn.A": r"model.layers.\1.self_attn.A",
|
| 34 |
+
r"^model.layers.(\d+).self_attn.dt_proj.weight": r"model.layers.\1.self_attn.dt_proj.weight",
|
| 35 |
+
r"^model.layers.(\d+).self_attn.o_proj.weight": r"model.layers.\1.self_attn.o_proj.weight",
|
| 36 |
+
|
| 37 |
+
# Feedforward keys
|
| 38 |
+
r"^model.layers.(\d+).feed_forward.gate_proj.weight": r"model.layers.\1.mlp.gate_proj.weight",
|
| 39 |
+
r"^model.layers.(\d+).feed_forward.up_proj.weight": r"model.layers.\1.mlp.up_proj.weight",
|
| 40 |
+
r"^model.layers.(\d+).feed_forward.down_proj.weight": r"model.layers.\1.mlp.down_proj.weight",
|
| 41 |
+
r"^model.layers.(\d+).feed_forward.router_gate.weight": r"model.layers.\1.mlp.router_gate.weight",
|
| 42 |
+
r"^model.layers.(\d+).feed_forward.router_gate.bias": None,
|
| 43 |
+
r"^model.layers.(\d+).feed_forward.down_embed.weight": r"model.layers.\1.mlp.down_embed.weight",
|
| 44 |
+
r"^model.layers.(\d+).feed_forward.up_embed.weight": r"model.layers.\1.mlp.up_embed.weight",
|
| 45 |
+
}
|
| 46 |
+
# fmt: on
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def load_weights(input_dir: str):
|
| 50 |
+
safetensor_files = [os.path.join(input_dir, x) for x in os.listdir(input_dir) if x.endswith(".safetensors")]
|
| 51 |
+
|
| 52 |
+
all_weights = {}
|
| 53 |
+
|
| 54 |
+
if safetensor_files:
|
| 55 |
+
if len(safetensor_files) == 1:
|
| 56 |
+
tensors = load_file(safetensor_files[0])
|
| 57 |
+
all_weights.update(tensors)
|
| 58 |
+
return all_weights
|
| 59 |
+
safetensor_files = sorted(safetensor_files, key=lambda x: int(x.rsplit("-", 3)[1]))
|
| 60 |
+
for file in safetensor_files:
|
| 61 |
+
tensors = load_file(file)
|
| 62 |
+
all_weights.update(tensors)
|
| 63 |
+
return all_weights
|
| 64 |
+
|
| 65 |
+
else:
|
| 66 |
+
raise ValueError("No .safetensors or .bin files found in the specified directory.")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def map_old_key_to_new(old_key):
|
| 70 |
+
for pattern, replacement in STATE_DICT_MAPPING.items():
|
| 71 |
+
if replacement is None:
|
| 72 |
+
if re.fullmatch(pattern, old_key):
|
| 73 |
+
return None
|
| 74 |
+
else:
|
| 75 |
+
new_key, n_replace = re.subn(pattern, replacement, old_key)
|
| 76 |
+
# Early exit of the loop
|
| 77 |
+
if n_replace > 0:
|
| 78 |
+
return new_key
|
| 79 |
+
|
| 80 |
+
raise ValueError(f"Key: {old_key} could not be mapped (check the mapping).")
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def convert_state_dict(original_state_dict: dict, config: DogeConfig):
|
| 84 |
+
new_dict = {}
|
| 85 |
+
|
| 86 |
+
for old_key, value in original_state_dict.items():
|
| 87 |
+
new_key = map_old_key_to_new(old_key)
|
| 88 |
+
if new_key is None:
|
| 89 |
+
continue
|
| 90 |
+
new_dict[new_key] = value
|
| 91 |
+
return new_dict
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def convert_doge_model(input_dir, output_dir):
|
| 95 |
+
# Load and convert config
|
| 96 |
+
with open(os.path.join(input_dir, "config.json")) as f:
|
| 97 |
+
config = json.load(f)
|
| 98 |
+
config = DogeConfig(**config)
|
| 99 |
+
config.save_pretrained(output_dir)
|
| 100 |
+
|
| 101 |
+
# Load and convert weights
|
| 102 |
+
original_state_dict = load_weights(input_dir)
|
| 103 |
+
new_dict = convert_state_dict(original_state_dict, config)
|
| 104 |
+
with torch.device("meta"):
|
| 105 |
+
model = DogeForCausalLM(config)
|
| 106 |
+
if config.tie_word_embeddings:
|
| 107 |
+
new_dict["lm_head.weight"] = new_dict["model.embed_tokens.weight"]
|
| 108 |
+
model.load_state_dict(new_dict, strict=True, assign=True)
|
| 109 |
+
model.save_pretrained(output_dir)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
if __name__ == "__main__":
|
| 113 |
+
parser = argparse.ArgumentParser()
|
| 114 |
+
parser.add_argument(
|
| 115 |
+
"input_dir",
|
| 116 |
+
type=str,
|
| 117 |
+
help="Location of the local folder copied from the Hub.",
|
| 118 |
+
)
|
| 119 |
+
parser.add_argument(
|
| 120 |
+
"output_dir",
|
| 121 |
+
type=str,
|
| 122 |
+
help="Location to write HF model.",
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
args = parser.parse_args()
|
| 126 |
+
convert_doge_model(args.input_dir, args.output_dir)
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/doge/modeling_doge.py
ADDED
|
@@ -0,0 +1,818 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/doge/modular_doge.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_doge.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 Jingze Shi and the HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
# The Doge family of small language models is trained by SmallDoge Team.
|
| 11 |
+
#
|
| 12 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 13 |
+
# you may not use this file except in compliance with the License.
|
| 14 |
+
# You may obtain a copy of the License at
|
| 15 |
+
#
|
| 16 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 17 |
+
#
|
| 18 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 19 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 20 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 21 |
+
# See the License for the specific language governing permissions and
|
| 22 |
+
# limitations under the License.
|
| 23 |
+
|
| 24 |
+
import math
|
| 25 |
+
from typing import Callable, Optional, Union
|
| 26 |
+
|
| 27 |
+
import torch
|
| 28 |
+
import torch.nn.functional as F
|
| 29 |
+
from torch import nn
|
| 30 |
+
|
| 31 |
+
from ...activations import ACT2FN
|
| 32 |
+
from ...cache_utils import Cache, DynamicCache
|
| 33 |
+
from ...generation import GenerationMixin
|
| 34 |
+
from ...integrations import use_kernel_forward_from_hub
|
| 35 |
+
from ...integrations.flex_attention import compile_friendly_flex_attention
|
| 36 |
+
from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
|
| 37 |
+
from ...modeling_layers import GenericForSequenceClassification, GradientCheckpointingLayer
|
| 38 |
+
from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
|
| 39 |
+
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 40 |
+
from ...modeling_utils import AttentionInterface, PreTrainedModel
|
| 41 |
+
from ...processing_utils import Unpack
|
| 42 |
+
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torch_flex_attn_available
|
| 43 |
+
from ...utils.deprecation import deprecate_kwarg
|
| 44 |
+
from ...utils.generic import OutputRecorder, check_model_inputs
|
| 45 |
+
from .configuration_doge import DogeConfig
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if is_torch_flex_attn_available():
|
| 49 |
+
from torch.nn.attention.flex_attention import BlockMask
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
| 53 |
+
class DogeRMSNorm(nn.Module):
|
| 54 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 55 |
+
"""
|
| 56 |
+
DogeRMSNorm is equivalent to T5LayerNorm
|
| 57 |
+
"""
|
| 58 |
+
super().__init__()
|
| 59 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 60 |
+
self.variance_epsilon = eps
|
| 61 |
+
|
| 62 |
+
def forward(self, hidden_states):
|
| 63 |
+
input_dtype = hidden_states.dtype
|
| 64 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 65 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 66 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 67 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 68 |
+
|
| 69 |
+
def extra_repr(self):
|
| 70 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class DogeRotaryEmbedding(nn.Module):
|
| 74 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
| 75 |
+
|
| 76 |
+
def __init__(self, config: DogeConfig, device=None):
|
| 77 |
+
super().__init__()
|
| 78 |
+
# BC: "rope_type" was originally "type"
|
| 79 |
+
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
|
| 80 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
| 81 |
+
else:
|
| 82 |
+
self.rope_type = "default"
|
| 83 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 84 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 85 |
+
|
| 86 |
+
self.config = config
|
| 87 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 88 |
+
|
| 89 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
| 90 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 91 |
+
self.original_inv_freq = self.inv_freq
|
| 92 |
+
|
| 93 |
+
@torch.no_grad()
|
| 94 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 95 |
+
def forward(self, x, position_ids):
|
| 96 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 97 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 98 |
+
|
| 99 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 100 |
+
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
| 101 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 102 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 103 |
+
cos = emb.cos() * self.attention_scaling
|
| 104 |
+
sin = emb.sin() * self.attention_scaling
|
| 105 |
+
|
| 106 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def rotate_half(x):
|
| 110 |
+
"""Rotates half the hidden dims of the input."""
|
| 111 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 112 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 113 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 117 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
q (`torch.Tensor`): The query tensor.
|
| 121 |
+
k (`torch.Tensor`): The key tensor.
|
| 122 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 123 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 124 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 125 |
+
Deprecated and unused.
|
| 126 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 127 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 128 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 129 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 130 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 131 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 132 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 133 |
+
Returns:
|
| 134 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 135 |
+
"""
|
| 136 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 137 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 138 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 139 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 140 |
+
return q_embed, k_embed
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 144 |
+
"""
|
| 145 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 146 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 147 |
+
"""
|
| 148 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 149 |
+
if n_rep == 1:
|
| 150 |
+
return hidden_states
|
| 151 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 152 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def eager_attention_forward(
|
| 156 |
+
module: nn.Module,
|
| 157 |
+
query: torch.Tensor,
|
| 158 |
+
key: torch.Tensor,
|
| 159 |
+
value: torch.Tensor,
|
| 160 |
+
attention_mask: Optional[torch.Tensor],
|
| 161 |
+
scaling: float,
|
| 162 |
+
dropout: float = 0.0,
|
| 163 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 164 |
+
):
|
| 165 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 166 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 167 |
+
|
| 168 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 169 |
+
if attention_mask is not None:
|
| 170 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 171 |
+
attn_weights = attn_weights + causal_mask
|
| 172 |
+
|
| 173 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 174 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 175 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 176 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 177 |
+
|
| 178 |
+
return attn_output, attn_weights
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def flex_attention_forward(
|
| 182 |
+
module: nn.Module,
|
| 183 |
+
query: torch.Tensor,
|
| 184 |
+
key: torch.Tensor,
|
| 185 |
+
value: torch.Tensor,
|
| 186 |
+
attention_mask: Union[torch.Tensor, "BlockMask"],
|
| 187 |
+
scaling: Optional[float] = None,
|
| 188 |
+
softcap: Optional[float] = None,
|
| 189 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 190 |
+
**kwargs,
|
| 191 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 192 |
+
block_mask = None
|
| 193 |
+
causal_mask = None
|
| 194 |
+
if isinstance(attention_mask, BlockMask):
|
| 195 |
+
block_mask = attention_mask
|
| 196 |
+
else:
|
| 197 |
+
causal_mask = attention_mask
|
| 198 |
+
|
| 199 |
+
if causal_mask is not None:
|
| 200 |
+
causal_mask = causal_mask[:, :, :, : key.shape[-2]]
|
| 201 |
+
|
| 202 |
+
def score_mod(score, batch_idx, head_idx, q_idx, kv_idx):
|
| 203 |
+
if softcap is not None:
|
| 204 |
+
score = softcap * torch.tanh(score / softcap)
|
| 205 |
+
if causal_mask is not None:
|
| 206 |
+
score = score + causal_mask[batch_idx][head_idx][q_idx][kv_idx]
|
| 207 |
+
if head_mask is not None:
|
| 208 |
+
score = score + head_mask[batch_idx][head_idx][0][0]
|
| 209 |
+
return score
|
| 210 |
+
|
| 211 |
+
attn_output, attention_weights = compile_friendly_flex_attention(
|
| 212 |
+
query,
|
| 213 |
+
key,
|
| 214 |
+
value,
|
| 215 |
+
score_mod=score_mod,
|
| 216 |
+
block_mask=block_mask,
|
| 217 |
+
enable_gqa=True,
|
| 218 |
+
scale=scaling,
|
| 219 |
+
# Last time checked on PyTorch == 2.5.1: Flex Attention always computes the lse regardless.
|
| 220 |
+
# For simplification, we thus always return it as no additional computations are introduced.
|
| 221 |
+
return_lse=True,
|
| 222 |
+
)
|
| 223 |
+
# lse is returned in float32
|
| 224 |
+
attention_weights = attention_weights.to(value.dtype)
|
| 225 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 226 |
+
|
| 227 |
+
return attn_output, attention_weights
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
ALL_ATTENTION_FUNCTIONS = AttentionInterface()
|
| 231 |
+
ALL_ATTENTION_FUNCTIONS["doge_flex_attention"] = flex_attention_forward
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class DogeAttention(nn.Module):
|
| 235 |
+
def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None):
|
| 236 |
+
super().__init__()
|
| 237 |
+
self.config = config
|
| 238 |
+
self.layer_idx = layer_idx
|
| 239 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 240 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 241 |
+
self.scaling = self.head_dim**-0.5
|
| 242 |
+
self.attention_dropout = config.attention_dropout
|
| 243 |
+
self.keep_window_size = config.keep_window_size
|
| 244 |
+
|
| 245 |
+
self.q_proj = nn.Linear(
|
| 246 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 247 |
+
)
|
| 248 |
+
self.k_proj = nn.Linear(
|
| 249 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 250 |
+
)
|
| 251 |
+
self.v_proj = nn.Linear(
|
| 252 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 253 |
+
)
|
| 254 |
+
# dynamic mask for the QK^T attention weights matrix
|
| 255 |
+
self.A = nn.Parameter(torch.zeros(config.num_key_value_heads))
|
| 256 |
+
self.dt_proj = nn.Linear(
|
| 257 |
+
config.num_key_value_heads * self.head_dim, config.num_key_value_heads, bias=config.attention_bias
|
| 258 |
+
)
|
| 259 |
+
self.o_proj = nn.Linear(
|
| 260 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 261 |
+
)
|
| 262 |
+
self.q_norm = DogeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 263 |
+
self.k_norm = DogeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 264 |
+
|
| 265 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 266 |
+
def forward(
|
| 267 |
+
self,
|
| 268 |
+
hidden_states: torch.Tensor,
|
| 269 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 270 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 271 |
+
past_key_values: Optional[Cache] = None,
|
| 272 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 273 |
+
**kwargs,
|
| 274 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
|
| 275 |
+
input_shape = hidden_states.shape[:-1]
|
| 276 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 277 |
+
|
| 278 |
+
query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 279 |
+
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 280 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 281 |
+
|
| 282 |
+
cos, sin = position_embeddings
|
| 283 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 284 |
+
|
| 285 |
+
if past_key_values is not None:
|
| 286 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 287 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 288 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 289 |
+
|
| 290 |
+
# calculate dynamic mask from value_states
|
| 291 |
+
dt_states = self.dt_proj(
|
| 292 |
+
value_states.transpose(1, 2).reshape(value_states.shape[0], value_states.shape[-2], -1)
|
| 293 |
+
)
|
| 294 |
+
dt_states = torch.exp(self.A * F.softplus(dt_states)).transpose(-1, -2)
|
| 295 |
+
attn_mask = self.prepare_dynamic_mask(
|
| 296 |
+
hidden_states=hidden_states,
|
| 297 |
+
dt_states=dt_states,
|
| 298 |
+
keep_window_size=self.keep_window_size,
|
| 299 |
+
attention_mask=attention_mask,
|
| 300 |
+
)
|
| 301 |
+
attn_mask = repeat_kv(attn_mask, self.num_key_value_groups)
|
| 302 |
+
|
| 303 |
+
attention_interface: Callable = eager_attention_forward
|
| 304 |
+
if self.config._attn_implementation != "eager":
|
| 305 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 306 |
+
|
| 307 |
+
attn_output, attn_weights = attention_interface(
|
| 308 |
+
self,
|
| 309 |
+
query_states,
|
| 310 |
+
key_states,
|
| 311 |
+
value_states,
|
| 312 |
+
attention_mask=attn_mask,
|
| 313 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 314 |
+
scaling=self.scaling,
|
| 315 |
+
**kwargs,
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 319 |
+
attn_output = self.o_proj(attn_output)
|
| 320 |
+
return attn_output, attn_weights
|
| 321 |
+
|
| 322 |
+
def prepare_dynamic_mask(
|
| 323 |
+
self,
|
| 324 |
+
hidden_states: torch.Tensor,
|
| 325 |
+
dt_states: torch.Tensor,
|
| 326 |
+
keep_window_size: int = 2048,
|
| 327 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 328 |
+
):
|
| 329 |
+
"""
|
| 330 |
+
The core idea of DMA is to calculate the dynamic attention mask to mask the tokens that should be masked, so as to form sparse attention.
|
| 331 |
+
|
| 332 |
+
Combine `dt_states` with `attention_mask` to generate the final `attn_mask`.
|
| 333 |
+
|
| 334 |
+
Args:
|
| 335 |
+
hidden_states (`torch.Tensor`): The input hidden_states, used to determine the minimum value of the current input precision.
|
| 336 |
+
dt_states (`torch.Tensor`): dt_states of shape `(batch_size, num_heads, key_sequence_length)`.
|
| 337 |
+
keep_window_size (`int`): The window size of tokens that are not dynamically masked, and dynamic masking is only performed when the sequence length exceeds this value.
|
| 338 |
+
attention_mask (`torch.Tensor`, *optional*): attention mask of shape `(batch_size, 1, query_sequence_length, key_sequence_length)`.
|
| 339 |
+
"""
|
| 340 |
+
min_dtype = torch.finfo(hidden_states.dtype).min
|
| 341 |
+
dtype = hidden_states.dtype
|
| 342 |
+
attn_mask = dt_states[:, :, None, :].expand(
|
| 343 |
+
-1, -1, hidden_states.shape[1], -1
|
| 344 |
+
) # [batch_size, num_heads, query_len, key_len]
|
| 345 |
+
if attention_mask is not None and not isinstance(attention_mask, BlockMask):
|
| 346 |
+
if attention_mask.dtype == torch.bool:
|
| 347 |
+
dtype = hidden_states.dtype
|
| 348 |
+
attention_mask = torch.where(
|
| 349 |
+
attention_mask, torch.tensor(0.0, device=attention_mask.device, dtype=dtype), min_dtype
|
| 350 |
+
)
|
| 351 |
+
attn_mask = attn_mask.masked_fill(attention_mask[:, :, :, : attn_mask.shape[-1]] != 0, min_dtype)
|
| 352 |
+
if attn_mask.shape[-1] > keep_window_size:
|
| 353 |
+
active_mask = torch.zeros_like(attn_mask, dtype=dtype, device=attn_mask.device)
|
| 354 |
+
topk_indices = torch.topk(attn_mask, keep_window_size, dim=-1, largest=True, sorted=False).indices
|
| 355 |
+
active_mask = active_mask.scatter(-1, topk_indices, 1.0)
|
| 356 |
+
attn_mask = attn_mask.masked_fill(active_mask == 0.0, min_dtype)
|
| 357 |
+
return attn_mask
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
class DogeMLP(nn.Module):
|
| 361 |
+
def __init__(self, config):
|
| 362 |
+
super().__init__()
|
| 363 |
+
self.config = config
|
| 364 |
+
self.hidden_size = config.hidden_size
|
| 365 |
+
self.intermediate_size = config.intermediate_size
|
| 366 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 367 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 368 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
| 369 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 370 |
+
|
| 371 |
+
def forward(self, x):
|
| 372 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 373 |
+
return down_proj
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
class DogeCDMoE(nn.Module):
|
| 377 |
+
def __init__(self, config: DogeConfig):
|
| 378 |
+
super().__init__()
|
| 379 |
+
self.hidden_size = config.hidden_size
|
| 380 |
+
self.intermediate_size = config.intermediate_size
|
| 381 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 382 |
+
|
| 383 |
+
self.num_experts = config.num_experts
|
| 384 |
+
self.num_keys = math.floor(math.sqrt(self.num_experts))
|
| 385 |
+
self.top_k = config.num_experts_per_tok
|
| 386 |
+
self.norm_topk_prob = config.norm_topk_prob
|
| 387 |
+
|
| 388 |
+
# shared expert
|
| 389 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 390 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 391 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
| 392 |
+
|
| 393 |
+
# router gate for retrieval experts
|
| 394 |
+
self.router_gate = nn.Linear(self.hidden_size, self.num_keys * 2, bias=False)
|
| 395 |
+
|
| 396 |
+
# routed experts
|
| 397 |
+
self.down_embed = nn.Embedding(self.num_experts, self.hidden_size)
|
| 398 |
+
self.up_embed = nn.Embedding(self.num_experts, self.hidden_size)
|
| 399 |
+
|
| 400 |
+
def forward(
|
| 401 |
+
self,
|
| 402 |
+
hidden_states: torch.Tensor,
|
| 403 |
+
**kwargs,
|
| 404 |
+
) -> torch.Tensor:
|
| 405 |
+
bsz, seq_len, _ = hidden_states.shape
|
| 406 |
+
|
| 407 |
+
# get routing logits with router gate
|
| 408 |
+
router_logits = self.router_gate(hidden_states).view(2, bsz * seq_len, -1)
|
| 409 |
+
|
| 410 |
+
# get experts with the highest routing logits
|
| 411 |
+
(scores_x, scores_y), (indices_x, indices_y) = router_logits.topk(self.num_keys, dim=-1)
|
| 412 |
+
all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2)
|
| 413 |
+
all_indices = indices_x.unsqueeze(-1) * self.num_keys + indices_y.unsqueeze(-2)
|
| 414 |
+
all_scores = all_scores.view(*all_scores.shape[:-2], -1)
|
| 415 |
+
all_indices = all_indices.view(*all_indices.shape[:-2], -1)
|
| 416 |
+
scores, position_indices = all_scores.topk(self.top_k, dim=-1)
|
| 417 |
+
indices = all_indices.gather(-1, position_indices)
|
| 418 |
+
routing_weights = F.softmax(scores, dim=-1)
|
| 419 |
+
if self.norm_topk_prob:
|
| 420 |
+
routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
|
| 421 |
+
|
| 422 |
+
# mix routed experts states with shared expert states
|
| 423 |
+
down_embed = self.down_embed(indices)
|
| 424 |
+
up_embed = self.up_embed(indices)
|
| 425 |
+
experts_weights = torch.matmul(down_embed, hidden_states.view(bsz * seq_len, -1, 1)).view(bsz * seq_len, -1)
|
| 426 |
+
experts_weights = self.act_fn(experts_weights) * routing_weights
|
| 427 |
+
experts_states = torch.matmul(experts_weights.view(bsz * seq_len, 1, -1), up_embed).view(bsz, seq_len, -1)
|
| 428 |
+
hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
|
| 429 |
+
hidden_states = hidden_states + experts_states
|
| 430 |
+
return hidden_states, router_logits
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
class DogeDecoderLayer(GradientCheckpointingLayer):
|
| 434 |
+
def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None):
|
| 435 |
+
super().__init__()
|
| 436 |
+
self.hidden_dropout = config.hidden_dropout
|
| 437 |
+
|
| 438 |
+
self.input_layernorm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 439 |
+
self.self_attn = DogeAttention(config=config, layer_idx=layer_idx)
|
| 440 |
+
self.input_residual = nn.Parameter(torch.ones(config.hidden_size))
|
| 441 |
+
|
| 442 |
+
self.post_attention_layernorm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 443 |
+
self.mlp = DogeMLP(config) if not config.is_moe else DogeCDMoE(config)
|
| 444 |
+
self.post_attention_residual = nn.Parameter(torch.ones(config.hidden_size))
|
| 445 |
+
|
| 446 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 447 |
+
def forward(
|
| 448 |
+
self,
|
| 449 |
+
hidden_states: torch.Tensor,
|
| 450 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 451 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 452 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 453 |
+
past_key_values: Optional[tuple[torch.Tensor]] = None,
|
| 454 |
+
use_cache: Optional[bool] = False,
|
| 455 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 456 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 457 |
+
) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 458 |
+
# sequence transformation
|
| 459 |
+
residual = hidden_states
|
| 460 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 461 |
+
hidden_states, self_attn_weights = self.self_attn(
|
| 462 |
+
hidden_states=hidden_states,
|
| 463 |
+
position_embeddings=position_embeddings,
|
| 464 |
+
attention_mask=attention_mask,
|
| 465 |
+
position_ids=position_ids,
|
| 466 |
+
past_key_values=past_key_values,
|
| 467 |
+
use_cache=use_cache,
|
| 468 |
+
cache_position=cache_position,
|
| 469 |
+
**kwargs,
|
| 470 |
+
)
|
| 471 |
+
hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training)
|
| 472 |
+
hidden_states = self.input_residual * residual + hidden_states
|
| 473 |
+
|
| 474 |
+
# state transformation
|
| 475 |
+
residual = hidden_states
|
| 476 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 477 |
+
hidden_states = self.mlp(hidden_states)
|
| 478 |
+
hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training)
|
| 479 |
+
hidden_states = self.post_attention_residual * residual + hidden_states
|
| 480 |
+
|
| 481 |
+
return hidden_states
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
@auto_docstring
|
| 485 |
+
class DogePreTrainedModel(PreTrainedModel):
|
| 486 |
+
config: DogeConfig
|
| 487 |
+
base_model_prefix = "model"
|
| 488 |
+
supports_gradient_checkpointing = True
|
| 489 |
+
_no_split_modules = ["DogeDecoderLayer"]
|
| 490 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 491 |
+
_supports_flash_attn = False
|
| 492 |
+
_supports_sdpa = True
|
| 493 |
+
_supports_flex_attn = True
|
| 494 |
+
_can_compile_fullgraph = False
|
| 495 |
+
_supports_attention_backend = True
|
| 496 |
+
_can_record_outputs = {
|
| 497 |
+
"router_logits": OutputRecorder(DogeCDMoE, index=1),
|
| 498 |
+
"hidden_states": DogeDecoderLayer,
|
| 499 |
+
"attentions": DogeAttention,
|
| 500 |
+
}
|
| 501 |
+
|
| 502 |
+
def _init_weights(self, module):
|
| 503 |
+
"""Initialize the weights"""
|
| 504 |
+
super()._init_weights(module)
|
| 505 |
+
if isinstance(module, DogeAttention):
|
| 506 |
+
if hasattr(module, "A"):
|
| 507 |
+
module.A.data.zero_()
|
| 508 |
+
elif isinstance(module, DogeDecoderLayer):
|
| 509 |
+
if hasattr(module, "input_residual"):
|
| 510 |
+
module.input_residual.data.fill_(1.0)
|
| 511 |
+
if hasattr(module, "post_attention_residual"):
|
| 512 |
+
module.post_attention_residual.data.fill_(1.0)
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
@auto_docstring
|
| 516 |
+
class DogeModel(DogePreTrainedModel):
|
| 517 |
+
def __init__(self, config: DogeConfig):
|
| 518 |
+
super().__init__(config)
|
| 519 |
+
self.padding_idx = config.pad_token_id
|
| 520 |
+
self.vocab_size = config.vocab_size
|
| 521 |
+
|
| 522 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 523 |
+
self.layers = nn.ModuleList(
|
| 524 |
+
[DogeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 525 |
+
)
|
| 526 |
+
self.norm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 527 |
+
self.rotary_emb = DogeRotaryEmbedding(config=config)
|
| 528 |
+
self.gradient_checkpointing = False
|
| 529 |
+
|
| 530 |
+
# Initialize weights and apply final processing
|
| 531 |
+
self.post_init()
|
| 532 |
+
|
| 533 |
+
@check_model_inputs
|
| 534 |
+
@auto_docstring
|
| 535 |
+
def forward(
|
| 536 |
+
self,
|
| 537 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 538 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 539 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 540 |
+
past_key_values: Optional[Cache] = None,
|
| 541 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 542 |
+
use_cache: Optional[bool] = None,
|
| 543 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 544 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 545 |
+
) -> MoeModelOutputWithPast:
|
| 546 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 547 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 548 |
+
|
| 549 |
+
if use_cache and past_key_values is None:
|
| 550 |
+
past_key_values = DynamicCache(config=self.config)
|
| 551 |
+
|
| 552 |
+
if inputs_embeds is None:
|
| 553 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 554 |
+
|
| 555 |
+
if cache_position is None:
|
| 556 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 557 |
+
cache_position = torch.arange(
|
| 558 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
| 559 |
+
)
|
| 560 |
+
if position_ids is None:
|
| 561 |
+
position_ids = cache_position.unsqueeze(0)
|
| 562 |
+
|
| 563 |
+
mask_function = create_causal_mask if self.config.sliding_window is None else create_sliding_window_causal_mask
|
| 564 |
+
causal_mask = mask_function(
|
| 565 |
+
config=self.config,
|
| 566 |
+
input_embeds=inputs_embeds,
|
| 567 |
+
attention_mask=attention_mask,
|
| 568 |
+
cache_position=cache_position,
|
| 569 |
+
past_key_values=past_key_values,
|
| 570 |
+
position_ids=position_ids,
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
hidden_states = inputs_embeds
|
| 574 |
+
|
| 575 |
+
# create position embeddings to be shared across the decoder layers
|
| 576 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 577 |
+
|
| 578 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
| 579 |
+
hidden_states = decoder_layer(
|
| 580 |
+
hidden_states,
|
| 581 |
+
position_embeddings=position_embeddings,
|
| 582 |
+
attention_mask=causal_mask,
|
| 583 |
+
position_ids=position_ids,
|
| 584 |
+
past_key_values=past_key_values,
|
| 585 |
+
use_cache=use_cache,
|
| 586 |
+
cache_position=cache_position,
|
| 587 |
+
**kwargs,
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
hidden_states = self.norm(hidden_states)
|
| 591 |
+
|
| 592 |
+
return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE
|
| 593 |
+
last_hidden_state=hidden_states,
|
| 594 |
+
past_key_values=past_key_values,
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
def load_balancing_loss_func(
|
| 599 |
+
gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
|
| 600 |
+
num_experts: Optional[int] = None,
|
| 601 |
+
num_keys: Optional[int] = None,
|
| 602 |
+
top_k: int = 2,
|
| 603 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 604 |
+
) -> Union[torch.Tensor, int]:
|
| 605 |
+
r"""
|
| 606 |
+
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
|
| 607 |
+
|
| 608 |
+
See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
|
| 609 |
+
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
|
| 610 |
+
experts is too unbalanced.
|
| 611 |
+
|
| 612 |
+
Args:
|
| 613 |
+
gate_logits:
|
| 614 |
+
Logits from the `router_gate`, should be a tuple of model.config.num_hidden_layers tensors of
|
| 615 |
+
shape [2, batch_size * sequence_length, num_keys].
|
| 616 |
+
num_experts:
|
| 617 |
+
Number of experts
|
| 618 |
+
num_keys:
|
| 619 |
+
Number of keys
|
| 620 |
+
top_k:
|
| 621 |
+
The number of experts to route per-token, can be also interpreted as the `top-k` routing
|
| 622 |
+
parameter.
|
| 623 |
+
attention_mask (`torch.Tensor`, *optional*):
|
| 624 |
+
The attention_mask used in forward function
|
| 625 |
+
shape [batch_size X sequence_length] if not None.
|
| 626 |
+
|
| 627 |
+
Returns:
|
| 628 |
+
The auxiliary loss.
|
| 629 |
+
"""
|
| 630 |
+
if gate_logits is None or not isinstance(gate_logits, tuple):
|
| 631 |
+
return 0
|
| 632 |
+
|
| 633 |
+
compute_dtype = gate_logits[0].dtype
|
| 634 |
+
compute_device = gate_logits[0].device
|
| 635 |
+
all_expert_indices = []
|
| 636 |
+
all_routing_weights = []
|
| 637 |
+
|
| 638 |
+
for layer_gate_logits in gate_logits:
|
| 639 |
+
layer_gate_logits = layer_gate_logits.to(compute_device)
|
| 640 |
+
|
| 641 |
+
(scores_x, scores_y), (indices_x, indices_y) = layer_gate_logits.topk(num_keys, dim=-1)
|
| 642 |
+
|
| 643 |
+
all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2)
|
| 644 |
+
all_indices = indices_x.unsqueeze(-1) * num_keys + indices_y.unsqueeze(-2)
|
| 645 |
+
all_scores = all_scores.view(*all_scores.shape[:-2], -1)
|
| 646 |
+
all_indices = all_indices.view(*all_indices.shape[:-2], -1)
|
| 647 |
+
|
| 648 |
+
_, position_indices = all_scores.topk(top_k, dim=-1)
|
| 649 |
+
expert_indices = all_indices.gather(-1, position_indices)
|
| 650 |
+
|
| 651 |
+
routing_weights = F.softmax(all_scores, dim=-1)
|
| 652 |
+
|
| 653 |
+
all_expert_indices.append(expert_indices)
|
| 654 |
+
all_routing_weights.append(routing_weights)
|
| 655 |
+
all_expert_indices = torch.cat(all_expert_indices, dim=0)
|
| 656 |
+
all_routing_weights = torch.cat(all_routing_weights, dim=0)
|
| 657 |
+
|
| 658 |
+
if attention_mask is None:
|
| 659 |
+
# Compute the percentage of tokens routed to each experts
|
| 660 |
+
all_expert_indices = all_expert_indices.view(-1)
|
| 661 |
+
tokens_per_expert = torch.zeros(num_experts, dtype=compute_dtype, device=compute_device)
|
| 662 |
+
pad = torch.ones_like(all_expert_indices, dtype=compute_dtype, device=compute_device)
|
| 663 |
+
tokens_per_expert = tokens_per_expert.scatter_add_(0, all_expert_indices, pad) / all_expert_indices.shape[0]
|
| 664 |
+
|
| 665 |
+
# Compute the average probability of routing to these experts
|
| 666 |
+
router_prob_per_expert = torch.mean(all_routing_weights, dim=0)
|
| 667 |
+
else:
|
| 668 |
+
batch_size, sequence_length = attention_mask.shape
|
| 669 |
+
num_hidden_layers = len(gate_logits)
|
| 670 |
+
|
| 671 |
+
# Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
|
| 672 |
+
expert_attention_mask = (
|
| 673 |
+
attention_mask[None, :, :, None]
|
| 674 |
+
.expand((num_hidden_layers, batch_size, sequence_length, top_k))
|
| 675 |
+
.reshape(-1)
|
| 676 |
+
.to(compute_device)
|
| 677 |
+
)
|
| 678 |
+
all_expert_indices = all_expert_indices.view(-1)[expert_attention_mask.bool()]
|
| 679 |
+
|
| 680 |
+
# Compute the percentage of tokens routed to each experts
|
| 681 |
+
tokens_per_expert = torch.zeros(num_experts, dtype=compute_dtype, device=compute_device)
|
| 682 |
+
pad = torch.ones_like(all_expert_indices, dtype=compute_dtype, device=compute_device)
|
| 683 |
+
tokens_per_expert = tokens_per_expert.scatter_add_(0, all_expert_indices, pad) / torch.sum(
|
| 684 |
+
expert_attention_mask
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
# Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
|
| 688 |
+
router_per_expert_attention_mask = (
|
| 689 |
+
attention_mask[None, :, :, None]
|
| 690 |
+
.expand((num_hidden_layers, batch_size, sequence_length, num_experts))
|
| 691 |
+
.reshape(-1, num_experts)
|
| 692 |
+
.to(compute_device)
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
# Compute the average probability of routing to these experts
|
| 696 |
+
router_prob_per_expert = torch.sum(all_routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
|
| 697 |
+
router_per_expert_attention_mask, dim=0
|
| 698 |
+
)
|
| 699 |
+
|
| 700 |
+
overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert)
|
| 701 |
+
return overall_loss * num_experts
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
@auto_docstring
|
| 705 |
+
class DogeForCausalLM(DogePreTrainedModel, GenerationMixin):
|
| 706 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 707 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
| 708 |
+
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
| 709 |
+
|
| 710 |
+
def __init__(self, config):
|
| 711 |
+
super().__init__(config)
|
| 712 |
+
self.model = DogeModel(config)
|
| 713 |
+
self.vocab_size = config.vocab_size
|
| 714 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 715 |
+
self.router_aux_loss_coef = config.router_aux_loss_coef
|
| 716 |
+
self.num_experts = config.num_experts
|
| 717 |
+
self.num_experts_per_tok = config.num_experts_per_tok
|
| 718 |
+
|
| 719 |
+
# Initialize weights and apply final processing
|
| 720 |
+
self.post_init()
|
| 721 |
+
|
| 722 |
+
def set_decoder(self, decoder):
|
| 723 |
+
self.model = decoder
|
| 724 |
+
|
| 725 |
+
def get_decoder(self):
|
| 726 |
+
return self.model
|
| 727 |
+
|
| 728 |
+
@can_return_tuple
|
| 729 |
+
@auto_docstring
|
| 730 |
+
def forward(
|
| 731 |
+
self,
|
| 732 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 733 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 734 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 735 |
+
past_key_values: Optional[list[torch.FloatTensor]] = None,
|
| 736 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 737 |
+
labels: Optional[torch.LongTensor] = None,
|
| 738 |
+
use_cache: Optional[bool] = None,
|
| 739 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 740 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 741 |
+
output_router_logits: Optional[bool] = None,
|
| 742 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 743 |
+
) -> MoeCausalLMOutputWithPast:
|
| 744 |
+
r"""
|
| 745 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 746 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 747 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 748 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 749 |
+
|
| 750 |
+
Example:
|
| 751 |
+
|
| 752 |
+
```python
|
| 753 |
+
>>> from transformers import AutoTokenizer, DogeForCausalLM
|
| 754 |
+
|
| 755 |
+
>>> model = DogeForCausalLM.from_pretrained("SmallDoge/Doge-320M")
|
| 756 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("SmallDoge/Doge-320M")
|
| 757 |
+
|
| 758 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 759 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 760 |
+
|
| 761 |
+
>>> # Generate
|
| 762 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 763 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 764 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 765 |
+
```"""
|
| 766 |
+
output_router_logits = (
|
| 767 |
+
output_router_logits if output_router_logits is not None else self.config.output_router_logits
|
| 768 |
+
)
|
| 769 |
+
|
| 770 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 771 |
+
outputs: MoeModelOutputWithPast = self.model(
|
| 772 |
+
input_ids=input_ids,
|
| 773 |
+
attention_mask=attention_mask,
|
| 774 |
+
position_ids=position_ids,
|
| 775 |
+
past_key_values=past_key_values,
|
| 776 |
+
inputs_embeds=inputs_embeds,
|
| 777 |
+
use_cache=use_cache,
|
| 778 |
+
cache_position=cache_position,
|
| 779 |
+
**kwargs,
|
| 780 |
+
)
|
| 781 |
+
|
| 782 |
+
hidden_states = outputs.last_hidden_state
|
| 783 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 784 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 785 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 786 |
+
|
| 787 |
+
loss = None
|
| 788 |
+
if labels is not None:
|
| 789 |
+
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
|
| 790 |
+
|
| 791 |
+
aux_loss = None
|
| 792 |
+
if output_router_logits:
|
| 793 |
+
aux_loss = load_balancing_loss_func(
|
| 794 |
+
outputs.router_logits,
|
| 795 |
+
self.num_experts,
|
| 796 |
+
math.floor(math.sqrt(self.num_experts)),
|
| 797 |
+
self.num_experts_per_tok,
|
| 798 |
+
attention_mask,
|
| 799 |
+
)
|
| 800 |
+
if labels is not None:
|
| 801 |
+
loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
|
| 802 |
+
|
| 803 |
+
return MoeCausalLMOutputWithPast(
|
| 804 |
+
loss=loss,
|
| 805 |
+
aux_loss=aux_loss,
|
| 806 |
+
logits=logits,
|
| 807 |
+
past_key_values=outputs.past_key_values,
|
| 808 |
+
hidden_states=outputs.hidden_states,
|
| 809 |
+
attentions=outputs.attentions,
|
| 810 |
+
router_logits=outputs.router_logits,
|
| 811 |
+
)
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
class DogeForSequenceClassification(GenericForSequenceClassification, DogePreTrainedModel):
|
| 815 |
+
pass
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
__all__ = ["DogeForCausalLM", "DogeModel", "DogePreTrainedModel", "DogeForSequenceClassification"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/doge/modular_doge.py
ADDED
|
@@ -0,0 +1,800 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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shi and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# The Doge family of small language models is trained by SmallDoge Team.
|
| 5 |
+
#
|
| 6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 7 |
+
# you may not use this file except in compliance with the License.
|
| 8 |
+
# You may obtain a copy of the License at
|
| 9 |
+
#
|
| 10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 11 |
+
#
|
| 12 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 15 |
+
# See the License for the specific language governing permissions and
|
| 16 |
+
# limitations under the License.
|
| 17 |
+
"""PyTorch Doge model."""
|
| 18 |
+
|
| 19 |
+
import math
|
| 20 |
+
from typing import Callable, Optional, Union
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn.functional as F
|
| 24 |
+
from torch import nn
|
| 25 |
+
|
| 26 |
+
from ...activations import ACT2FN
|
| 27 |
+
from ...cache_utils import Cache
|
| 28 |
+
from ...configuration_utils import PretrainedConfig
|
| 29 |
+
from ...integrations.flex_attention import compile_friendly_flex_attention
|
| 30 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 31 |
+
from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
|
| 32 |
+
from ...modeling_rope_utils import rope_config_validation
|
| 33 |
+
from ...modeling_utils import AttentionInterface
|
| 34 |
+
from ...processing_utils import Unpack
|
| 35 |
+
from ...utils import TransformersKwargs, is_torch_flex_attn_available
|
| 36 |
+
from ...utils.deprecation import deprecate_kwarg
|
| 37 |
+
from ...utils.generic import OutputRecorder
|
| 38 |
+
from ..llama.modeling_llama import (
|
| 39 |
+
LlamaForSequenceClassification,
|
| 40 |
+
LlamaMLP,
|
| 41 |
+
LlamaPreTrainedModel,
|
| 42 |
+
LlamaRMSNorm,
|
| 43 |
+
LlamaRotaryEmbedding,
|
| 44 |
+
apply_rotary_pos_emb,
|
| 45 |
+
eager_attention_forward,
|
| 46 |
+
repeat_kv,
|
| 47 |
+
)
|
| 48 |
+
from ..mixtral.modeling_mixtral import MixtralForCausalLM, MixtralModel
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
if is_torch_flex_attn_available():
|
| 52 |
+
from torch.nn.attention.flex_attention import BlockMask
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class DogeConfig(PretrainedConfig):
|
| 56 |
+
r"""
|
| 57 |
+
This is the configuration class to store the configuration of a [`DogeModel`]. It is used to instantiate an Doge
|
| 58 |
+
model according to the specified arguments, defining the model architecture like [SmallDoge/Doge-320M](https://huggingface.co/SmallDoge/Doge-320M).
|
| 59 |
+
|
| 60 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 61 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
vocab_size (`int`, *optional*, defaults to 32768):
|
| 65 |
+
Vocabulary size of the Doge2 model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`DogeModel`]
|
| 66 |
+
hidden_size (`int`, *optional*, defaults to 1024):
|
| 67 |
+
Dimension of the hidden representations.
|
| 68 |
+
intermediate_size (`int`, *optional*, defaults to 2048):
|
| 69 |
+
Dimension of the MLP representations.
|
| 70 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
| 71 |
+
Number of hidden layers in the Transformer decoder.
|
| 72 |
+
hidden_dropout (`float`, *optional*, defaults to 0.0):
|
| 73 |
+
Dropout probability for each sequence transformation and state transformation module.
|
| 74 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 75 |
+
The non-linear activation function (function or string) in the decoder.
|
| 76 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 77 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 78 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 79 |
+
The epsilon used by the rms normalization layers.
|
| 80 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 81 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 82 |
+
relevant if `config.is_decoder=True`.
|
| 83 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 84 |
+
Whether the model's input and output word embeddings should be tied.
|
| 85 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
| 86 |
+
The maximum sequence length that this model might ever be used with.
|
| 87 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
| 88 |
+
The base period of the RoPE embeddings.
|
| 89 |
+
rope_scaling (`Dict`, *optional*):
|
| 90 |
+
Dictionary containing the scaling configuration for the RoPE embeddings.
|
| 91 |
+
NOTE: if you apply new rope type and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value accordingly.
|
| 92 |
+
Doge family of small models use `{ 'rope_type': 'dynamic', 'factor': 4.0, 'original_max_position_embeddings': 2048 }` as the default value.
|
| 93 |
+
Expected contents:
|
| 94 |
+
`rope_type` (`str`):
|
| 95 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope', 'llama3'], with 'default' being the original RoPE implementation.
|
| 96 |
+
`factor` (`float`, *optional*):
|
| 97 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings.
|
| 98 |
+
In most scaling types, a `factor` of x will enable the model to handle sequences of length x * original maximum pre-trained length.
|
| 99 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
| 100 |
+
Used with 'dynamic', 'longrope' and 'llama3'.
|
| 101 |
+
The original max position embeddings used during pretraining.
|
| 102 |
+
`attention_factor` (`float`, *optional*):
|
| 103 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
| 104 |
+
computation.
|
| 105 |
+
If unspecified, it defaults to value recommended by the implementation, using the `factor` field to infer the suggested value.
|
| 106 |
+
`beta_fast` (`float`, *optional*):
|
| 107 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
| 108 |
+
ramp function. If unspecified, it defaults to 32.
|
| 109 |
+
`beta_slow` (`float`, *optional*):
|
| 110 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
| 111 |
+
ramp function. If unspecified, it defaults to 1.
|
| 112 |
+
`short_factor` (`List[float]`, *optional*):
|
| 113 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<`original_max_position_embeddings`).
|
| 114 |
+
Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2
|
| 115 |
+
`long_factor` (`List[float]`, *optional*):
|
| 116 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<`original_max_position_embeddings`).
|
| 117 |
+
Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2
|
| 118 |
+
`low_freq_factor` (`float`, *optional*):
|
| 119 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
| 120 |
+
`high_freq_factor` (`float`, *optional*):
|
| 121 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
| 122 |
+
num_attention_heads (`int`, *optional*, defaults to 8):
|
| 123 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 124 |
+
num_key_value_heads (`int`, *optional*):
|
| 125 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention.
|
| 126 |
+
If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 127 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used.
|
| 128 |
+
When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group.
|
| 129 |
+
For more details checkout [this paper](https://arxiv.org/pdf/2305.13245.pdf).
|
| 130 |
+
If it is not specified, will default to `num_attention_heads`.
|
| 131 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
| 132 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
| 133 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 134 |
+
The dropout ratio for the attention probabilities.
|
| 135 |
+
mlp_bias (`bool`, *optional*, defaults to `False`):
|
| 136 |
+
Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
|
| 137 |
+
sliding_window (`int`, *optional*):
|
| 138 |
+
Sliding window attention window size. If not specified, will default to `None`.
|
| 139 |
+
keep_window_size (`int`, *optional*, defaults to 2048):
|
| 140 |
+
The window size of tokens that are not dynamically masked, and dynamic masking is only performed when the sequence length exceeds this value.
|
| 141 |
+
is_moe (`bool`, *optional*, defaults to `False`):
|
| 142 |
+
Whether to use the Cross Domain Mixture of Experts, if `True`, the MoE will inherit the MLP to initialize.
|
| 143 |
+
num_experts (`int`, *optional*, defaults to 16384):
|
| 144 |
+
Number of routed experts in the model. This is only used when `is_moe=True`.
|
| 145 |
+
num_experts_per_tok (`int`, *optional*, defaults to 64):
|
| 146 |
+
Number of selected experts to route per-token.
|
| 147 |
+
norm_topk_prob (`bool`, *optional*, defaults to `False`):
|
| 148 |
+
Whether to normalize the topk probabilities.
|
| 149 |
+
output_router_logits (`bool`, *optional*, defaults to `False`):
|
| 150 |
+
Whether or not the router logits should be returned by the model. Enabling this will also
|
| 151 |
+
allow the model to output the auxiliary loss, including load balancing loss and router z-loss.
|
| 152 |
+
router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
|
| 153 |
+
The aux loss factor for the total loss.
|
| 154 |
+
|
| 155 |
+
```python
|
| 156 |
+
>>> from transformers import DogeConfig, DogeModel
|
| 157 |
+
|
| 158 |
+
>>> # Initializing a Doge-320M style configuration
|
| 159 |
+
>>> configuration = DogeConfig()
|
| 160 |
+
|
| 161 |
+
>>> # Initializing a model from the Doge-320M style configuration
|
| 162 |
+
>>> model = DogeModel(configuration)
|
| 163 |
+
|
| 164 |
+
>>> # Accessing the model configuration
|
| 165 |
+
>>> configuration = model.config
|
| 166 |
+
```"""
|
| 167 |
+
|
| 168 |
+
model_type = "doge"
|
| 169 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 170 |
+
# Default tensor parallel plan for base model `DogeModel`
|
| 171 |
+
base_model_tp_plan = {
|
| 172 |
+
"layers.*.self_attn.q_proj": "colwise",
|
| 173 |
+
"layers.*.self_attn.k_proj": "colwise",
|
| 174 |
+
"layers.*.self_attn.v_proj": "colwise",
|
| 175 |
+
"layers.*.self_attn.dt_proj": "rowwise",
|
| 176 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
| 177 |
+
"layers.*.input_layernorm.weight": "sequence_parallel",
|
| 178 |
+
"layers.*.input_residual.weight": "sequence_parallel",
|
| 179 |
+
"layers.*.post_attention_layernorm.weight": "sequence_parallel",
|
| 180 |
+
"layers.*.post_attention_residual.weight": "sequence_parallel",
|
| 181 |
+
"norm.weight": "sequence_parallel",
|
| 182 |
+
"layers.*.mlp.gate_proj": "colwise",
|
| 183 |
+
"layers.*.mlp.up_proj": "colwise",
|
| 184 |
+
"layers.*.mlp.down_proj": "rowwise",
|
| 185 |
+
"layers.*.mlp.router_gate": "colwise_rep",
|
| 186 |
+
"layers.*.mlp.down_embed": "rowwise_rep",
|
| 187 |
+
"layers.*.mlp.up_embed": "rowwise_rep",
|
| 188 |
+
}
|
| 189 |
+
base_model_pp_plan = {
|
| 190 |
+
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
| 191 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
| 192 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
def __init__(
|
| 196 |
+
self,
|
| 197 |
+
vocab_size=32768,
|
| 198 |
+
hidden_size=1024,
|
| 199 |
+
intermediate_size=2048,
|
| 200 |
+
num_hidden_layers=32,
|
| 201 |
+
hidden_dropout=0.0,
|
| 202 |
+
hidden_act="silu",
|
| 203 |
+
initializer_range=0.02,
|
| 204 |
+
rms_norm_eps=1e-06,
|
| 205 |
+
use_cache=True,
|
| 206 |
+
tie_word_embeddings=False,
|
| 207 |
+
max_position_embeddings=2048,
|
| 208 |
+
rope_theta=10000.0,
|
| 209 |
+
rope_scaling=None,
|
| 210 |
+
num_attention_heads=8,
|
| 211 |
+
num_key_value_heads=None,
|
| 212 |
+
attention_bias=False,
|
| 213 |
+
attention_dropout=0.0,
|
| 214 |
+
mlp_bias=False,
|
| 215 |
+
sliding_window=None,
|
| 216 |
+
keep_window_size=2048,
|
| 217 |
+
is_moe=False,
|
| 218 |
+
num_experts=16384,
|
| 219 |
+
num_experts_per_tok=64,
|
| 220 |
+
norm_topk_prob=False,
|
| 221 |
+
output_router_logits=False,
|
| 222 |
+
router_aux_loss_coef=0.001,
|
| 223 |
+
**kwargs,
|
| 224 |
+
):
|
| 225 |
+
self.vocab_size = vocab_size
|
| 226 |
+
self.hidden_size = hidden_size
|
| 227 |
+
self.intermediate_size = intermediate_size
|
| 228 |
+
self.num_hidden_layers = num_hidden_layers
|
| 229 |
+
|
| 230 |
+
self.hidden_dropout = hidden_dropout
|
| 231 |
+
self.hidden_act = hidden_act
|
| 232 |
+
self.initializer_range = initializer_range
|
| 233 |
+
self.rms_norm_eps = rms_norm_eps
|
| 234 |
+
self.use_cache = use_cache
|
| 235 |
+
|
| 236 |
+
self.max_position_embeddings = max_position_embeddings
|
| 237 |
+
self.rope_theta = rope_theta
|
| 238 |
+
self.rope_scaling = rope_scaling
|
| 239 |
+
self.num_attention_heads = num_attention_heads
|
| 240 |
+
self.num_key_value_heads = num_key_value_heads
|
| 241 |
+
self.attention_bias = attention_bias
|
| 242 |
+
self.attention_dropout = attention_dropout
|
| 243 |
+
self.mlp_bias = mlp_bias
|
| 244 |
+
self.sliding_window = sliding_window
|
| 245 |
+
self.keep_window_size = keep_window_size
|
| 246 |
+
self.is_moe = is_moe
|
| 247 |
+
self.num_experts = num_experts
|
| 248 |
+
self.num_experts_per_tok = num_experts_per_tok
|
| 249 |
+
self.norm_topk_prob = norm_topk_prob
|
| 250 |
+
self.output_router_logits = output_router_logits
|
| 251 |
+
self.router_aux_loss_coef = router_aux_loss_coef
|
| 252 |
+
|
| 253 |
+
# Validate the correctness of rotary position embeddings parameters
|
| 254 |
+
# BC: if there is a 'type' field, copy it it to 'rope_type'.
|
| 255 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
| 256 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
| 257 |
+
rope_config_validation(self)
|
| 258 |
+
|
| 259 |
+
# for backward compatibility
|
| 260 |
+
if num_key_value_heads is None:
|
| 261 |
+
self.num_key_value_heads = num_attention_heads
|
| 262 |
+
|
| 263 |
+
super().__init__(
|
| 264 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 265 |
+
**kwargs,
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class DogeRMSNorm(LlamaRMSNorm):
|
| 270 |
+
pass
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
class DogeRotaryEmbedding(LlamaRotaryEmbedding):
|
| 274 |
+
pass
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def flex_attention_forward(
|
| 278 |
+
module: nn.Module,
|
| 279 |
+
query: torch.Tensor,
|
| 280 |
+
key: torch.Tensor,
|
| 281 |
+
value: torch.Tensor,
|
| 282 |
+
attention_mask: Union[torch.Tensor, "BlockMask"],
|
| 283 |
+
scaling: Optional[float] = None,
|
| 284 |
+
softcap: Optional[float] = None,
|
| 285 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 286 |
+
**kwargs,
|
| 287 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 288 |
+
block_mask = None
|
| 289 |
+
causal_mask = None
|
| 290 |
+
if isinstance(attention_mask, BlockMask):
|
| 291 |
+
block_mask = attention_mask
|
| 292 |
+
else:
|
| 293 |
+
causal_mask = attention_mask
|
| 294 |
+
|
| 295 |
+
if causal_mask is not None:
|
| 296 |
+
causal_mask = causal_mask[:, :, :, : key.shape[-2]]
|
| 297 |
+
|
| 298 |
+
def score_mod(score, batch_idx, head_idx, q_idx, kv_idx):
|
| 299 |
+
if softcap is not None:
|
| 300 |
+
score = softcap * torch.tanh(score / softcap)
|
| 301 |
+
if causal_mask is not None:
|
| 302 |
+
score = score + causal_mask[batch_idx][head_idx][q_idx][kv_idx]
|
| 303 |
+
if head_mask is not None:
|
| 304 |
+
score = score + head_mask[batch_idx][head_idx][0][0]
|
| 305 |
+
return score
|
| 306 |
+
|
| 307 |
+
attn_output, attention_weights = compile_friendly_flex_attention(
|
| 308 |
+
query,
|
| 309 |
+
key,
|
| 310 |
+
value,
|
| 311 |
+
score_mod=score_mod,
|
| 312 |
+
block_mask=block_mask,
|
| 313 |
+
enable_gqa=True,
|
| 314 |
+
scale=scaling,
|
| 315 |
+
# Last time checked on PyTorch == 2.5.1: Flex Attention always computes the lse regardless.
|
| 316 |
+
# For simplification, we thus always return it as no additional computations are introduced.
|
| 317 |
+
return_lse=True,
|
| 318 |
+
)
|
| 319 |
+
# lse is returned in float32
|
| 320 |
+
attention_weights = attention_weights.to(value.dtype)
|
| 321 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 322 |
+
|
| 323 |
+
return attn_output, attention_weights
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
ALL_ATTENTION_FUNCTIONS = AttentionInterface()
|
| 327 |
+
ALL_ATTENTION_FUNCTIONS["doge_flex_attention"] = flex_attention_forward
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class DogeAttention(nn.Module):
|
| 331 |
+
def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None):
|
| 332 |
+
super().__init__()
|
| 333 |
+
self.config = config
|
| 334 |
+
self.layer_idx = layer_idx
|
| 335 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 336 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 337 |
+
self.scaling = self.head_dim**-0.5
|
| 338 |
+
self.attention_dropout = config.attention_dropout
|
| 339 |
+
self.keep_window_size = config.keep_window_size
|
| 340 |
+
|
| 341 |
+
self.q_proj = nn.Linear(
|
| 342 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 343 |
+
)
|
| 344 |
+
self.k_proj = nn.Linear(
|
| 345 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 346 |
+
)
|
| 347 |
+
self.v_proj = nn.Linear(
|
| 348 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 349 |
+
)
|
| 350 |
+
# dynamic mask for the QK^T attention weights matrix
|
| 351 |
+
self.A = nn.Parameter(torch.zeros(config.num_key_value_heads))
|
| 352 |
+
self.dt_proj = nn.Linear(
|
| 353 |
+
config.num_key_value_heads * self.head_dim, config.num_key_value_heads, bias=config.attention_bias
|
| 354 |
+
)
|
| 355 |
+
self.o_proj = nn.Linear(
|
| 356 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 357 |
+
)
|
| 358 |
+
self.q_norm = DogeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 359 |
+
self.k_norm = DogeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 360 |
+
|
| 361 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 362 |
+
def forward(
|
| 363 |
+
self,
|
| 364 |
+
hidden_states: torch.Tensor,
|
| 365 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 366 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 367 |
+
past_key_values: Optional[Cache] = None,
|
| 368 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 369 |
+
**kwargs,
|
| 370 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
|
| 371 |
+
input_shape = hidden_states.shape[:-1]
|
| 372 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 373 |
+
|
| 374 |
+
query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 375 |
+
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 376 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 377 |
+
|
| 378 |
+
cos, sin = position_embeddings
|
| 379 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 380 |
+
|
| 381 |
+
if past_key_values is not None:
|
| 382 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 383 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 384 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 385 |
+
|
| 386 |
+
# calculate dynamic mask from value_states
|
| 387 |
+
dt_states = self.dt_proj(
|
| 388 |
+
value_states.transpose(1, 2).reshape(value_states.shape[0], value_states.shape[-2], -1)
|
| 389 |
+
)
|
| 390 |
+
dt_states = torch.exp(self.A * F.softplus(dt_states)).transpose(-1, -2)
|
| 391 |
+
attn_mask = self.prepare_dynamic_mask(
|
| 392 |
+
hidden_states=hidden_states,
|
| 393 |
+
dt_states=dt_states,
|
| 394 |
+
keep_window_size=self.keep_window_size,
|
| 395 |
+
attention_mask=attention_mask,
|
| 396 |
+
)
|
| 397 |
+
attn_mask = repeat_kv(attn_mask, self.num_key_value_groups)
|
| 398 |
+
|
| 399 |
+
attention_interface: Callable = eager_attention_forward
|
| 400 |
+
if self.config._attn_implementation != "eager":
|
| 401 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 402 |
+
|
| 403 |
+
attn_output, attn_weights = attention_interface(
|
| 404 |
+
self,
|
| 405 |
+
query_states,
|
| 406 |
+
key_states,
|
| 407 |
+
value_states,
|
| 408 |
+
attention_mask=attn_mask,
|
| 409 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 410 |
+
scaling=self.scaling,
|
| 411 |
+
**kwargs,
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 415 |
+
attn_output = self.o_proj(attn_output)
|
| 416 |
+
return attn_output, attn_weights
|
| 417 |
+
|
| 418 |
+
def prepare_dynamic_mask(
|
| 419 |
+
self,
|
| 420 |
+
hidden_states: torch.Tensor,
|
| 421 |
+
dt_states: torch.Tensor,
|
| 422 |
+
keep_window_size: int = 2048,
|
| 423 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 424 |
+
):
|
| 425 |
+
"""
|
| 426 |
+
The core idea of DMA is to calculate the dynamic attention mask to mask the tokens that should be masked, so as to form sparse attention.
|
| 427 |
+
|
| 428 |
+
Combine `dt_states` with `attention_mask` to generate the final `attn_mask`.
|
| 429 |
+
|
| 430 |
+
Args:
|
| 431 |
+
hidden_states (`torch.Tensor`): The input hidden_states, used to determine the minimum value of the current input precision.
|
| 432 |
+
dt_states (`torch.Tensor`): dt_states of shape `(batch_size, num_heads, key_sequence_length)`.
|
| 433 |
+
keep_window_size (`int`): The window size of tokens that are not dynamically masked, and dynamic masking is only performed when the sequence length exceeds this value.
|
| 434 |
+
attention_mask (`torch.Tensor`, *optional*): attention mask of shape `(batch_size, 1, query_sequence_length, key_sequence_length)`.
|
| 435 |
+
"""
|
| 436 |
+
min_dtype = torch.finfo(hidden_states.dtype).min
|
| 437 |
+
dtype = hidden_states.dtype
|
| 438 |
+
attn_mask = dt_states[:, :, None, :].expand(
|
| 439 |
+
-1, -1, hidden_states.shape[1], -1
|
| 440 |
+
) # [batch_size, num_heads, query_len, key_len]
|
| 441 |
+
if attention_mask is not None and not isinstance(attention_mask, BlockMask):
|
| 442 |
+
if attention_mask.dtype == torch.bool:
|
| 443 |
+
dtype = hidden_states.dtype
|
| 444 |
+
attention_mask = torch.where(
|
| 445 |
+
attention_mask, torch.tensor(0.0, device=attention_mask.device, dtype=dtype), min_dtype
|
| 446 |
+
)
|
| 447 |
+
attn_mask = attn_mask.masked_fill(attention_mask[:, :, :, : attn_mask.shape[-1]] != 0, min_dtype)
|
| 448 |
+
if attn_mask.shape[-1] > keep_window_size:
|
| 449 |
+
active_mask = torch.zeros_like(attn_mask, dtype=dtype, device=attn_mask.device)
|
| 450 |
+
topk_indices = torch.topk(attn_mask, keep_window_size, dim=-1, largest=True, sorted=False).indices
|
| 451 |
+
active_mask = active_mask.scatter(-1, topk_indices, 1.0)
|
| 452 |
+
attn_mask = attn_mask.masked_fill(active_mask == 0.0, min_dtype)
|
| 453 |
+
return attn_mask
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
class DogeMLP(LlamaMLP):
|
| 457 |
+
pass
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
class DogeCDMoE(nn.Module):
|
| 461 |
+
def __init__(self, config: DogeConfig):
|
| 462 |
+
super().__init__()
|
| 463 |
+
self.hidden_size = config.hidden_size
|
| 464 |
+
self.intermediate_size = config.intermediate_size
|
| 465 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 466 |
+
|
| 467 |
+
self.num_experts = config.num_experts
|
| 468 |
+
self.num_keys = math.floor(math.sqrt(self.num_experts))
|
| 469 |
+
self.top_k = config.num_experts_per_tok
|
| 470 |
+
self.norm_topk_prob = config.norm_topk_prob
|
| 471 |
+
|
| 472 |
+
# shared expert
|
| 473 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 474 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 475 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
| 476 |
+
|
| 477 |
+
# router gate for retrieval experts
|
| 478 |
+
self.router_gate = nn.Linear(self.hidden_size, self.num_keys * 2, bias=False)
|
| 479 |
+
|
| 480 |
+
# routed experts
|
| 481 |
+
self.down_embed = nn.Embedding(self.num_experts, self.hidden_size)
|
| 482 |
+
self.up_embed = nn.Embedding(self.num_experts, self.hidden_size)
|
| 483 |
+
|
| 484 |
+
def forward(
|
| 485 |
+
self,
|
| 486 |
+
hidden_states: torch.Tensor,
|
| 487 |
+
**kwargs,
|
| 488 |
+
) -> torch.Tensor:
|
| 489 |
+
bsz, seq_len, _ = hidden_states.shape
|
| 490 |
+
|
| 491 |
+
# get routing logits with router gate
|
| 492 |
+
router_logits = self.router_gate(hidden_states).view(2, bsz * seq_len, -1)
|
| 493 |
+
|
| 494 |
+
# get experts with the highest routing logits
|
| 495 |
+
(scores_x, scores_y), (indices_x, indices_y) = router_logits.topk(self.num_keys, dim=-1)
|
| 496 |
+
all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2)
|
| 497 |
+
all_indices = indices_x.unsqueeze(-1) * self.num_keys + indices_y.unsqueeze(-2)
|
| 498 |
+
all_scores = all_scores.view(*all_scores.shape[:-2], -1)
|
| 499 |
+
all_indices = all_indices.view(*all_indices.shape[:-2], -1)
|
| 500 |
+
scores, position_indices = all_scores.topk(self.top_k, dim=-1)
|
| 501 |
+
indices = all_indices.gather(-1, position_indices)
|
| 502 |
+
routing_weights = F.softmax(scores, dim=-1)
|
| 503 |
+
if self.norm_topk_prob:
|
| 504 |
+
routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
|
| 505 |
+
|
| 506 |
+
# mix routed experts states with shared expert states
|
| 507 |
+
down_embed = self.down_embed(indices)
|
| 508 |
+
up_embed = self.up_embed(indices)
|
| 509 |
+
experts_weights = torch.matmul(down_embed, hidden_states.view(bsz * seq_len, -1, 1)).view(bsz * seq_len, -1)
|
| 510 |
+
experts_weights = self.act_fn(experts_weights) * routing_weights
|
| 511 |
+
experts_states = torch.matmul(experts_weights.view(bsz * seq_len, 1, -1), up_embed).view(bsz, seq_len, -1)
|
| 512 |
+
hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
|
| 513 |
+
hidden_states = hidden_states + experts_states
|
| 514 |
+
return hidden_states, router_logits
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
class DogeDecoderLayer(GradientCheckpointingLayer):
|
| 518 |
+
def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None):
|
| 519 |
+
super().__init__()
|
| 520 |
+
self.hidden_dropout = config.hidden_dropout
|
| 521 |
+
|
| 522 |
+
self.input_layernorm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 523 |
+
self.self_attn = DogeAttention(config=config, layer_idx=layer_idx)
|
| 524 |
+
self.input_residual = nn.Parameter(torch.ones(config.hidden_size))
|
| 525 |
+
|
| 526 |
+
self.post_attention_layernorm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 527 |
+
self.mlp = DogeMLP(config) if not config.is_moe else DogeCDMoE(config)
|
| 528 |
+
self.post_attention_residual = nn.Parameter(torch.ones(config.hidden_size))
|
| 529 |
+
|
| 530 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 531 |
+
def forward(
|
| 532 |
+
self,
|
| 533 |
+
hidden_states: torch.Tensor,
|
| 534 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 535 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 536 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 537 |
+
past_key_values: Optional[tuple[torch.Tensor]] = None,
|
| 538 |
+
use_cache: Optional[bool] = False,
|
| 539 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 540 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 541 |
+
) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 542 |
+
# sequence transformation
|
| 543 |
+
residual = hidden_states
|
| 544 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 545 |
+
hidden_states, self_attn_weights = self.self_attn(
|
| 546 |
+
hidden_states=hidden_states,
|
| 547 |
+
position_embeddings=position_embeddings,
|
| 548 |
+
attention_mask=attention_mask,
|
| 549 |
+
position_ids=position_ids,
|
| 550 |
+
past_key_values=past_key_values,
|
| 551 |
+
use_cache=use_cache,
|
| 552 |
+
cache_position=cache_position,
|
| 553 |
+
**kwargs,
|
| 554 |
+
)
|
| 555 |
+
hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training)
|
| 556 |
+
hidden_states = self.input_residual * residual + hidden_states
|
| 557 |
+
|
| 558 |
+
# state transformation
|
| 559 |
+
residual = hidden_states
|
| 560 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 561 |
+
hidden_states = self.mlp(hidden_states)
|
| 562 |
+
hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training)
|
| 563 |
+
hidden_states = self.post_attention_residual * residual + hidden_states
|
| 564 |
+
|
| 565 |
+
return hidden_states
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
class DogePreTrainedModel(LlamaPreTrainedModel):
|
| 569 |
+
_supports_flash_attn = False
|
| 570 |
+
_can_compile_fullgraph = False
|
| 571 |
+
_can_record_outputs = {
|
| 572 |
+
"router_logits": OutputRecorder(DogeCDMoE, index=1),
|
| 573 |
+
"hidden_states": DogeDecoderLayer,
|
| 574 |
+
"attentions": DogeAttention,
|
| 575 |
+
}
|
| 576 |
+
|
| 577 |
+
def _init_weights(self, module):
|
| 578 |
+
"""Initialize the weights"""
|
| 579 |
+
LlamaPreTrainedModel._init_weights(module)
|
| 580 |
+
if isinstance(module, DogeAttention):
|
| 581 |
+
if hasattr(module, "A"):
|
| 582 |
+
module.A.data.zero_()
|
| 583 |
+
elif isinstance(module, DogeDecoderLayer):
|
| 584 |
+
if hasattr(module, "input_residual"):
|
| 585 |
+
module.input_residual.data.fill_(1.0)
|
| 586 |
+
if hasattr(module, "post_attention_residual"):
|
| 587 |
+
module.post_attention_residual.data.fill_(1.0)
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
class DogeModel(MixtralModel):
|
| 591 |
+
pass
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
def load_balancing_loss_func(
|
| 595 |
+
gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
|
| 596 |
+
num_experts: Optional[int] = None,
|
| 597 |
+
num_keys: Optional[int] = None,
|
| 598 |
+
top_k: int = 2,
|
| 599 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 600 |
+
) -> Union[torch.Tensor, int]:
|
| 601 |
+
r"""
|
| 602 |
+
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
|
| 603 |
+
|
| 604 |
+
See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
|
| 605 |
+
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
|
| 606 |
+
experts is too unbalanced.
|
| 607 |
+
|
| 608 |
+
Args:
|
| 609 |
+
gate_logits:
|
| 610 |
+
Logits from the `router_gate`, should be a tuple of model.config.num_hidden_layers tensors of
|
| 611 |
+
shape [2, batch_size * sequence_length, num_keys].
|
| 612 |
+
num_experts:
|
| 613 |
+
Number of experts
|
| 614 |
+
num_keys:
|
| 615 |
+
Number of keys
|
| 616 |
+
top_k:
|
| 617 |
+
The number of experts to route per-token, can be also interpreted as the `top-k` routing
|
| 618 |
+
parameter.
|
| 619 |
+
attention_mask (`torch.Tensor`, *optional*):
|
| 620 |
+
The attention_mask used in forward function
|
| 621 |
+
shape [batch_size X sequence_length] if not None.
|
| 622 |
+
|
| 623 |
+
Returns:
|
| 624 |
+
The auxiliary loss.
|
| 625 |
+
"""
|
| 626 |
+
if gate_logits is None or not isinstance(gate_logits, tuple):
|
| 627 |
+
return 0
|
| 628 |
+
|
| 629 |
+
compute_dtype = gate_logits[0].dtype
|
| 630 |
+
compute_device = gate_logits[0].device
|
| 631 |
+
all_expert_indices = []
|
| 632 |
+
all_routing_weights = []
|
| 633 |
+
|
| 634 |
+
for layer_gate_logits in gate_logits:
|
| 635 |
+
layer_gate_logits = layer_gate_logits.to(compute_device)
|
| 636 |
+
|
| 637 |
+
(scores_x, scores_y), (indices_x, indices_y) = layer_gate_logits.topk(num_keys, dim=-1)
|
| 638 |
+
|
| 639 |
+
all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2)
|
| 640 |
+
all_indices = indices_x.unsqueeze(-1) * num_keys + indices_y.unsqueeze(-2)
|
| 641 |
+
all_scores = all_scores.view(*all_scores.shape[:-2], -1)
|
| 642 |
+
all_indices = all_indices.view(*all_indices.shape[:-2], -1)
|
| 643 |
+
|
| 644 |
+
_, position_indices = all_scores.topk(top_k, dim=-1)
|
| 645 |
+
expert_indices = all_indices.gather(-1, position_indices)
|
| 646 |
+
|
| 647 |
+
routing_weights = F.softmax(all_scores, dim=-1)
|
| 648 |
+
|
| 649 |
+
all_expert_indices.append(expert_indices)
|
| 650 |
+
all_routing_weights.append(routing_weights)
|
| 651 |
+
all_expert_indices = torch.cat(all_expert_indices, dim=0)
|
| 652 |
+
all_routing_weights = torch.cat(all_routing_weights, dim=0)
|
| 653 |
+
|
| 654 |
+
if attention_mask is None:
|
| 655 |
+
# Compute the percentage of tokens routed to each experts
|
| 656 |
+
all_expert_indices = all_expert_indices.view(-1)
|
| 657 |
+
tokens_per_expert = torch.zeros(num_experts, dtype=compute_dtype, device=compute_device)
|
| 658 |
+
pad = torch.ones_like(all_expert_indices, dtype=compute_dtype, device=compute_device)
|
| 659 |
+
tokens_per_expert = tokens_per_expert.scatter_add_(0, all_expert_indices, pad) / all_expert_indices.shape[0]
|
| 660 |
+
|
| 661 |
+
# Compute the average probability of routing to these experts
|
| 662 |
+
router_prob_per_expert = torch.mean(all_routing_weights, dim=0)
|
| 663 |
+
else:
|
| 664 |
+
batch_size, sequence_length = attention_mask.shape
|
| 665 |
+
num_hidden_layers = len(gate_logits)
|
| 666 |
+
|
| 667 |
+
# Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
|
| 668 |
+
expert_attention_mask = (
|
| 669 |
+
attention_mask[None, :, :, None]
|
| 670 |
+
.expand((num_hidden_layers, batch_size, sequence_length, top_k))
|
| 671 |
+
.reshape(-1)
|
| 672 |
+
.to(compute_device)
|
| 673 |
+
)
|
| 674 |
+
all_expert_indices = all_expert_indices.view(-1)[expert_attention_mask.bool()]
|
| 675 |
+
|
| 676 |
+
# Compute the percentage of tokens routed to each experts
|
| 677 |
+
tokens_per_expert = torch.zeros(num_experts, dtype=compute_dtype, device=compute_device)
|
| 678 |
+
pad = torch.ones_like(all_expert_indices, dtype=compute_dtype, device=compute_device)
|
| 679 |
+
tokens_per_expert = tokens_per_expert.scatter_add_(0, all_expert_indices, pad) / torch.sum(
|
| 680 |
+
expert_attention_mask
|
| 681 |
+
)
|
| 682 |
+
|
| 683 |
+
# Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
|
| 684 |
+
router_per_expert_attention_mask = (
|
| 685 |
+
attention_mask[None, :, :, None]
|
| 686 |
+
.expand((num_hidden_layers, batch_size, sequence_length, num_experts))
|
| 687 |
+
.reshape(-1, num_experts)
|
| 688 |
+
.to(compute_device)
|
| 689 |
+
)
|
| 690 |
+
|
| 691 |
+
# Compute the average probability of routing to these experts
|
| 692 |
+
router_prob_per_expert = torch.sum(all_routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
|
| 693 |
+
router_per_expert_attention_mask, dim=0
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert)
|
| 697 |
+
return overall_loss * num_experts
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
class DogeForCausalLM(MixtralForCausalLM):
|
| 701 |
+
def __init__(self, config):
|
| 702 |
+
super().__init__(config)
|
| 703 |
+
self.model = DogeModel(config)
|
| 704 |
+
self.num_experts = config.num_experts
|
| 705 |
+
|
| 706 |
+
def forward(
|
| 707 |
+
self,
|
| 708 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 709 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 710 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 711 |
+
past_key_values: Optional[list[torch.FloatTensor]] = None,
|
| 712 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 713 |
+
labels: Optional[torch.LongTensor] = None,
|
| 714 |
+
use_cache: Optional[bool] = None,
|
| 715 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 716 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 717 |
+
output_router_logits: Optional[bool] = None,
|
| 718 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 719 |
+
) -> MoeCausalLMOutputWithPast:
|
| 720 |
+
r"""
|
| 721 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 722 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 723 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 724 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 725 |
+
|
| 726 |
+
Example:
|
| 727 |
+
|
| 728 |
+
```python
|
| 729 |
+
>>> from transformers import AutoTokenizer, DogeForCausalLM
|
| 730 |
+
|
| 731 |
+
>>> model = DogeForCausalLM.from_pretrained("SmallDoge/Doge-320M")
|
| 732 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("SmallDoge/Doge-320M")
|
| 733 |
+
|
| 734 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 735 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 736 |
+
|
| 737 |
+
>>> # Generate
|
| 738 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 739 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 740 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 741 |
+
```"""
|
| 742 |
+
output_router_logits = (
|
| 743 |
+
output_router_logits if output_router_logits is not None else self.config.output_router_logits
|
| 744 |
+
)
|
| 745 |
+
|
| 746 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 747 |
+
outputs: MoeModelOutputWithPast = self.model(
|
| 748 |
+
input_ids=input_ids,
|
| 749 |
+
attention_mask=attention_mask,
|
| 750 |
+
position_ids=position_ids,
|
| 751 |
+
past_key_values=past_key_values,
|
| 752 |
+
inputs_embeds=inputs_embeds,
|
| 753 |
+
use_cache=use_cache,
|
| 754 |
+
cache_position=cache_position,
|
| 755 |
+
**kwargs,
|
| 756 |
+
)
|
| 757 |
+
|
| 758 |
+
hidden_states = outputs.last_hidden_state
|
| 759 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 760 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 761 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 762 |
+
|
| 763 |
+
loss = None
|
| 764 |
+
if labels is not None:
|
| 765 |
+
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
|
| 766 |
+
|
| 767 |
+
aux_loss = None
|
| 768 |
+
if output_router_logits:
|
| 769 |
+
aux_loss = load_balancing_loss_func(
|
| 770 |
+
outputs.router_logits,
|
| 771 |
+
self.num_experts,
|
| 772 |
+
math.floor(math.sqrt(self.num_experts)),
|
| 773 |
+
self.num_experts_per_tok,
|
| 774 |
+
attention_mask,
|
| 775 |
+
)
|
| 776 |
+
if labels is not None:
|
| 777 |
+
loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
|
| 778 |
+
|
| 779 |
+
return MoeCausalLMOutputWithPast(
|
| 780 |
+
loss=loss,
|
| 781 |
+
aux_loss=aux_loss,
|
| 782 |
+
logits=logits,
|
| 783 |
+
past_key_values=outputs.past_key_values,
|
| 784 |
+
hidden_states=outputs.hidden_states,
|
| 785 |
+
attentions=outputs.attentions,
|
| 786 |
+
router_logits=outputs.router_logits,
|
| 787 |
+
)
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
class DogeForSequenceClassification(LlamaForSequenceClassification):
|
| 791 |
+
pass
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
__all__ = [
|
| 795 |
+
"DogeConfig",
|
| 796 |
+
"DogeForCausalLM",
|
| 797 |
+
"DogeModel",
|
| 798 |
+
"DogePreTrainedModel",
|
| 799 |
+
"DogeForSequenceClassification",
|
| 800 |
+
]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/donut/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_donut_swin import *
|
| 22 |
+
from .feature_extraction_donut import *
|
| 23 |
+
from .image_processing_donut import *
|
| 24 |
+
from .image_processing_donut_fast import *
|
| 25 |
+
from .modeling_donut_swin import *
|
| 26 |
+
from .processing_donut import *
|
| 27 |
+
else:
|
| 28 |
+
import sys
|
| 29 |
+
|
| 30 |
+
_file = globals()["__file__"]
|
| 31 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/donut/configuration_donut_swin.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Donut Swin Transformer model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class DonutSwinConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`DonutSwinModel`]. It is used to instantiate a
|
| 27 |
+
Donut model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 28 |
+
with the defaults will yield a similar configuration to that of the Donut
|
| 29 |
+
[naver-clova-ix/donut-base](https://huggingface.co/naver-clova-ix/donut-base) architecture.
|
| 30 |
+
|
| 31 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 32 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 36 |
+
The size (resolution) of each image.
|
| 37 |
+
patch_size (`int`, *optional*, defaults to 4):
|
| 38 |
+
The size (resolution) of each patch.
|
| 39 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 40 |
+
The number of input channels.
|
| 41 |
+
embed_dim (`int`, *optional*, defaults to 96):
|
| 42 |
+
Dimensionality of patch embedding.
|
| 43 |
+
depths (`list(int)`, *optional*, defaults to `[2, 2, 6, 2]`):
|
| 44 |
+
Depth of each layer in the Transformer encoder.
|
| 45 |
+
num_heads (`list(int)`, *optional*, defaults to `[3, 6, 12, 24]`):
|
| 46 |
+
Number of attention heads in each layer of the Transformer encoder.
|
| 47 |
+
window_size (`int`, *optional*, defaults to 7):
|
| 48 |
+
Size of windows.
|
| 49 |
+
mlp_ratio (`float`, *optional*, defaults to 4.0):
|
| 50 |
+
Ratio of MLP hidden dimensionality to embedding dimensionality.
|
| 51 |
+
qkv_bias (`bool`, *optional*, defaults to `True`):
|
| 52 |
+
Whether or not a learnable bias should be added to the queries, keys and values.
|
| 53 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 54 |
+
The dropout probability for all fully connected layers in the embeddings and encoder.
|
| 55 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 56 |
+
The dropout ratio for the attention probabilities.
|
| 57 |
+
drop_path_rate (`float`, *optional*, defaults to 0.1):
|
| 58 |
+
Stochastic depth rate.
|
| 59 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 60 |
+
The non-linear activation function (function or string) in the encoder. If string, `"gelu"`, `"relu"`,
|
| 61 |
+
`"selu"` and `"gelu_new"` are supported.
|
| 62 |
+
use_absolute_embeddings (`bool`, *optional*, defaults to `False`):
|
| 63 |
+
Whether or not to add absolute position embeddings to the patch embeddings.
|
| 64 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 65 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 66 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 67 |
+
The epsilon used by the layer normalization layers.
|
| 68 |
+
|
| 69 |
+
Example:
|
| 70 |
+
|
| 71 |
+
```python
|
| 72 |
+
>>> from transformers import DonutSwinConfig, DonutSwinModel
|
| 73 |
+
|
| 74 |
+
>>> # Initializing a Donut naver-clova-ix/donut-base style configuration
|
| 75 |
+
>>> configuration = DonutSwinConfig()
|
| 76 |
+
|
| 77 |
+
>>> # Randomly initializing a model from the naver-clova-ix/donut-base style configuration
|
| 78 |
+
>>> model = DonutSwinModel(configuration)
|
| 79 |
+
|
| 80 |
+
>>> # Accessing the model configuration
|
| 81 |
+
>>> configuration = model.config
|
| 82 |
+
```"""
|
| 83 |
+
|
| 84 |
+
model_type = "donut-swin"
|
| 85 |
+
|
| 86 |
+
attribute_map = {
|
| 87 |
+
"num_attention_heads": "num_heads",
|
| 88 |
+
"num_hidden_layers": "num_layers",
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
def __init__(
|
| 92 |
+
self,
|
| 93 |
+
image_size=224,
|
| 94 |
+
patch_size=4,
|
| 95 |
+
num_channels=3,
|
| 96 |
+
embed_dim=96,
|
| 97 |
+
depths=[2, 2, 6, 2],
|
| 98 |
+
num_heads=[3, 6, 12, 24],
|
| 99 |
+
window_size=7,
|
| 100 |
+
mlp_ratio=4.0,
|
| 101 |
+
qkv_bias=True,
|
| 102 |
+
hidden_dropout_prob=0.0,
|
| 103 |
+
attention_probs_dropout_prob=0.0,
|
| 104 |
+
drop_path_rate=0.1,
|
| 105 |
+
hidden_act="gelu",
|
| 106 |
+
use_absolute_embeddings=False,
|
| 107 |
+
initializer_range=0.02,
|
| 108 |
+
layer_norm_eps=1e-5,
|
| 109 |
+
**kwargs,
|
| 110 |
+
):
|
| 111 |
+
super().__init__(**kwargs)
|
| 112 |
+
|
| 113 |
+
self.image_size = image_size
|
| 114 |
+
self.patch_size = patch_size
|
| 115 |
+
self.num_channels = num_channels
|
| 116 |
+
self.embed_dim = embed_dim
|
| 117 |
+
self.depths = depths
|
| 118 |
+
self.num_layers = len(depths)
|
| 119 |
+
self.num_heads = num_heads
|
| 120 |
+
self.window_size = window_size
|
| 121 |
+
self.mlp_ratio = mlp_ratio
|
| 122 |
+
self.qkv_bias = qkv_bias
|
| 123 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 124 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 125 |
+
self.drop_path_rate = drop_path_rate
|
| 126 |
+
self.hidden_act = hidden_act
|
| 127 |
+
self.use_absolute_embeddings = use_absolute_embeddings
|
| 128 |
+
self.layer_norm_eps = layer_norm_eps
|
| 129 |
+
self.initializer_range = initializer_range
|
| 130 |
+
# we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
|
| 131 |
+
# this indicates the channel dimension after the last stage of the model
|
| 132 |
+
self.hidden_size = int(embed_dim * 2 ** (len(depths) - 1))
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
__all__ = ["DonutSwinConfig"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/donut/convert_donut_to_pytorch.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert Donut checkpoints using the original `donut-python` library. URL: https://github.com/clovaai/donut"""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from datasets import load_dataset
|
| 21 |
+
from donut import DonutModel
|
| 22 |
+
|
| 23 |
+
from transformers import (
|
| 24 |
+
DonutImageProcessor,
|
| 25 |
+
DonutProcessor,
|
| 26 |
+
DonutSwinConfig,
|
| 27 |
+
DonutSwinModel,
|
| 28 |
+
MBartConfig,
|
| 29 |
+
MBartForCausalLM,
|
| 30 |
+
VisionEncoderDecoderModel,
|
| 31 |
+
XLMRobertaTokenizerFast,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def get_configs(model):
|
| 36 |
+
original_config = model.config
|
| 37 |
+
|
| 38 |
+
encoder_config = DonutSwinConfig(
|
| 39 |
+
image_size=original_config.input_size,
|
| 40 |
+
patch_size=4,
|
| 41 |
+
depths=original_config.encoder_layer,
|
| 42 |
+
num_heads=[4, 8, 16, 32],
|
| 43 |
+
window_size=original_config.window_size,
|
| 44 |
+
embed_dim=128,
|
| 45 |
+
)
|
| 46 |
+
decoder_config = MBartConfig(
|
| 47 |
+
is_decoder=True,
|
| 48 |
+
is_encoder_decoder=False,
|
| 49 |
+
add_cross_attention=True,
|
| 50 |
+
decoder_layers=original_config.decoder_layer,
|
| 51 |
+
max_position_embeddings=original_config.max_position_embeddings,
|
| 52 |
+
vocab_size=len(
|
| 53 |
+
model.decoder.tokenizer
|
| 54 |
+
), # several special tokens are added to the vocab of XLMRobertaTokenizer, see repo on the hub (added_tokens.json)
|
| 55 |
+
scale_embedding=True,
|
| 56 |
+
add_final_layer_norm=True,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
return encoder_config, decoder_config
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def rename_key(name):
|
| 63 |
+
if "encoder.model" in name:
|
| 64 |
+
name = name.replace("encoder.model", "encoder")
|
| 65 |
+
if "decoder.model" in name:
|
| 66 |
+
name = name.replace("decoder.model", "decoder")
|
| 67 |
+
if "patch_embed.proj" in name:
|
| 68 |
+
name = name.replace("patch_embed.proj", "embeddings.patch_embeddings.projection")
|
| 69 |
+
if "patch_embed.norm" in name:
|
| 70 |
+
name = name.replace("patch_embed.norm", "embeddings.norm")
|
| 71 |
+
if name.startswith("encoder"):
|
| 72 |
+
if "layers" in name:
|
| 73 |
+
name = "encoder." + name
|
| 74 |
+
if "attn.proj" in name:
|
| 75 |
+
name = name.replace("attn.proj", "attention.output.dense")
|
| 76 |
+
if "attn" in name and "mask" not in name:
|
| 77 |
+
name = name.replace("attn", "attention.self")
|
| 78 |
+
if "norm1" in name:
|
| 79 |
+
name = name.replace("norm1", "layernorm_before")
|
| 80 |
+
if "norm2" in name:
|
| 81 |
+
name = name.replace("norm2", "layernorm_after")
|
| 82 |
+
if "mlp.fc1" in name:
|
| 83 |
+
name = name.replace("mlp.fc1", "intermediate.dense")
|
| 84 |
+
if "mlp.fc2" in name:
|
| 85 |
+
name = name.replace("mlp.fc2", "output.dense")
|
| 86 |
+
|
| 87 |
+
if name == "encoder.norm.weight":
|
| 88 |
+
name = "encoder.layernorm.weight"
|
| 89 |
+
if name == "encoder.norm.bias":
|
| 90 |
+
name = "encoder.layernorm.bias"
|
| 91 |
+
|
| 92 |
+
return name
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def convert_state_dict(orig_state_dict, model):
|
| 96 |
+
for key in orig_state_dict.copy():
|
| 97 |
+
val = orig_state_dict.pop(key)
|
| 98 |
+
|
| 99 |
+
if "qkv" in key:
|
| 100 |
+
key_split = key.split(".")
|
| 101 |
+
layer_num = int(key_split[3])
|
| 102 |
+
block_num = int(key_split[5])
|
| 103 |
+
dim = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size
|
| 104 |
+
|
| 105 |
+
if "weight" in key:
|
| 106 |
+
orig_state_dict[
|
| 107 |
+
f"encoder.encoder.layers.{layer_num}.blocks.{block_num}.attention.self.query.weight"
|
| 108 |
+
] = val[:dim, :]
|
| 109 |
+
orig_state_dict[f"encoder.encoder.layers.{layer_num}.blocks.{block_num}.attention.self.key.weight"] = (
|
| 110 |
+
val[dim : dim * 2, :]
|
| 111 |
+
)
|
| 112 |
+
orig_state_dict[
|
| 113 |
+
f"encoder.encoder.layers.{layer_num}.blocks.{block_num}.attention.self.value.weight"
|
| 114 |
+
] = val[-dim:, :]
|
| 115 |
+
else:
|
| 116 |
+
orig_state_dict[f"encoder.encoder.layers.{layer_num}.blocks.{block_num}.attention.self.query.bias"] = (
|
| 117 |
+
val[:dim]
|
| 118 |
+
)
|
| 119 |
+
orig_state_dict[f"encoder.encoder.layers.{layer_num}.blocks.{block_num}.attention.self.key.bias"] = (
|
| 120 |
+
val[dim : dim * 2]
|
| 121 |
+
)
|
| 122 |
+
orig_state_dict[f"encoder.encoder.layers.{layer_num}.blocks.{block_num}.attention.self.value.bias"] = (
|
| 123 |
+
val[-dim:]
|
| 124 |
+
)
|
| 125 |
+
elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]:
|
| 126 |
+
# HuggingFace implementation doesn't use attn_mask buffer
|
| 127 |
+
# and model doesn't use final LayerNorms for the encoder
|
| 128 |
+
pass
|
| 129 |
+
else:
|
| 130 |
+
orig_state_dict[rename_key(key)] = val
|
| 131 |
+
|
| 132 |
+
return orig_state_dict
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def convert_donut_checkpoint(model_name, pytorch_dump_folder_path=None, push_to_hub=False):
|
| 136 |
+
# load original model
|
| 137 |
+
original_model = DonutModel.from_pretrained(model_name).eval()
|
| 138 |
+
|
| 139 |
+
# load HuggingFace model
|
| 140 |
+
encoder_config, decoder_config = get_configs(original_model)
|
| 141 |
+
encoder = DonutSwinModel(encoder_config)
|
| 142 |
+
decoder = MBartForCausalLM(decoder_config)
|
| 143 |
+
model = VisionEncoderDecoderModel(encoder=encoder, decoder=decoder)
|
| 144 |
+
model.eval()
|
| 145 |
+
|
| 146 |
+
state_dict = original_model.state_dict()
|
| 147 |
+
new_state_dict = convert_state_dict(state_dict, model)
|
| 148 |
+
model.load_state_dict(new_state_dict)
|
| 149 |
+
|
| 150 |
+
# verify results on scanned document
|
| 151 |
+
dataset = load_dataset("hf-internal-testing/example-documents") # no-script
|
| 152 |
+
image = dataset["test"][0]["image"].convert("RGB")
|
| 153 |
+
|
| 154 |
+
tokenizer = XLMRobertaTokenizerFast.from_pretrained(model_name, from_slow=True)
|
| 155 |
+
image_processor = DonutImageProcessor(
|
| 156 |
+
do_align_long_axis=original_model.config.align_long_axis, size=original_model.config.input_size[::-1]
|
| 157 |
+
)
|
| 158 |
+
processor = DonutProcessor(image_processor, tokenizer)
|
| 159 |
+
pixel_values = processor(image, return_tensors="pt").pixel_values
|
| 160 |
+
|
| 161 |
+
if model_name == "naver-clova-ix/donut-base-finetuned-docvqa":
|
| 162 |
+
task_prompt = "<s_docvqa><s_question>{user_input}</s_question><s_answer>"
|
| 163 |
+
question = "When is the coffee break?"
|
| 164 |
+
task_prompt = task_prompt.replace("{user_input}", question)
|
| 165 |
+
elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip":
|
| 166 |
+
task_prompt = "<s_rvlcdip>"
|
| 167 |
+
elif model_name in [
|
| 168 |
+
"naver-clova-ix/donut-base-finetuned-cord-v1",
|
| 169 |
+
"naver-clova-ix/donut-base-finetuned-cord-v1-2560",
|
| 170 |
+
]:
|
| 171 |
+
task_prompt = "<s_cord>"
|
| 172 |
+
elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2":
|
| 173 |
+
task_prompt = "s_cord-v2>"
|
| 174 |
+
elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket":
|
| 175 |
+
task_prompt = "<s_zhtrainticket>"
|
| 176 |
+
elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]:
|
| 177 |
+
# use a random prompt
|
| 178 |
+
task_prompt = "hello world"
|
| 179 |
+
else:
|
| 180 |
+
raise ValueError("Model name not supported")
|
| 181 |
+
prompt_tensors = original_model.decoder.tokenizer(task_prompt, add_special_tokens=False, return_tensors="pt")[
|
| 182 |
+
"input_ids"
|
| 183 |
+
]
|
| 184 |
+
|
| 185 |
+
original_patch_embed = original_model.encoder.model.patch_embed(pixel_values)
|
| 186 |
+
patch_embeddings, _ = model.encoder.embeddings(pixel_values)
|
| 187 |
+
assert torch.allclose(original_patch_embed, patch_embeddings, atol=1e-3)
|
| 188 |
+
|
| 189 |
+
# verify encoder hidden states
|
| 190 |
+
original_last_hidden_state = original_model.encoder(pixel_values)
|
| 191 |
+
last_hidden_state = model.encoder(pixel_values).last_hidden_state
|
| 192 |
+
assert torch.allclose(original_last_hidden_state, last_hidden_state, atol=1e-2)
|
| 193 |
+
|
| 194 |
+
# verify decoder hidden states
|
| 195 |
+
original_logits = original_model(pixel_values, prompt_tensors, None).logits
|
| 196 |
+
logits = model(pixel_values, decoder_input_ids=prompt_tensors).logits
|
| 197 |
+
assert torch.allclose(original_logits, logits, atol=1e-3)
|
| 198 |
+
print("Looks ok!")
|
| 199 |
+
|
| 200 |
+
if pytorch_dump_folder_path is not None:
|
| 201 |
+
print(f"Saving model and processor to {pytorch_dump_folder_path}")
|
| 202 |
+
model.save_pretrained(pytorch_dump_folder_path)
|
| 203 |
+
processor.save_pretrained(pytorch_dump_folder_path)
|
| 204 |
+
|
| 205 |
+
if push_to_hub:
|
| 206 |
+
model.push_to_hub("nielsr/" + model_name.split("/")[-1], commit_message="Update model")
|
| 207 |
+
processor.push_to_hub("nielsr/" + model_name.split("/")[-1], commit_message="Update model")
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
if __name__ == "__main__":
|
| 211 |
+
parser = argparse.ArgumentParser()
|
| 212 |
+
# Required parameters
|
| 213 |
+
parser.add_argument(
|
| 214 |
+
"--model_name",
|
| 215 |
+
default="naver-clova-ix/donut-base-finetuned-docvqa",
|
| 216 |
+
required=False,
|
| 217 |
+
type=str,
|
| 218 |
+
help="Name of the original model you'd like to convert.",
|
| 219 |
+
)
|
| 220 |
+
parser.add_argument(
|
| 221 |
+
"--pytorch_dump_folder_path",
|
| 222 |
+
default=None,
|
| 223 |
+
required=False,
|
| 224 |
+
type=str,
|
| 225 |
+
help="Path to the output PyTorch model directory.",
|
| 226 |
+
)
|
| 227 |
+
parser.add_argument(
|
| 228 |
+
"--push_to_hub",
|
| 229 |
+
action="store_true",
|
| 230 |
+
help="Whether or not to push the converted model and processor to the 🤗 hub.",
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
args = parser.parse_args()
|
| 234 |
+
convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/donut/feature_extraction_donut.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Feature extractor class for Donut."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
|
| 19 |
+
from ...utils import logging
|
| 20 |
+
from ...utils.import_utils import requires
|
| 21 |
+
from .image_processing_donut import DonutImageProcessor
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@requires(backends=("vision",))
|
| 28 |
+
class DonutFeatureExtractor(DonutImageProcessor):
|
| 29 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 30 |
+
warnings.warn(
|
| 31 |
+
"The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
|
| 32 |
+
" use DonutImageProcessor instead.",
|
| 33 |
+
FutureWarning,
|
| 34 |
+
)
|
| 35 |
+
super().__init__(*args, **kwargs)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
__all__ = ["DonutFeatureExtractor"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/donut/image_processing_donut.py
ADDED
|
@@ -0,0 +1,477 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Image processor class for Donut."""
|
| 16 |
+
|
| 17 |
+
from typing import Optional, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
| 22 |
+
from ...image_transforms import (
|
| 23 |
+
convert_to_rgb,
|
| 24 |
+
get_resize_output_image_size,
|
| 25 |
+
pad,
|
| 26 |
+
resize,
|
| 27 |
+
to_channel_dimension_format,
|
| 28 |
+
)
|
| 29 |
+
from ...image_utils import (
|
| 30 |
+
IMAGENET_STANDARD_MEAN,
|
| 31 |
+
IMAGENET_STANDARD_STD,
|
| 32 |
+
ChannelDimension,
|
| 33 |
+
ImageInput,
|
| 34 |
+
PILImageResampling,
|
| 35 |
+
get_image_size,
|
| 36 |
+
infer_channel_dimension_format,
|
| 37 |
+
is_scaled_image,
|
| 38 |
+
make_list_of_images,
|
| 39 |
+
to_numpy_array,
|
| 40 |
+
valid_images,
|
| 41 |
+
validate_preprocess_arguments,
|
| 42 |
+
)
|
| 43 |
+
from ...utils import TensorType, filter_out_non_signature_kwargs, logging
|
| 44 |
+
from ...utils.import_utils import is_vision_available, requires
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
logger = logging.get_logger(__name__)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
if is_vision_available():
|
| 51 |
+
import PIL
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@requires(backends=("vision",))
|
| 55 |
+
class DonutImageProcessor(BaseImageProcessor):
|
| 56 |
+
r"""
|
| 57 |
+
Constructs a Donut image processor.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 61 |
+
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
|
| 62 |
+
`do_resize` in the `preprocess` method.
|
| 63 |
+
size (`dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
|
| 64 |
+
Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with
|
| 65 |
+
the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess`
|
| 66 |
+
method.
|
| 67 |
+
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
|
| 68 |
+
Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
|
| 69 |
+
do_thumbnail (`bool`, *optional*, defaults to `True`):
|
| 70 |
+
Whether to resize the image using thumbnail method.
|
| 71 |
+
do_align_long_axis (`bool`, *optional*, defaults to `False`):
|
| 72 |
+
Whether to align the long axis of the image with the long axis of `size` by rotating by 90 degrees.
|
| 73 |
+
do_pad (`bool`, *optional*, defaults to `True`):
|
| 74 |
+
Whether to pad the image. If `random_padding` is set to `True` in `preprocess`, each image is padded with a
|
| 75 |
+
random amount of padding on each size, up to the largest image size in the batch. Otherwise, all images are
|
| 76 |
+
padded to the largest image size in the batch.
|
| 77 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 78 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
|
| 79 |
+
the `preprocess` method.
|
| 80 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
| 81 |
+
Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
|
| 82 |
+
method.
|
| 83 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 84 |
+
Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
|
| 85 |
+
image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
|
| 86 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
| 87 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
| 88 |
+
image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
|
| 89 |
+
Image standard deviation.
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
model_input_names = ["pixel_values"]
|
| 93 |
+
|
| 94 |
+
def __init__(
|
| 95 |
+
self,
|
| 96 |
+
do_resize: bool = True,
|
| 97 |
+
size: Optional[dict[str, int]] = None,
|
| 98 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 99 |
+
do_thumbnail: bool = True,
|
| 100 |
+
do_align_long_axis: bool = False,
|
| 101 |
+
do_pad: bool = True,
|
| 102 |
+
do_rescale: bool = True,
|
| 103 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 104 |
+
do_normalize: bool = True,
|
| 105 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 106 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 107 |
+
**kwargs,
|
| 108 |
+
) -> None:
|
| 109 |
+
super().__init__(**kwargs)
|
| 110 |
+
|
| 111 |
+
size = size if size is not None else {"height": 2560, "width": 1920}
|
| 112 |
+
if isinstance(size, (tuple, list)):
|
| 113 |
+
# The previous feature extractor size parameter was in (width, height) format
|
| 114 |
+
size = size[::-1]
|
| 115 |
+
size = get_size_dict(size)
|
| 116 |
+
|
| 117 |
+
self.do_resize = do_resize
|
| 118 |
+
self.size = size
|
| 119 |
+
self.resample = resample
|
| 120 |
+
self.do_thumbnail = do_thumbnail
|
| 121 |
+
self.do_align_long_axis = do_align_long_axis
|
| 122 |
+
self.do_pad = do_pad
|
| 123 |
+
self.do_rescale = do_rescale
|
| 124 |
+
self.rescale_factor = rescale_factor
|
| 125 |
+
self.do_normalize = do_normalize
|
| 126 |
+
self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
|
| 127 |
+
self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
|
| 128 |
+
|
| 129 |
+
def align_long_axis(
|
| 130 |
+
self,
|
| 131 |
+
image: np.ndarray,
|
| 132 |
+
size: dict[str, int],
|
| 133 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 134 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 135 |
+
) -> np.ndarray:
|
| 136 |
+
"""
|
| 137 |
+
Align the long axis of the image to the longest axis of the specified size.
|
| 138 |
+
|
| 139 |
+
Args:
|
| 140 |
+
image (`np.ndarray`):
|
| 141 |
+
The image to be aligned.
|
| 142 |
+
size (`dict[str, int]`):
|
| 143 |
+
The size `{"height": h, "width": w}` to align the long axis to.
|
| 144 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 145 |
+
The data format of the output image. If unset, the same format as the input image is used.
|
| 146 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 147 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 148 |
+
|
| 149 |
+
Returns:
|
| 150 |
+
`np.ndarray`: The aligned image.
|
| 151 |
+
"""
|
| 152 |
+
input_height, input_width = get_image_size(image, channel_dim=input_data_format)
|
| 153 |
+
output_height, output_width = size["height"], size["width"]
|
| 154 |
+
|
| 155 |
+
if input_data_format is None:
|
| 156 |
+
# We assume that all images have the same channel dimension format.
|
| 157 |
+
input_data_format = infer_channel_dimension_format(image)
|
| 158 |
+
|
| 159 |
+
if input_data_format == ChannelDimension.LAST:
|
| 160 |
+
rot_axes = (0, 1)
|
| 161 |
+
elif input_data_format == ChannelDimension.FIRST:
|
| 162 |
+
rot_axes = (1, 2)
|
| 163 |
+
else:
|
| 164 |
+
raise ValueError(f"Unsupported data format: {input_data_format}")
|
| 165 |
+
|
| 166 |
+
if (output_width < output_height and input_width > input_height) or (
|
| 167 |
+
output_width > output_height and input_width < input_height
|
| 168 |
+
):
|
| 169 |
+
image = np.rot90(image, 3, axes=rot_axes)
|
| 170 |
+
|
| 171 |
+
if data_format is not None:
|
| 172 |
+
image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
| 173 |
+
|
| 174 |
+
return image
|
| 175 |
+
|
| 176 |
+
def pad_image(
|
| 177 |
+
self,
|
| 178 |
+
image: np.ndarray,
|
| 179 |
+
size: dict[str, int],
|
| 180 |
+
random_padding: bool = False,
|
| 181 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 182 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 183 |
+
) -> np.ndarray:
|
| 184 |
+
"""
|
| 185 |
+
Pad the image to the specified size.
|
| 186 |
+
|
| 187 |
+
Args:
|
| 188 |
+
image (`np.ndarray`):
|
| 189 |
+
The image to be padded.
|
| 190 |
+
size (`dict[str, int]`):
|
| 191 |
+
The size `{"height": h, "width": w}` to pad the image to.
|
| 192 |
+
random_padding (`bool`, *optional*, defaults to `False`):
|
| 193 |
+
Whether to use random padding or not.
|
| 194 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 195 |
+
The data format of the output image. If unset, the same format as the input image is used.
|
| 196 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 197 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 198 |
+
"""
|
| 199 |
+
output_height, output_width = size["height"], size["width"]
|
| 200 |
+
input_height, input_width = get_image_size(image, channel_dim=input_data_format)
|
| 201 |
+
|
| 202 |
+
delta_width = output_width - input_width
|
| 203 |
+
delta_height = output_height - input_height
|
| 204 |
+
|
| 205 |
+
if random_padding:
|
| 206 |
+
pad_top = np.random.randint(low=0, high=delta_height + 1)
|
| 207 |
+
pad_left = np.random.randint(low=0, high=delta_width + 1)
|
| 208 |
+
else:
|
| 209 |
+
pad_top = delta_height // 2
|
| 210 |
+
pad_left = delta_width // 2
|
| 211 |
+
|
| 212 |
+
pad_bottom = delta_height - pad_top
|
| 213 |
+
pad_right = delta_width - pad_left
|
| 214 |
+
|
| 215 |
+
padding = ((pad_top, pad_bottom), (pad_left, pad_right))
|
| 216 |
+
return pad(image, padding, data_format=data_format, input_data_format=input_data_format)
|
| 217 |
+
|
| 218 |
+
def pad(self, *args, **kwargs):
|
| 219 |
+
logger.info("pad is deprecated and will be removed in version 4.27. Please use pad_image instead.")
|
| 220 |
+
return self.pad_image(*args, **kwargs)
|
| 221 |
+
|
| 222 |
+
def thumbnail(
|
| 223 |
+
self,
|
| 224 |
+
image: np.ndarray,
|
| 225 |
+
size: dict[str, int],
|
| 226 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 227 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 228 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 229 |
+
**kwargs,
|
| 230 |
+
) -> np.ndarray:
|
| 231 |
+
"""
|
| 232 |
+
Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any
|
| 233 |
+
corresponding dimension of the specified size.
|
| 234 |
+
|
| 235 |
+
Args:
|
| 236 |
+
image (`np.ndarray`):
|
| 237 |
+
The image to be resized.
|
| 238 |
+
size (`dict[str, int]`):
|
| 239 |
+
The size `{"height": h, "width": w}` to resize the image to.
|
| 240 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
| 241 |
+
The resampling filter to use.
|
| 242 |
+
data_format (`Optional[Union[str, ChannelDimension]]`, *optional*):
|
| 243 |
+
The data format of the output image. If unset, the same format as the input image is used.
|
| 244 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 245 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 246 |
+
"""
|
| 247 |
+
input_height, input_width = get_image_size(image, channel_dim=input_data_format)
|
| 248 |
+
output_height, output_width = size["height"], size["width"]
|
| 249 |
+
|
| 250 |
+
# We always resize to the smallest of either the input or output size.
|
| 251 |
+
height = min(input_height, output_height)
|
| 252 |
+
width = min(input_width, output_width)
|
| 253 |
+
|
| 254 |
+
if height == input_height and width == input_width:
|
| 255 |
+
return image
|
| 256 |
+
|
| 257 |
+
if input_height > input_width:
|
| 258 |
+
width = int(input_width * height / input_height)
|
| 259 |
+
elif input_width > input_height:
|
| 260 |
+
height = int(input_height * width / input_width)
|
| 261 |
+
|
| 262 |
+
return resize(
|
| 263 |
+
image,
|
| 264 |
+
size=(height, width),
|
| 265 |
+
resample=resample,
|
| 266 |
+
reducing_gap=2.0,
|
| 267 |
+
data_format=data_format,
|
| 268 |
+
input_data_format=input_data_format,
|
| 269 |
+
**kwargs,
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
def resize(
|
| 273 |
+
self,
|
| 274 |
+
image: np.ndarray,
|
| 275 |
+
size: dict[str, int],
|
| 276 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 277 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 278 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 279 |
+
**kwargs,
|
| 280 |
+
) -> np.ndarray:
|
| 281 |
+
"""
|
| 282 |
+
Resizes `image` to `(height, width)` specified by `size` using the PIL library.
|
| 283 |
+
|
| 284 |
+
Args:
|
| 285 |
+
image (`np.ndarray`):
|
| 286 |
+
Image to resize.
|
| 287 |
+
size (`dict[str, int]`):
|
| 288 |
+
Size of the output image.
|
| 289 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
| 290 |
+
Resampling filter to use when resiizing the image.
|
| 291 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 292 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
| 293 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 294 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 295 |
+
"""
|
| 296 |
+
size = get_size_dict(size)
|
| 297 |
+
shortest_edge = min(size["height"], size["width"])
|
| 298 |
+
output_size = get_resize_output_image_size(
|
| 299 |
+
image, size=shortest_edge, default_to_square=False, input_data_format=input_data_format
|
| 300 |
+
)
|
| 301 |
+
resized_image = resize(
|
| 302 |
+
image,
|
| 303 |
+
size=output_size,
|
| 304 |
+
resample=resample,
|
| 305 |
+
data_format=data_format,
|
| 306 |
+
input_data_format=input_data_format,
|
| 307 |
+
**kwargs,
|
| 308 |
+
)
|
| 309 |
+
return resized_image
|
| 310 |
+
|
| 311 |
+
@filter_out_non_signature_kwargs()
|
| 312 |
+
def preprocess(
|
| 313 |
+
self,
|
| 314 |
+
images: ImageInput,
|
| 315 |
+
do_resize: Optional[bool] = None,
|
| 316 |
+
size: Optional[dict[str, int]] = None,
|
| 317 |
+
resample: PILImageResampling = None,
|
| 318 |
+
do_thumbnail: Optional[bool] = None,
|
| 319 |
+
do_align_long_axis: Optional[bool] = None,
|
| 320 |
+
do_pad: Optional[bool] = None,
|
| 321 |
+
random_padding: bool = False,
|
| 322 |
+
do_rescale: Optional[bool] = None,
|
| 323 |
+
rescale_factor: Optional[float] = None,
|
| 324 |
+
do_normalize: Optional[bool] = None,
|
| 325 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 326 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 327 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 328 |
+
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
|
| 329 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 330 |
+
) -> PIL.Image.Image:
|
| 331 |
+
"""
|
| 332 |
+
Preprocess an image or batch of images.
|
| 333 |
+
|
| 334 |
+
Args:
|
| 335 |
+
images (`ImageInput`):
|
| 336 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 337 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 338 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 339 |
+
Whether to resize the image.
|
| 340 |
+
size (`dict[str, int]`, *optional*, defaults to `self.size`):
|
| 341 |
+
Size of the image after resizing. Shortest edge of the image is resized to min(size["height"],
|
| 342 |
+
size["width"]) with the longest edge resized to keep the input aspect ratio.
|
| 343 |
+
resample (`int`, *optional*, defaults to `self.resample`):
|
| 344 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
|
| 345 |
+
has an effect if `do_resize` is set to `True`.
|
| 346 |
+
do_thumbnail (`bool`, *optional*, defaults to `self.do_thumbnail`):
|
| 347 |
+
Whether to resize the image using thumbnail method.
|
| 348 |
+
do_align_long_axis (`bool`, *optional*, defaults to `self.do_align_long_axis`):
|
| 349 |
+
Whether to align the long axis of the image with the long axis of `size` by rotating by 90 degrees.
|
| 350 |
+
do_pad (`bool`, *optional*, defaults to `self.do_pad`):
|
| 351 |
+
Whether to pad the image. If `random_padding` is set to `True`, each image is padded with a random
|
| 352 |
+
amount of padding on each size, up to the largest image size in the batch. Otherwise, all images are
|
| 353 |
+
padded to the largest image size in the batch.
|
| 354 |
+
random_padding (`bool`, *optional*, defaults to `self.random_padding`):
|
| 355 |
+
Whether to use random padding when padding the image. If `True`, each image in the batch with be padded
|
| 356 |
+
with a random amount of padding on each side up to the size of the largest image in the batch.
|
| 357 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 358 |
+
Whether to rescale the image pixel values.
|
| 359 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 360 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 361 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 362 |
+
Whether to normalize the image.
|
| 363 |
+
image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
|
| 364 |
+
Image mean to use for normalization.
|
| 365 |
+
image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
|
| 366 |
+
Image standard deviation to use for normalization.
|
| 367 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 368 |
+
The type of tensors to return. Can be one of:
|
| 369 |
+
- Unset: Return a list of `np.ndarray`.
|
| 370 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 371 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 372 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 373 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 374 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 375 |
+
The channel dimension format for the output image. Can be one of:
|
| 376 |
+
- `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 377 |
+
- `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 378 |
+
- Unset: defaults to the channel dimension format of the input image.
|
| 379 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 380 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 381 |
+
from the input image. Can be one of:
|
| 382 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 383 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 384 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 385 |
+
"""
|
| 386 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 387 |
+
size = size if size is not None else self.size
|
| 388 |
+
if isinstance(size, (tuple, list)):
|
| 389 |
+
# Previous feature extractor had size in (width, height) format
|
| 390 |
+
size = size[::-1]
|
| 391 |
+
size = get_size_dict(size)
|
| 392 |
+
resample = resample if resample is not None else self.resample
|
| 393 |
+
do_thumbnail = do_thumbnail if do_thumbnail is not None else self.do_thumbnail
|
| 394 |
+
do_align_long_axis = do_align_long_axis if do_align_long_axis is not None else self.do_align_long_axis
|
| 395 |
+
do_pad = do_pad if do_pad is not None else self.do_pad
|
| 396 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 397 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 398 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 399 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 400 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 401 |
+
|
| 402 |
+
images = make_list_of_images(images)
|
| 403 |
+
|
| 404 |
+
if not valid_images(images):
|
| 405 |
+
raise ValueError(
|
| 406 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 407 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 408 |
+
)
|
| 409 |
+
validate_preprocess_arguments(
|
| 410 |
+
do_rescale=do_rescale,
|
| 411 |
+
rescale_factor=rescale_factor,
|
| 412 |
+
do_normalize=do_normalize,
|
| 413 |
+
image_mean=image_mean,
|
| 414 |
+
image_std=image_std,
|
| 415 |
+
do_pad=do_pad,
|
| 416 |
+
size_divisibility=size, # There is no pad divisibility in this processor, but pad requires the size arg.
|
| 417 |
+
do_resize=do_resize,
|
| 418 |
+
size=size,
|
| 419 |
+
resample=resample,
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
images = [convert_to_rgb(image) for image in images]
|
| 423 |
+
|
| 424 |
+
# All transformations expect numpy arrays.
|
| 425 |
+
images = [to_numpy_array(image) for image in images]
|
| 426 |
+
|
| 427 |
+
if do_rescale and is_scaled_image(images[0]):
|
| 428 |
+
logger.warning_once(
|
| 429 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 430 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
if input_data_format is None:
|
| 434 |
+
# We assume that all images have the same channel dimension format.
|
| 435 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 436 |
+
|
| 437 |
+
if do_align_long_axis:
|
| 438 |
+
images = [self.align_long_axis(image, size=size, input_data_format=input_data_format) for image in images]
|
| 439 |
+
|
| 440 |
+
if do_resize:
|
| 441 |
+
images = [
|
| 442 |
+
self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
|
| 443 |
+
for image in images
|
| 444 |
+
]
|
| 445 |
+
|
| 446 |
+
if do_thumbnail:
|
| 447 |
+
images = [self.thumbnail(image=image, size=size, input_data_format=input_data_format) for image in images]
|
| 448 |
+
|
| 449 |
+
if do_pad:
|
| 450 |
+
images = [
|
| 451 |
+
self.pad_image(
|
| 452 |
+
image=image, size=size, random_padding=random_padding, input_data_format=input_data_format
|
| 453 |
+
)
|
| 454 |
+
for image in images
|
| 455 |
+
]
|
| 456 |
+
|
| 457 |
+
if do_rescale:
|
| 458 |
+
images = [
|
| 459 |
+
self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
| 460 |
+
for image in images
|
| 461 |
+
]
|
| 462 |
+
|
| 463 |
+
if do_normalize:
|
| 464 |
+
images = [
|
| 465 |
+
self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
|
| 466 |
+
for image in images
|
| 467 |
+
]
|
| 468 |
+
|
| 469 |
+
images = [
|
| 470 |
+
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
|
| 471 |
+
]
|
| 472 |
+
|
| 473 |
+
data = {"pixel_values": images}
|
| 474 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
__all__ = ["DonutImageProcessor"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/donut/image_processing_donut_fast.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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8
|
| 2 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Fast Image processor class for Donut."""
|
| 16 |
+
|
| 17 |
+
from typing import Optional, Union
|
| 18 |
+
|
| 19 |
+
from ...image_processing_utils_fast import BaseImageProcessorFast, BatchFeature, DefaultFastImageProcessorKwargs
|
| 20 |
+
from ...image_transforms import group_images_by_shape, reorder_images
|
| 21 |
+
from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ImageInput, PILImageResampling, SizeDict
|
| 22 |
+
from ...processing_utils import Unpack
|
| 23 |
+
from ...utils import (
|
| 24 |
+
TensorType,
|
| 25 |
+
auto_docstring,
|
| 26 |
+
is_torch_available,
|
| 27 |
+
is_torchvision_available,
|
| 28 |
+
is_torchvision_v2_available,
|
| 29 |
+
logging,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
if is_torch_available():
|
| 36 |
+
import torch
|
| 37 |
+
|
| 38 |
+
if is_torchvision_available():
|
| 39 |
+
if is_torchvision_v2_available():
|
| 40 |
+
from torchvision.transforms.v2 import functional as F
|
| 41 |
+
else:
|
| 42 |
+
from torchvision.transforms import functional as F
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class DonutFastImageProcessorKwargs(DefaultFastImageProcessorKwargs):
|
| 46 |
+
"""
|
| 47 |
+
Args:
|
| 48 |
+
do_thumbnail (`bool`, *optional*, defaults to `self.do_thumbnail`):
|
| 49 |
+
Whether to resize the image using thumbnail method.
|
| 50 |
+
do_align_long_axis (`bool`, *optional*, defaults to `self.do_align_long_axis`):
|
| 51 |
+
Whether to align the long axis of the image with the long axis of `size` by rotating by 90 degrees.
|
| 52 |
+
do_pad (`bool`, *optional*, defaults to `self.do_pad`):
|
| 53 |
+
Whether to pad the image. If `random_padding` is set to `True`, each image is padded with a random
|
| 54 |
+
amount of padding on each size, up to the largest image size in the batch. Otherwise, all images are
|
| 55 |
+
padded to the largest image size in the batch.
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
do_thumbnail: Optional[bool]
|
| 59 |
+
do_align_long_axis: Optional[bool]
|
| 60 |
+
do_pad: Optional[bool]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@auto_docstring
|
| 64 |
+
class DonutImageProcessorFast(BaseImageProcessorFast):
|
| 65 |
+
resample = PILImageResampling.BILINEAR
|
| 66 |
+
image_mean = IMAGENET_STANDARD_MEAN
|
| 67 |
+
image_std = IMAGENET_STANDARD_STD
|
| 68 |
+
size = {"height": 2560, "width": 1920}
|
| 69 |
+
do_resize = True
|
| 70 |
+
do_rescale = True
|
| 71 |
+
do_normalize = True
|
| 72 |
+
do_thumbnail = True
|
| 73 |
+
do_align_long_axis = False
|
| 74 |
+
do_pad = True
|
| 75 |
+
valid_kwargs = DonutFastImageProcessorKwargs
|
| 76 |
+
|
| 77 |
+
def __init__(self, **kwargs: Unpack[DonutFastImageProcessorKwargs]):
|
| 78 |
+
size = kwargs.pop("size", None)
|
| 79 |
+
if isinstance(size, (tuple, list)):
|
| 80 |
+
size = size[::-1]
|
| 81 |
+
kwargs["size"] = size
|
| 82 |
+
super().__init__(**kwargs)
|
| 83 |
+
|
| 84 |
+
@auto_docstring
|
| 85 |
+
def preprocess(self, images: ImageInput, **kwargs: Unpack[DonutFastImageProcessorKwargs]) -> BatchFeature:
|
| 86 |
+
if "size" in kwargs:
|
| 87 |
+
size = kwargs.pop("size")
|
| 88 |
+
if isinstance(size, (tuple, list)):
|
| 89 |
+
size = size[::-1]
|
| 90 |
+
kwargs["size"] = size
|
| 91 |
+
return super().preprocess(images, **kwargs)
|
| 92 |
+
|
| 93 |
+
def align_long_axis(
|
| 94 |
+
self,
|
| 95 |
+
image: "torch.Tensor",
|
| 96 |
+
size: SizeDict,
|
| 97 |
+
) -> "torch.Tensor":
|
| 98 |
+
"""
|
| 99 |
+
Align the long axis of the image to the longest axis of the specified size.
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
image (`torch.Tensor`):
|
| 103 |
+
The image to be aligned.
|
| 104 |
+
size (`dict[str, int]`):
|
| 105 |
+
The size `{"height": h, "width": w}` to align the long axis to.
|
| 106 |
+
|
| 107 |
+
Returns:
|
| 108 |
+
`torch.Tensor`: The aligned image.
|
| 109 |
+
"""
|
| 110 |
+
input_height, input_width = image.shape[-2:]
|
| 111 |
+
output_height, output_width = size.height, size.width
|
| 112 |
+
|
| 113 |
+
if (output_width < output_height and input_width > input_height) or (
|
| 114 |
+
output_width > output_height and input_width < input_height
|
| 115 |
+
):
|
| 116 |
+
height_dim, width_dim = image.dim() - 2, image.dim() - 1
|
| 117 |
+
image = torch.rot90(image, 3, dims=[height_dim, width_dim])
|
| 118 |
+
|
| 119 |
+
return image
|
| 120 |
+
|
| 121 |
+
def pad_image(
|
| 122 |
+
self,
|
| 123 |
+
image: "torch.Tensor",
|
| 124 |
+
size: SizeDict,
|
| 125 |
+
random_padding: bool = False,
|
| 126 |
+
) -> "torch.Tensor":
|
| 127 |
+
"""
|
| 128 |
+
Pad the image to the specified size.
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
image (`torch.Tensor`):
|
| 132 |
+
The image to be padded.
|
| 133 |
+
size (`dict[str, int]`):
|
| 134 |
+
The size `{"height": h, "width": w}` to pad the image to.
|
| 135 |
+
random_padding (`bool`, *optional*, defaults to `False`):
|
| 136 |
+
Whether to use random padding or not.
|
| 137 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 138 |
+
The data format of the output image. If unset, the same format as the input image is used.
|
| 139 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 140 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 141 |
+
"""
|
| 142 |
+
output_height, output_width = size.height, size.width
|
| 143 |
+
input_height, input_width = image.shape[-2:]
|
| 144 |
+
|
| 145 |
+
delta_width = output_width - input_width
|
| 146 |
+
delta_height = output_height - input_height
|
| 147 |
+
|
| 148 |
+
if random_padding:
|
| 149 |
+
pad_top = torch.random.randint(low=0, high=delta_height + 1)
|
| 150 |
+
pad_left = torch.random.randint(low=0, high=delta_width + 1)
|
| 151 |
+
else:
|
| 152 |
+
pad_top = delta_height // 2
|
| 153 |
+
pad_left = delta_width // 2
|
| 154 |
+
|
| 155 |
+
pad_bottom = delta_height - pad_top
|
| 156 |
+
pad_right = delta_width - pad_left
|
| 157 |
+
|
| 158 |
+
padding = (pad_left, pad_top, pad_right, pad_bottom)
|
| 159 |
+
return F.pad(image, padding)
|
| 160 |
+
|
| 161 |
+
def pad(self, *args, **kwargs):
|
| 162 |
+
logger.info("pad is deprecated and will be removed in version 4.27. Please use pad_image instead.")
|
| 163 |
+
return self.pad_image(*args, **kwargs)
|
| 164 |
+
|
| 165 |
+
def thumbnail(
|
| 166 |
+
self,
|
| 167 |
+
image: "torch.Tensor",
|
| 168 |
+
size: SizeDict,
|
| 169 |
+
) -> "torch.Tensor":
|
| 170 |
+
"""
|
| 171 |
+
Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any
|
| 172 |
+
corresponding dimension of the specified size.
|
| 173 |
+
|
| 174 |
+
Args:
|
| 175 |
+
image (`torch.Tensor`):
|
| 176 |
+
The image to be resized.
|
| 177 |
+
size (`dict[str, int]`):
|
| 178 |
+
The size `{"height": h, "width": w}` to resize the image to.
|
| 179 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
| 180 |
+
The resampling filter to use.
|
| 181 |
+
data_format (`Optional[Union[str, ChannelDimension]]`, *optional*):
|
| 182 |
+
The data format of the output image. If unset, the same format as the input image is used.
|
| 183 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 184 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 185 |
+
"""
|
| 186 |
+
input_height, input_width = image.shape[-2:]
|
| 187 |
+
output_height, output_width = size.height, size.width
|
| 188 |
+
|
| 189 |
+
# We always resize to the smallest of either the input or output size.
|
| 190 |
+
height = min(input_height, output_height)
|
| 191 |
+
width = min(input_width, output_width)
|
| 192 |
+
|
| 193 |
+
if height == input_height and width == input_width:
|
| 194 |
+
return image
|
| 195 |
+
|
| 196 |
+
if input_height > input_width:
|
| 197 |
+
width = int(input_width * height / input_height)
|
| 198 |
+
elif input_width > input_height:
|
| 199 |
+
height = int(input_height * width / input_width)
|
| 200 |
+
|
| 201 |
+
return self.resize(
|
| 202 |
+
image,
|
| 203 |
+
size=SizeDict(width=width, height=height),
|
| 204 |
+
interpolation=F.InterpolationMode.BICUBIC,
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
def _preprocess(
|
| 208 |
+
self,
|
| 209 |
+
images: list["torch.Tensor"],
|
| 210 |
+
do_resize: bool,
|
| 211 |
+
do_thumbnail: bool,
|
| 212 |
+
do_align_long_axis: bool,
|
| 213 |
+
do_pad: bool,
|
| 214 |
+
size: SizeDict,
|
| 215 |
+
interpolation: Optional["F.InterpolationMode"],
|
| 216 |
+
do_center_crop: bool,
|
| 217 |
+
crop_size: SizeDict,
|
| 218 |
+
do_rescale: bool,
|
| 219 |
+
rescale_factor: float,
|
| 220 |
+
do_normalize: bool,
|
| 221 |
+
image_mean: Optional[Union[float, list[float]]],
|
| 222 |
+
image_std: Optional[Union[float, list[float]]],
|
| 223 |
+
disable_grouping: Optional[bool],
|
| 224 |
+
return_tensors: Optional[Union[str, TensorType]],
|
| 225 |
+
**kwargs,
|
| 226 |
+
) -> BatchFeature:
|
| 227 |
+
# Group images by size for batched resizing
|
| 228 |
+
grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
|
| 229 |
+
resized_images_grouped = {}
|
| 230 |
+
for shape, stacked_images in grouped_images.items():
|
| 231 |
+
if do_align_long_axis:
|
| 232 |
+
stacked_images = self.align_long_axis(image=stacked_images, size=size)
|
| 233 |
+
if do_resize:
|
| 234 |
+
shortest_edge = min(size.height, size.width)
|
| 235 |
+
stacked_images = self.resize(
|
| 236 |
+
image=stacked_images, size=SizeDict(shortest_edge=shortest_edge), interpolation=interpolation
|
| 237 |
+
)
|
| 238 |
+
if do_thumbnail:
|
| 239 |
+
stacked_images = self.thumbnail(image=stacked_images, size=size)
|
| 240 |
+
if do_pad:
|
| 241 |
+
stacked_images = self.pad_image(image=stacked_images, size=size, random_padding=False)
|
| 242 |
+
|
| 243 |
+
resized_images_grouped[shape] = stacked_images
|
| 244 |
+
resized_images = reorder_images(resized_images_grouped, grouped_images_index)
|
| 245 |
+
|
| 246 |
+
# Group images by size for further processing
|
| 247 |
+
# Needed in case do_resize is False, or resize returns images with different sizes
|
| 248 |
+
grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
|
| 249 |
+
processed_images_grouped = {}
|
| 250 |
+
for shape, stacked_images in grouped_images.items():
|
| 251 |
+
if do_center_crop:
|
| 252 |
+
stacked_images = self.center_crop(stacked_images, crop_size)
|
| 253 |
+
# Fused rescale and normalize
|
| 254 |
+
stacked_images = self.rescale_and_normalize(
|
| 255 |
+
stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
|
| 256 |
+
)
|
| 257 |
+
processed_images_grouped[shape] = stacked_images
|
| 258 |
+
|
| 259 |
+
processed_images = reorder_images(processed_images_grouped, grouped_images_index)
|
| 260 |
+
processed_images = torch.stack(processed_images, dim=0) if return_tensors else processed_images
|
| 261 |
+
|
| 262 |
+
return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
__all__ = ["DonutImageProcessorFast"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/donut/modeling_donut_swin.py
ADDED
|
@@ -0,0 +1,1032 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch Donut Swin Transformer model.
|
| 16 |
+
|
| 17 |
+
This implementation is identical to a regular Swin Transformer, without final layer norm on top of the final hidden
|
| 18 |
+
states."""
|
| 19 |
+
|
| 20 |
+
import collections.abc
|
| 21 |
+
import math
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from typing import Optional, Union
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.utils.checkpoint
|
| 27 |
+
from torch import nn
|
| 28 |
+
|
| 29 |
+
from ...activations import ACT2FN
|
| 30 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 31 |
+
from ...modeling_utils import PreTrainedModel
|
| 32 |
+
from ...pytorch_utils import find_pruneable_heads_and_indices, meshgrid, prune_linear_layer
|
| 33 |
+
from ...utils import ModelOutput, auto_docstring, logging, torch_int
|
| 34 |
+
from .configuration_donut_swin import DonutSwinConfig
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
logger = logging.get_logger(__name__)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass
|
| 41 |
+
@auto_docstring(
|
| 42 |
+
custom_intro="""
|
| 43 |
+
DonutSwin encoder's outputs, with potential hidden states and attentions.
|
| 44 |
+
"""
|
| 45 |
+
)
|
| 46 |
+
# Copied from transformers.models.swin.modeling_swin.SwinEncoderOutput with Swin->DonutSwin
|
| 47 |
+
class DonutSwinEncoderOutput(ModelOutput):
|
| 48 |
+
r"""
|
| 49 |
+
reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 50 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
|
| 51 |
+
shape `(batch_size, hidden_size, height, width)`.
|
| 52 |
+
|
| 53 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
|
| 54 |
+
include the spatial dimensions.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
last_hidden_state: Optional[torch.FloatTensor] = None
|
| 58 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 59 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 60 |
+
reshaped_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@dataclass
|
| 64 |
+
@auto_docstring(
|
| 65 |
+
custom_intro="""
|
| 66 |
+
DonutSwin model's outputs that also contains a pooling of the last hidden states.
|
| 67 |
+
"""
|
| 68 |
+
)
|
| 69 |
+
# Copied from transformers.models.swin.modeling_swin.SwinModelOutput with Swin->DonutSwin
|
| 70 |
+
class DonutSwinModelOutput(ModelOutput):
|
| 71 |
+
r"""
|
| 72 |
+
pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
|
| 73 |
+
Average pooling of the last layer hidden-state.
|
| 74 |
+
reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 75 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
|
| 76 |
+
shape `(batch_size, hidden_size, height, width)`.
|
| 77 |
+
|
| 78 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
|
| 79 |
+
include the spatial dimensions.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
last_hidden_state: Optional[torch.FloatTensor] = None
|
| 83 |
+
pooler_output: Optional[torch.FloatTensor] = None
|
| 84 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 85 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 86 |
+
reshaped_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@dataclass
|
| 90 |
+
@auto_docstring(
|
| 91 |
+
custom_intro="""
|
| 92 |
+
DonutSwin outputs for image classification.
|
| 93 |
+
"""
|
| 94 |
+
)
|
| 95 |
+
# Copied from transformers.models.swin.modeling_swin.SwinImageClassifierOutput with Swin->DonutSwin
|
| 96 |
+
class DonutSwinImageClassifierOutput(ModelOutput):
|
| 97 |
+
r"""
|
| 98 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 99 |
+
Classification (or regression if config.num_labels==1) loss.
|
| 100 |
+
logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
|
| 101 |
+
Classification (or regression if config.num_labels==1) scores (before SoftMax).
|
| 102 |
+
reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 103 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
|
| 104 |
+
shape `(batch_size, hidden_size, height, width)`.
|
| 105 |
+
|
| 106 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
|
| 107 |
+
include the spatial dimensions.
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
loss: Optional[torch.FloatTensor] = None
|
| 111 |
+
logits: Optional[torch.FloatTensor] = None
|
| 112 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 113 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 114 |
+
reshaped_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
# Copied from transformers.models.swin.modeling_swin.window_partition
|
| 118 |
+
def window_partition(input_feature, window_size):
|
| 119 |
+
"""
|
| 120 |
+
Partitions the given input into windows.
|
| 121 |
+
"""
|
| 122 |
+
batch_size, height, width, num_channels = input_feature.shape
|
| 123 |
+
input_feature = input_feature.view(
|
| 124 |
+
batch_size, height // window_size, window_size, width // window_size, window_size, num_channels
|
| 125 |
+
)
|
| 126 |
+
windows = input_feature.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, num_channels)
|
| 127 |
+
return windows
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
# Copied from transformers.models.swin.modeling_swin.window_reverse
|
| 131 |
+
def window_reverse(windows, window_size, height, width):
|
| 132 |
+
"""
|
| 133 |
+
Merges windows to produce higher resolution features.
|
| 134 |
+
"""
|
| 135 |
+
num_channels = windows.shape[-1]
|
| 136 |
+
windows = windows.view(-1, height // window_size, width // window_size, window_size, window_size, num_channels)
|
| 137 |
+
windows = windows.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, height, width, num_channels)
|
| 138 |
+
return windows
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# Copied from transformers.models.swin.modeling_swin.SwinEmbeddings with Swin->DonutSwin
|
| 142 |
+
class DonutSwinEmbeddings(nn.Module):
|
| 143 |
+
"""
|
| 144 |
+
Construct the patch and position embeddings. Optionally, also the mask token.
|
| 145 |
+
"""
|
| 146 |
+
|
| 147 |
+
def __init__(self, config, use_mask_token=False):
|
| 148 |
+
super().__init__()
|
| 149 |
+
|
| 150 |
+
self.patch_embeddings = DonutSwinPatchEmbeddings(config)
|
| 151 |
+
num_patches = self.patch_embeddings.num_patches
|
| 152 |
+
self.patch_grid = self.patch_embeddings.grid_size
|
| 153 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, config.embed_dim)) if use_mask_token else None
|
| 154 |
+
|
| 155 |
+
if config.use_absolute_embeddings:
|
| 156 |
+
self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.embed_dim))
|
| 157 |
+
else:
|
| 158 |
+
self.position_embeddings = None
|
| 159 |
+
|
| 160 |
+
self.norm = nn.LayerNorm(config.embed_dim)
|
| 161 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 162 |
+
self.patch_size = config.patch_size
|
| 163 |
+
self.config = config
|
| 164 |
+
|
| 165 |
+
# Copied from transformers.models.vit.modeling_vit.ViTEmbeddings.interpolate_pos_encoding
|
| 166 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 167 |
+
"""
|
| 168 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
|
| 169 |
+
images. This method is also adapted to support torch.jit tracing.
|
| 170 |
+
|
| 171 |
+
Adapted from:
|
| 172 |
+
- https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
|
| 173 |
+
- https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
num_patches = embeddings.shape[1] - 1
|
| 177 |
+
num_positions = self.position_embeddings.shape[1] - 1
|
| 178 |
+
|
| 179 |
+
# always interpolate when tracing to ensure the exported model works for dynamic input shapes
|
| 180 |
+
if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
|
| 181 |
+
return self.position_embeddings
|
| 182 |
+
|
| 183 |
+
class_pos_embed = self.position_embeddings[:, :1]
|
| 184 |
+
patch_pos_embed = self.position_embeddings[:, 1:]
|
| 185 |
+
|
| 186 |
+
dim = embeddings.shape[-1]
|
| 187 |
+
|
| 188 |
+
new_height = height // self.patch_size
|
| 189 |
+
new_width = width // self.patch_size
|
| 190 |
+
|
| 191 |
+
sqrt_num_positions = torch_int(num_positions**0.5)
|
| 192 |
+
patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
|
| 193 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 194 |
+
|
| 195 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 196 |
+
patch_pos_embed,
|
| 197 |
+
size=(new_height, new_width),
|
| 198 |
+
mode="bicubic",
|
| 199 |
+
align_corners=False,
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 203 |
+
|
| 204 |
+
return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
|
| 205 |
+
|
| 206 |
+
def forward(
|
| 207 |
+
self,
|
| 208 |
+
pixel_values: Optional[torch.FloatTensor],
|
| 209 |
+
bool_masked_pos: Optional[torch.BoolTensor] = None,
|
| 210 |
+
interpolate_pos_encoding: bool = False,
|
| 211 |
+
) -> tuple[torch.Tensor]:
|
| 212 |
+
_, num_channels, height, width = pixel_values.shape
|
| 213 |
+
embeddings, output_dimensions = self.patch_embeddings(pixel_values)
|
| 214 |
+
embeddings = self.norm(embeddings)
|
| 215 |
+
batch_size, seq_len, _ = embeddings.size()
|
| 216 |
+
|
| 217 |
+
if bool_masked_pos is not None:
|
| 218 |
+
mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
|
| 219 |
+
# replace the masked visual tokens by mask_tokens
|
| 220 |
+
mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
|
| 221 |
+
embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
|
| 222 |
+
|
| 223 |
+
if self.position_embeddings is not None:
|
| 224 |
+
if interpolate_pos_encoding:
|
| 225 |
+
embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
|
| 226 |
+
else:
|
| 227 |
+
embeddings = embeddings + self.position_embeddings
|
| 228 |
+
|
| 229 |
+
embeddings = self.dropout(embeddings)
|
| 230 |
+
|
| 231 |
+
return embeddings, output_dimensions
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# Copied from transformers.models.swin.modeling_swin.SwinPatchEmbeddings with Swin->DonutSwin
|
| 235 |
+
class DonutSwinPatchEmbeddings(nn.Module):
|
| 236 |
+
"""
|
| 237 |
+
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
| 238 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
| 239 |
+
Transformer.
|
| 240 |
+
"""
|
| 241 |
+
|
| 242 |
+
def __init__(self, config):
|
| 243 |
+
super().__init__()
|
| 244 |
+
image_size, patch_size = config.image_size, config.patch_size
|
| 245 |
+
num_channels, hidden_size = config.num_channels, config.embed_dim
|
| 246 |
+
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
|
| 247 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 248 |
+
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 249 |
+
self.image_size = image_size
|
| 250 |
+
self.patch_size = patch_size
|
| 251 |
+
self.num_channels = num_channels
|
| 252 |
+
self.num_patches = num_patches
|
| 253 |
+
self.grid_size = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
|
| 254 |
+
|
| 255 |
+
self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
|
| 256 |
+
|
| 257 |
+
def maybe_pad(self, pixel_values, height, width):
|
| 258 |
+
if width % self.patch_size[1] != 0:
|
| 259 |
+
pad_values = (0, self.patch_size[1] - width % self.patch_size[1])
|
| 260 |
+
pixel_values = nn.functional.pad(pixel_values, pad_values)
|
| 261 |
+
if height % self.patch_size[0] != 0:
|
| 262 |
+
pad_values = (0, 0, 0, self.patch_size[0] - height % self.patch_size[0])
|
| 263 |
+
pixel_values = nn.functional.pad(pixel_values, pad_values)
|
| 264 |
+
return pixel_values
|
| 265 |
+
|
| 266 |
+
def forward(self, pixel_values: Optional[torch.FloatTensor]) -> tuple[torch.Tensor, tuple[int]]:
|
| 267 |
+
_, num_channels, height, width = pixel_values.shape
|
| 268 |
+
# pad the input to be divisible by self.patch_size, if needed
|
| 269 |
+
pixel_values = self.maybe_pad(pixel_values, height, width)
|
| 270 |
+
embeddings = self.projection(pixel_values)
|
| 271 |
+
_, _, height, width = embeddings.shape
|
| 272 |
+
output_dimensions = (height, width)
|
| 273 |
+
embeddings = embeddings.flatten(2).transpose(1, 2)
|
| 274 |
+
|
| 275 |
+
return embeddings, output_dimensions
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
# Copied from transformers.models.swin.modeling_swin.SwinPatchMerging
|
| 279 |
+
class DonutSwinPatchMerging(nn.Module):
|
| 280 |
+
"""
|
| 281 |
+
Patch Merging Layer.
|
| 282 |
+
|
| 283 |
+
Args:
|
| 284 |
+
input_resolution (`tuple[int]`):
|
| 285 |
+
Resolution of input feature.
|
| 286 |
+
dim (`int`):
|
| 287 |
+
Number of input channels.
|
| 288 |
+
norm_layer (`nn.Module`, *optional*, defaults to `nn.LayerNorm`):
|
| 289 |
+
Normalization layer class.
|
| 290 |
+
"""
|
| 291 |
+
|
| 292 |
+
def __init__(self, input_resolution: tuple[int], dim: int, norm_layer: nn.Module = nn.LayerNorm) -> None:
|
| 293 |
+
super().__init__()
|
| 294 |
+
self.input_resolution = input_resolution
|
| 295 |
+
self.dim = dim
|
| 296 |
+
self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
|
| 297 |
+
self.norm = norm_layer(4 * dim)
|
| 298 |
+
|
| 299 |
+
def maybe_pad(self, input_feature, height, width):
|
| 300 |
+
should_pad = (height % 2 == 1) or (width % 2 == 1)
|
| 301 |
+
if should_pad:
|
| 302 |
+
pad_values = (0, 0, 0, width % 2, 0, height % 2)
|
| 303 |
+
input_feature = nn.functional.pad(input_feature, pad_values)
|
| 304 |
+
|
| 305 |
+
return input_feature
|
| 306 |
+
|
| 307 |
+
def forward(self, input_feature: torch.Tensor, input_dimensions: tuple[int, int]) -> torch.Tensor:
|
| 308 |
+
height, width = input_dimensions
|
| 309 |
+
# `dim` is height * width
|
| 310 |
+
batch_size, dim, num_channels = input_feature.shape
|
| 311 |
+
|
| 312 |
+
input_feature = input_feature.view(batch_size, height, width, num_channels)
|
| 313 |
+
# pad input to be divisible by width and height, if needed
|
| 314 |
+
input_feature = self.maybe_pad(input_feature, height, width)
|
| 315 |
+
# [batch_size, height/2, width/2, num_channels]
|
| 316 |
+
input_feature_0 = input_feature[:, 0::2, 0::2, :]
|
| 317 |
+
# [batch_size, height/2, width/2, num_channels]
|
| 318 |
+
input_feature_1 = input_feature[:, 1::2, 0::2, :]
|
| 319 |
+
# [batch_size, height/2, width/2, num_channels]
|
| 320 |
+
input_feature_2 = input_feature[:, 0::2, 1::2, :]
|
| 321 |
+
# [batch_size, height/2, width/2, num_channels]
|
| 322 |
+
input_feature_3 = input_feature[:, 1::2, 1::2, :]
|
| 323 |
+
# batch_size height/2 width/2 4*num_channels
|
| 324 |
+
input_feature = torch.cat([input_feature_0, input_feature_1, input_feature_2, input_feature_3], -1)
|
| 325 |
+
input_feature = input_feature.view(batch_size, -1, 4 * num_channels) # batch_size height/2*width/2 4*C
|
| 326 |
+
|
| 327 |
+
input_feature = self.norm(input_feature)
|
| 328 |
+
input_feature = self.reduction(input_feature)
|
| 329 |
+
|
| 330 |
+
return input_feature
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
# Copied from transformers.models.beit.modeling_beit.drop_path
|
| 334 |
+
def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
|
| 335 |
+
"""
|
| 336 |
+
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 337 |
+
|
| 338 |
+
Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
|
| 339 |
+
however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
|
| 340 |
+
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
|
| 341 |
+
layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
|
| 342 |
+
argument.
|
| 343 |
+
"""
|
| 344 |
+
if drop_prob == 0.0 or not training:
|
| 345 |
+
return input
|
| 346 |
+
keep_prob = 1 - drop_prob
|
| 347 |
+
shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 348 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
|
| 349 |
+
random_tensor.floor_() # binarize
|
| 350 |
+
output = input.div(keep_prob) * random_tensor
|
| 351 |
+
return output
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
# Copied from transformers.models.swin.modeling_swin.SwinDropPath
|
| 355 |
+
class DonutSwinDropPath(nn.Module):
|
| 356 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 357 |
+
|
| 358 |
+
def __init__(self, drop_prob: Optional[float] = None) -> None:
|
| 359 |
+
super().__init__()
|
| 360 |
+
self.drop_prob = drop_prob
|
| 361 |
+
|
| 362 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 363 |
+
return drop_path(hidden_states, self.drop_prob, self.training)
|
| 364 |
+
|
| 365 |
+
def extra_repr(self) -> str:
|
| 366 |
+
return f"p={self.drop_prob}"
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
# Copied from transformers.models.swin.modeling_swin.SwinSelfAttention with Swin->DonutSwin
|
| 370 |
+
class DonutSwinSelfAttention(nn.Module):
|
| 371 |
+
def __init__(self, config, dim, num_heads, window_size):
|
| 372 |
+
super().__init__()
|
| 373 |
+
if dim % num_heads != 0:
|
| 374 |
+
raise ValueError(
|
| 375 |
+
f"The hidden size ({dim}) is not a multiple of the number of attention heads ({num_heads})"
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
self.num_attention_heads = num_heads
|
| 379 |
+
self.attention_head_size = int(dim / num_heads)
|
| 380 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 381 |
+
self.window_size = (
|
| 382 |
+
window_size if isinstance(window_size, collections.abc.Iterable) else (window_size, window_size)
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
self.relative_position_bias_table = nn.Parameter(
|
| 386 |
+
torch.zeros((2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1), num_heads)
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
# get pair-wise relative position index for each token inside the window
|
| 390 |
+
coords_h = torch.arange(self.window_size[0])
|
| 391 |
+
coords_w = torch.arange(self.window_size[1])
|
| 392 |
+
coords = torch.stack(meshgrid([coords_h, coords_w], indexing="ij"))
|
| 393 |
+
coords_flatten = torch.flatten(coords, 1)
|
| 394 |
+
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]
|
| 395 |
+
relative_coords = relative_coords.permute(1, 2, 0).contiguous()
|
| 396 |
+
relative_coords[:, :, 0] += self.window_size[0] - 1
|
| 397 |
+
relative_coords[:, :, 1] += self.window_size[1] - 1
|
| 398 |
+
relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
|
| 399 |
+
relative_position_index = relative_coords.sum(-1)
|
| 400 |
+
self.register_buffer("relative_position_index", relative_position_index)
|
| 401 |
+
|
| 402 |
+
self.query = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
|
| 403 |
+
self.key = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
|
| 404 |
+
self.value = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
|
| 405 |
+
|
| 406 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 407 |
+
|
| 408 |
+
def forward(
|
| 409 |
+
self,
|
| 410 |
+
hidden_states: torch.Tensor,
|
| 411 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 412 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 413 |
+
output_attentions: Optional[bool] = False,
|
| 414 |
+
) -> tuple[torch.Tensor]:
|
| 415 |
+
batch_size, dim, num_channels = hidden_states.shape
|
| 416 |
+
hidden_shape = (batch_size, dim, -1, self.attention_head_size)
|
| 417 |
+
|
| 418 |
+
query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 419 |
+
key_layer = self.key(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 420 |
+
value_layer = self.value(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 421 |
+
|
| 422 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 423 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 424 |
+
|
| 425 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 426 |
+
|
| 427 |
+
relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)]
|
| 428 |
+
relative_position_bias = relative_position_bias.view(
|
| 429 |
+
self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()
|
| 433 |
+
attention_scores = attention_scores + relative_position_bias.unsqueeze(0)
|
| 434 |
+
|
| 435 |
+
if attention_mask is not None:
|
| 436 |
+
# Apply the attention mask is (precomputed for all layers in DonutSwinModel forward() function)
|
| 437 |
+
mask_shape = attention_mask.shape[0]
|
| 438 |
+
attention_scores = attention_scores.view(
|
| 439 |
+
batch_size // mask_shape, mask_shape, self.num_attention_heads, dim, dim
|
| 440 |
+
)
|
| 441 |
+
attention_scores = attention_scores + attention_mask.unsqueeze(1).unsqueeze(0)
|
| 442 |
+
attention_scores = attention_scores.view(-1, self.num_attention_heads, dim, dim)
|
| 443 |
+
|
| 444 |
+
# Normalize the attention scores to probabilities.
|
| 445 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 446 |
+
|
| 447 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 448 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 449 |
+
attention_probs = self.dropout(attention_probs)
|
| 450 |
+
|
| 451 |
+
# Mask heads if we want to
|
| 452 |
+
if head_mask is not None:
|
| 453 |
+
attention_probs = attention_probs * head_mask
|
| 454 |
+
|
| 455 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 456 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 457 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 458 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 459 |
+
|
| 460 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 461 |
+
|
| 462 |
+
return outputs
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
# Copied from transformers.models.swin.modeling_swin.SwinSelfOutput
|
| 466 |
+
class DonutSwinSelfOutput(nn.Module):
|
| 467 |
+
def __init__(self, config, dim):
|
| 468 |
+
super().__init__()
|
| 469 |
+
self.dense = nn.Linear(dim, dim)
|
| 470 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 471 |
+
|
| 472 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 473 |
+
hidden_states = self.dense(hidden_states)
|
| 474 |
+
hidden_states = self.dropout(hidden_states)
|
| 475 |
+
|
| 476 |
+
return hidden_states
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
# Copied from transformers.models.swin.modeling_swin.SwinAttention with Swin->DonutSwin
|
| 480 |
+
class DonutSwinAttention(nn.Module):
|
| 481 |
+
def __init__(self, config, dim, num_heads, window_size):
|
| 482 |
+
super().__init__()
|
| 483 |
+
self.self = DonutSwinSelfAttention(config, dim, num_heads, window_size)
|
| 484 |
+
self.output = DonutSwinSelfOutput(config, dim)
|
| 485 |
+
self.pruned_heads = set()
|
| 486 |
+
|
| 487 |
+
def prune_heads(self, heads):
|
| 488 |
+
if len(heads) == 0:
|
| 489 |
+
return
|
| 490 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 491 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
# Prune linear layers
|
| 495 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
| 496 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
| 497 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
| 498 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 499 |
+
|
| 500 |
+
# Update hyper params and store pruned heads
|
| 501 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
| 502 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
| 503 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 504 |
+
|
| 505 |
+
def forward(
|
| 506 |
+
self,
|
| 507 |
+
hidden_states: torch.Tensor,
|
| 508 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 509 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 510 |
+
output_attentions: Optional[bool] = False,
|
| 511 |
+
) -> tuple[torch.Tensor]:
|
| 512 |
+
self_outputs = self.self(hidden_states, attention_mask, head_mask, output_attentions)
|
| 513 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 514 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 515 |
+
return outputs
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
# Copied from transformers.models.swin.modeling_swin.SwinIntermediate
|
| 519 |
+
class DonutSwinIntermediate(nn.Module):
|
| 520 |
+
def __init__(self, config, dim):
|
| 521 |
+
super().__init__()
|
| 522 |
+
self.dense = nn.Linear(dim, int(config.mlp_ratio * dim))
|
| 523 |
+
if isinstance(config.hidden_act, str):
|
| 524 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 525 |
+
else:
|
| 526 |
+
self.intermediate_act_fn = config.hidden_act
|
| 527 |
+
|
| 528 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 529 |
+
hidden_states = self.dense(hidden_states)
|
| 530 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 531 |
+
return hidden_states
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
# Copied from transformers.models.swin.modeling_swin.SwinOutput
|
| 535 |
+
class DonutSwinOutput(nn.Module):
|
| 536 |
+
def __init__(self, config, dim):
|
| 537 |
+
super().__init__()
|
| 538 |
+
self.dense = nn.Linear(int(config.mlp_ratio * dim), dim)
|
| 539 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 540 |
+
|
| 541 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 542 |
+
hidden_states = self.dense(hidden_states)
|
| 543 |
+
hidden_states = self.dropout(hidden_states)
|
| 544 |
+
return hidden_states
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
# Copied from transformers.models.swin.modeling_swin.SwinLayer with Swin->DonutSwin
|
| 548 |
+
class DonutSwinLayer(nn.Module):
|
| 549 |
+
def __init__(self, config, dim, input_resolution, num_heads, drop_path_rate=0.0, shift_size=0):
|
| 550 |
+
super().__init__()
|
| 551 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 552 |
+
self.shift_size = shift_size
|
| 553 |
+
self.window_size = config.window_size
|
| 554 |
+
self.input_resolution = input_resolution
|
| 555 |
+
self.layernorm_before = nn.LayerNorm(dim, eps=config.layer_norm_eps)
|
| 556 |
+
self.attention = DonutSwinAttention(config, dim, num_heads, window_size=self.window_size)
|
| 557 |
+
self.drop_path = DonutSwinDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
|
| 558 |
+
self.layernorm_after = nn.LayerNorm(dim, eps=config.layer_norm_eps)
|
| 559 |
+
self.intermediate = DonutSwinIntermediate(config, dim)
|
| 560 |
+
self.output = DonutSwinOutput(config, dim)
|
| 561 |
+
|
| 562 |
+
def set_shift_and_window_size(self, input_resolution):
|
| 563 |
+
if min(input_resolution) <= self.window_size:
|
| 564 |
+
# if window size is larger than input resolution, we don't partition windows
|
| 565 |
+
self.shift_size = torch_int(0)
|
| 566 |
+
self.window_size = (
|
| 567 |
+
torch.min(torch.tensor(input_resolution)) if torch.jit.is_tracing() else min(input_resolution)
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
def get_attn_mask(self, height, width, dtype, device):
|
| 571 |
+
if self.shift_size > 0:
|
| 572 |
+
# calculate attention mask for SW-MSA
|
| 573 |
+
img_mask = torch.zeros((1, height, width, 1), dtype=dtype, device=device)
|
| 574 |
+
height_slices = (
|
| 575 |
+
slice(0, -self.window_size),
|
| 576 |
+
slice(-self.window_size, -self.shift_size),
|
| 577 |
+
slice(-self.shift_size, None),
|
| 578 |
+
)
|
| 579 |
+
width_slices = (
|
| 580 |
+
slice(0, -self.window_size),
|
| 581 |
+
slice(-self.window_size, -self.shift_size),
|
| 582 |
+
slice(-self.shift_size, None),
|
| 583 |
+
)
|
| 584 |
+
count = 0
|
| 585 |
+
for height_slice in height_slices:
|
| 586 |
+
for width_slice in width_slices:
|
| 587 |
+
img_mask[:, height_slice, width_slice, :] = count
|
| 588 |
+
count += 1
|
| 589 |
+
|
| 590 |
+
mask_windows = window_partition(img_mask, self.window_size)
|
| 591 |
+
mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
|
| 592 |
+
attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
|
| 593 |
+
attn_mask = attn_mask.masked_fill(attn_mask != 0, -100.0).masked_fill(attn_mask == 0, 0.0)
|
| 594 |
+
else:
|
| 595 |
+
attn_mask = None
|
| 596 |
+
return attn_mask
|
| 597 |
+
|
| 598 |
+
def maybe_pad(self, hidden_states, height, width):
|
| 599 |
+
pad_right = (self.window_size - width % self.window_size) % self.window_size
|
| 600 |
+
pad_bottom = (self.window_size - height % self.window_size) % self.window_size
|
| 601 |
+
pad_values = (0, 0, 0, pad_right, 0, pad_bottom)
|
| 602 |
+
hidden_states = nn.functional.pad(hidden_states, pad_values)
|
| 603 |
+
return hidden_states, pad_values
|
| 604 |
+
|
| 605 |
+
def forward(
|
| 606 |
+
self,
|
| 607 |
+
hidden_states: torch.Tensor,
|
| 608 |
+
input_dimensions: tuple[int, int],
|
| 609 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 610 |
+
output_attentions: Optional[bool] = False,
|
| 611 |
+
always_partition: Optional[bool] = False,
|
| 612 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 613 |
+
if not always_partition:
|
| 614 |
+
self.set_shift_and_window_size(input_dimensions)
|
| 615 |
+
else:
|
| 616 |
+
pass
|
| 617 |
+
height, width = input_dimensions
|
| 618 |
+
batch_size, _, channels = hidden_states.size()
|
| 619 |
+
shortcut = hidden_states
|
| 620 |
+
|
| 621 |
+
hidden_states = self.layernorm_before(hidden_states)
|
| 622 |
+
|
| 623 |
+
hidden_states = hidden_states.view(batch_size, height, width, channels)
|
| 624 |
+
|
| 625 |
+
# pad hidden_states to multiples of window size
|
| 626 |
+
hidden_states, pad_values = self.maybe_pad(hidden_states, height, width)
|
| 627 |
+
|
| 628 |
+
_, height_pad, width_pad, _ = hidden_states.shape
|
| 629 |
+
# cyclic shift
|
| 630 |
+
if self.shift_size > 0:
|
| 631 |
+
shifted_hidden_states = torch.roll(hidden_states, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
|
| 632 |
+
else:
|
| 633 |
+
shifted_hidden_states = hidden_states
|
| 634 |
+
|
| 635 |
+
# partition windows
|
| 636 |
+
hidden_states_windows = window_partition(shifted_hidden_states, self.window_size)
|
| 637 |
+
hidden_states_windows = hidden_states_windows.view(-1, self.window_size * self.window_size, channels)
|
| 638 |
+
attn_mask = self.get_attn_mask(
|
| 639 |
+
height_pad, width_pad, dtype=hidden_states.dtype, device=hidden_states_windows.device
|
| 640 |
+
)
|
| 641 |
+
|
| 642 |
+
attention_outputs = self.attention(
|
| 643 |
+
hidden_states_windows, attn_mask, head_mask, output_attentions=output_attentions
|
| 644 |
+
)
|
| 645 |
+
|
| 646 |
+
attention_output = attention_outputs[0]
|
| 647 |
+
|
| 648 |
+
attention_windows = attention_output.view(-1, self.window_size, self.window_size, channels)
|
| 649 |
+
shifted_windows = window_reverse(attention_windows, self.window_size, height_pad, width_pad)
|
| 650 |
+
|
| 651 |
+
# reverse cyclic shift
|
| 652 |
+
if self.shift_size > 0:
|
| 653 |
+
attention_windows = torch.roll(shifted_windows, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
|
| 654 |
+
else:
|
| 655 |
+
attention_windows = shifted_windows
|
| 656 |
+
|
| 657 |
+
was_padded = pad_values[3] > 0 or pad_values[5] > 0
|
| 658 |
+
if was_padded:
|
| 659 |
+
attention_windows = attention_windows[:, :height, :width, :].contiguous()
|
| 660 |
+
|
| 661 |
+
attention_windows = attention_windows.view(batch_size, height * width, channels)
|
| 662 |
+
|
| 663 |
+
hidden_states = shortcut + self.drop_path(attention_windows)
|
| 664 |
+
|
| 665 |
+
layer_output = self.layernorm_after(hidden_states)
|
| 666 |
+
layer_output = self.intermediate(layer_output)
|
| 667 |
+
layer_output = hidden_states + self.output(layer_output)
|
| 668 |
+
|
| 669 |
+
layer_outputs = (layer_output, attention_outputs[1]) if output_attentions else (layer_output,)
|
| 670 |
+
return layer_outputs
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
# Copied from transformers.models.swin.modeling_swin.SwinStage with Swin->DonutSwin
|
| 674 |
+
class DonutSwinStage(GradientCheckpointingLayer):
|
| 675 |
+
def __init__(self, config, dim, input_resolution, depth, num_heads, drop_path, downsample):
|
| 676 |
+
super().__init__()
|
| 677 |
+
self.config = config
|
| 678 |
+
self.dim = dim
|
| 679 |
+
self.blocks = nn.ModuleList(
|
| 680 |
+
[
|
| 681 |
+
DonutSwinLayer(
|
| 682 |
+
config=config,
|
| 683 |
+
dim=dim,
|
| 684 |
+
input_resolution=input_resolution,
|
| 685 |
+
num_heads=num_heads,
|
| 686 |
+
drop_path_rate=drop_path[i],
|
| 687 |
+
shift_size=0 if (i % 2 == 0) else config.window_size // 2,
|
| 688 |
+
)
|
| 689 |
+
for i in range(depth)
|
| 690 |
+
]
|
| 691 |
+
)
|
| 692 |
+
|
| 693 |
+
# patch merging layer
|
| 694 |
+
if downsample is not None:
|
| 695 |
+
self.downsample = downsample(input_resolution, dim=dim, norm_layer=nn.LayerNorm)
|
| 696 |
+
else:
|
| 697 |
+
self.downsample = None
|
| 698 |
+
|
| 699 |
+
self.pointing = False
|
| 700 |
+
|
| 701 |
+
def forward(
|
| 702 |
+
self,
|
| 703 |
+
hidden_states: torch.Tensor,
|
| 704 |
+
input_dimensions: tuple[int, int],
|
| 705 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 706 |
+
output_attentions: Optional[bool] = False,
|
| 707 |
+
always_partition: Optional[bool] = False,
|
| 708 |
+
) -> tuple[torch.Tensor]:
|
| 709 |
+
height, width = input_dimensions
|
| 710 |
+
for i, layer_module in enumerate(self.blocks):
|
| 711 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 712 |
+
|
| 713 |
+
layer_outputs = layer_module(
|
| 714 |
+
hidden_states, input_dimensions, layer_head_mask, output_attentions, always_partition
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
hidden_states = layer_outputs[0]
|
| 718 |
+
|
| 719 |
+
hidden_states_before_downsampling = hidden_states
|
| 720 |
+
if self.downsample is not None:
|
| 721 |
+
height_downsampled, width_downsampled = (height + 1) // 2, (width + 1) // 2
|
| 722 |
+
output_dimensions = (height, width, height_downsampled, width_downsampled)
|
| 723 |
+
hidden_states = self.downsample(hidden_states_before_downsampling, input_dimensions)
|
| 724 |
+
else:
|
| 725 |
+
output_dimensions = (height, width, height, width)
|
| 726 |
+
|
| 727 |
+
stage_outputs = (hidden_states, hidden_states_before_downsampling, output_dimensions)
|
| 728 |
+
|
| 729 |
+
if output_attentions:
|
| 730 |
+
stage_outputs += layer_outputs[1:]
|
| 731 |
+
return stage_outputs
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
# Copied from transformers.models.swin.modeling_swin.SwinEncoder with Swin->DonutSwin
|
| 735 |
+
class DonutSwinEncoder(nn.Module):
|
| 736 |
+
def __init__(self, config, grid_size):
|
| 737 |
+
super().__init__()
|
| 738 |
+
self.num_layers = len(config.depths)
|
| 739 |
+
self.config = config
|
| 740 |
+
dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu")]
|
| 741 |
+
self.layers = nn.ModuleList(
|
| 742 |
+
[
|
| 743 |
+
DonutSwinStage(
|
| 744 |
+
config=config,
|
| 745 |
+
dim=int(config.embed_dim * 2**i_layer),
|
| 746 |
+
input_resolution=(grid_size[0] // (2**i_layer), grid_size[1] // (2**i_layer)),
|
| 747 |
+
depth=config.depths[i_layer],
|
| 748 |
+
num_heads=config.num_heads[i_layer],
|
| 749 |
+
drop_path=dpr[sum(config.depths[:i_layer]) : sum(config.depths[: i_layer + 1])],
|
| 750 |
+
downsample=DonutSwinPatchMerging if (i_layer < self.num_layers - 1) else None,
|
| 751 |
+
)
|
| 752 |
+
for i_layer in range(self.num_layers)
|
| 753 |
+
]
|
| 754 |
+
)
|
| 755 |
+
|
| 756 |
+
self.gradient_checkpointing = False
|
| 757 |
+
|
| 758 |
+
def forward(
|
| 759 |
+
self,
|
| 760 |
+
hidden_states: torch.Tensor,
|
| 761 |
+
input_dimensions: tuple[int, int],
|
| 762 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 763 |
+
output_attentions: Optional[bool] = False,
|
| 764 |
+
output_hidden_states: Optional[bool] = False,
|
| 765 |
+
output_hidden_states_before_downsampling: Optional[bool] = False,
|
| 766 |
+
always_partition: Optional[bool] = False,
|
| 767 |
+
return_dict: Optional[bool] = True,
|
| 768 |
+
) -> Union[tuple, DonutSwinEncoderOutput]:
|
| 769 |
+
all_hidden_states = () if output_hidden_states else None
|
| 770 |
+
all_reshaped_hidden_states = () if output_hidden_states else None
|
| 771 |
+
all_self_attentions = () if output_attentions else None
|
| 772 |
+
|
| 773 |
+
if output_hidden_states:
|
| 774 |
+
batch_size, _, hidden_size = hidden_states.shape
|
| 775 |
+
# rearrange b (h w) c -> b c h w
|
| 776 |
+
reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
|
| 777 |
+
reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
|
| 778 |
+
all_hidden_states += (hidden_states,)
|
| 779 |
+
all_reshaped_hidden_states += (reshaped_hidden_state,)
|
| 780 |
+
|
| 781 |
+
for i, layer_module in enumerate(self.layers):
|
| 782 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 783 |
+
|
| 784 |
+
layer_outputs = layer_module(
|
| 785 |
+
hidden_states, input_dimensions, layer_head_mask, output_attentions, always_partition
|
| 786 |
+
)
|
| 787 |
+
|
| 788 |
+
hidden_states = layer_outputs[0]
|
| 789 |
+
hidden_states_before_downsampling = layer_outputs[1]
|
| 790 |
+
output_dimensions = layer_outputs[2]
|
| 791 |
+
|
| 792 |
+
input_dimensions = (output_dimensions[-2], output_dimensions[-1])
|
| 793 |
+
|
| 794 |
+
if output_hidden_states and output_hidden_states_before_downsampling:
|
| 795 |
+
batch_size, _, hidden_size = hidden_states_before_downsampling.shape
|
| 796 |
+
# rearrange b (h w) c -> b c h w
|
| 797 |
+
# here we use the original (not downsampled) height and width
|
| 798 |
+
reshaped_hidden_state = hidden_states_before_downsampling.view(
|
| 799 |
+
batch_size, *(output_dimensions[0], output_dimensions[1]), hidden_size
|
| 800 |
+
)
|
| 801 |
+
reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
|
| 802 |
+
all_hidden_states += (hidden_states_before_downsampling,)
|
| 803 |
+
all_reshaped_hidden_states += (reshaped_hidden_state,)
|
| 804 |
+
elif output_hidden_states and not output_hidden_states_before_downsampling:
|
| 805 |
+
batch_size, _, hidden_size = hidden_states.shape
|
| 806 |
+
# rearrange b (h w) c -> b c h w
|
| 807 |
+
reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
|
| 808 |
+
reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
|
| 809 |
+
all_hidden_states += (hidden_states,)
|
| 810 |
+
all_reshaped_hidden_states += (reshaped_hidden_state,)
|
| 811 |
+
|
| 812 |
+
if output_attentions:
|
| 813 |
+
all_self_attentions += layer_outputs[3:]
|
| 814 |
+
|
| 815 |
+
if not return_dict:
|
| 816 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
|
| 817 |
+
|
| 818 |
+
return DonutSwinEncoderOutput(
|
| 819 |
+
last_hidden_state=hidden_states,
|
| 820 |
+
hidden_states=all_hidden_states,
|
| 821 |
+
attentions=all_self_attentions,
|
| 822 |
+
reshaped_hidden_states=all_reshaped_hidden_states,
|
| 823 |
+
)
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
@auto_docstring
|
| 827 |
+
# Copied from transformers.models.swin.modeling_swin.SwinPreTrainedModel with Swin->DonutSwin,swin->donut
|
| 828 |
+
class DonutSwinPreTrainedModel(PreTrainedModel):
|
| 829 |
+
config: DonutSwinConfig
|
| 830 |
+
base_model_prefix = "donut"
|
| 831 |
+
main_input_name = "pixel_values"
|
| 832 |
+
supports_gradient_checkpointing = True
|
| 833 |
+
_no_split_modules = ["DonutSwinStage"]
|
| 834 |
+
|
| 835 |
+
def _init_weights(self, module):
|
| 836 |
+
"""Initialize the weights"""
|
| 837 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 838 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 839 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 840 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 841 |
+
if module.bias is not None:
|
| 842 |
+
module.bias.data.zero_()
|
| 843 |
+
elif isinstance(module, nn.LayerNorm):
|
| 844 |
+
module.bias.data.zero_()
|
| 845 |
+
module.weight.data.fill_(1.0)
|
| 846 |
+
elif isinstance(module, DonutSwinEmbeddings):
|
| 847 |
+
if module.mask_token is not None:
|
| 848 |
+
module.mask_token.data.zero_()
|
| 849 |
+
if module.position_embeddings is not None:
|
| 850 |
+
module.position_embeddings.data.zero_()
|
| 851 |
+
elif isinstance(module, DonutSwinSelfAttention):
|
| 852 |
+
module.relative_position_bias_table.data.zero_()
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
@auto_docstring
|
| 856 |
+
class DonutSwinModel(DonutSwinPreTrainedModel):
|
| 857 |
+
def __init__(self, config, add_pooling_layer=True, use_mask_token=False):
|
| 858 |
+
r"""
|
| 859 |
+
add_pooling_layer (bool, *optional*, defaults to `True`):
|
| 860 |
+
Whether to add a pooling layer
|
| 861 |
+
use_mask_token (`bool`, *optional*, defaults to `False`):
|
| 862 |
+
Whether to use a mask token for masked image modeling.
|
| 863 |
+
"""
|
| 864 |
+
super().__init__(config)
|
| 865 |
+
self.config = config
|
| 866 |
+
self.num_layers = len(config.depths)
|
| 867 |
+
self.num_features = int(config.embed_dim * 2 ** (self.num_layers - 1))
|
| 868 |
+
|
| 869 |
+
self.embeddings = DonutSwinEmbeddings(config, use_mask_token=use_mask_token)
|
| 870 |
+
self.encoder = DonutSwinEncoder(config, self.embeddings.patch_grid)
|
| 871 |
+
|
| 872 |
+
self.pooler = nn.AdaptiveAvgPool1d(1) if add_pooling_layer else None
|
| 873 |
+
|
| 874 |
+
# Initialize weights and apply final processing
|
| 875 |
+
self.post_init()
|
| 876 |
+
|
| 877 |
+
def get_input_embeddings(self):
|
| 878 |
+
return self.embeddings.patch_embeddings
|
| 879 |
+
|
| 880 |
+
def _prune_heads(self, heads_to_prune):
|
| 881 |
+
"""
|
| 882 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 883 |
+
class PreTrainedModel
|
| 884 |
+
"""
|
| 885 |
+
for layer, heads in heads_to_prune.items():
|
| 886 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 887 |
+
|
| 888 |
+
@auto_docstring
|
| 889 |
+
def forward(
|
| 890 |
+
self,
|
| 891 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 892 |
+
bool_masked_pos: Optional[torch.BoolTensor] = None,
|
| 893 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 894 |
+
output_attentions: Optional[bool] = None,
|
| 895 |
+
output_hidden_states: Optional[bool] = None,
|
| 896 |
+
interpolate_pos_encoding: bool = False,
|
| 897 |
+
return_dict: Optional[bool] = None,
|
| 898 |
+
) -> Union[tuple, DonutSwinModelOutput]:
|
| 899 |
+
r"""
|
| 900 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
|
| 901 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
|
| 902 |
+
"""
|
| 903 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 904 |
+
output_hidden_states = (
|
| 905 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 906 |
+
)
|
| 907 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 908 |
+
|
| 909 |
+
if pixel_values is None:
|
| 910 |
+
raise ValueError("You have to specify pixel_values")
|
| 911 |
+
|
| 912 |
+
# Prepare head mask if needed
|
| 913 |
+
# 1.0 in head_mask indicate we keep the head
|
| 914 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 915 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 916 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 917 |
+
head_mask = self.get_head_mask(head_mask, len(self.config.depths))
|
| 918 |
+
|
| 919 |
+
embedding_output, input_dimensions = self.embeddings(
|
| 920 |
+
pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding
|
| 921 |
+
)
|
| 922 |
+
|
| 923 |
+
encoder_outputs = self.encoder(
|
| 924 |
+
embedding_output,
|
| 925 |
+
input_dimensions,
|
| 926 |
+
head_mask=head_mask,
|
| 927 |
+
output_attentions=output_attentions,
|
| 928 |
+
output_hidden_states=output_hidden_states,
|
| 929 |
+
return_dict=return_dict,
|
| 930 |
+
)
|
| 931 |
+
|
| 932 |
+
sequence_output = encoder_outputs[0]
|
| 933 |
+
|
| 934 |
+
pooled_output = None
|
| 935 |
+
if self.pooler is not None:
|
| 936 |
+
pooled_output = self.pooler(sequence_output.transpose(1, 2))
|
| 937 |
+
pooled_output = torch.flatten(pooled_output, 1)
|
| 938 |
+
|
| 939 |
+
if not return_dict:
|
| 940 |
+
output = (sequence_output, pooled_output) + encoder_outputs[1:]
|
| 941 |
+
|
| 942 |
+
return output
|
| 943 |
+
|
| 944 |
+
return DonutSwinModelOutput(
|
| 945 |
+
last_hidden_state=sequence_output,
|
| 946 |
+
pooler_output=pooled_output,
|
| 947 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 948 |
+
attentions=encoder_outputs.attentions,
|
| 949 |
+
reshaped_hidden_states=encoder_outputs.reshaped_hidden_states,
|
| 950 |
+
)
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
@auto_docstring(
|
| 954 |
+
custom_intro="""
|
| 955 |
+
DonutSwin Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
|
| 956 |
+
the [CLS] token) e.g. for ImageNet.
|
| 957 |
+
|
| 958 |
+
<Tip>
|
| 959 |
+
|
| 960 |
+
Note that it's possible to fine-tune DonutSwin on higher resolution images than the ones it has been trained on, by
|
| 961 |
+
setting `interpolate_pos_encoding` to `True` in the forward of the model. This will interpolate the pre-trained
|
| 962 |
+
position embeddings to the higher resolution.
|
| 963 |
+
|
| 964 |
+
</Tip>
|
| 965 |
+
"""
|
| 966 |
+
)
|
| 967 |
+
# Copied from transformers.models.swin.modeling_swin.SwinForImageClassification with Swin->DonutSwin,swin->donut
|
| 968 |
+
class DonutSwinForImageClassification(DonutSwinPreTrainedModel):
|
| 969 |
+
def __init__(self, config):
|
| 970 |
+
super().__init__(config)
|
| 971 |
+
|
| 972 |
+
self.num_labels = config.num_labels
|
| 973 |
+
self.donut = DonutSwinModel(config)
|
| 974 |
+
|
| 975 |
+
# Classifier head
|
| 976 |
+
self.classifier = (
|
| 977 |
+
nn.Linear(self.donut.num_features, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 978 |
+
)
|
| 979 |
+
|
| 980 |
+
# Initialize weights and apply final processing
|
| 981 |
+
self.post_init()
|
| 982 |
+
|
| 983 |
+
@auto_docstring
|
| 984 |
+
def forward(
|
| 985 |
+
self,
|
| 986 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 987 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 988 |
+
labels: Optional[torch.LongTensor] = None,
|
| 989 |
+
output_attentions: Optional[bool] = None,
|
| 990 |
+
output_hidden_states: Optional[bool] = None,
|
| 991 |
+
interpolate_pos_encoding: bool = False,
|
| 992 |
+
return_dict: Optional[bool] = None,
|
| 993 |
+
) -> Union[tuple, DonutSwinImageClassifierOutput]:
|
| 994 |
+
r"""
|
| 995 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 996 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 997 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 998 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 999 |
+
"""
|
| 1000 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1001 |
+
|
| 1002 |
+
outputs = self.donut(
|
| 1003 |
+
pixel_values,
|
| 1004 |
+
head_mask=head_mask,
|
| 1005 |
+
output_attentions=output_attentions,
|
| 1006 |
+
output_hidden_states=output_hidden_states,
|
| 1007 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1008 |
+
return_dict=return_dict,
|
| 1009 |
+
)
|
| 1010 |
+
|
| 1011 |
+
pooled_output = outputs[1]
|
| 1012 |
+
|
| 1013 |
+
logits = self.classifier(pooled_output)
|
| 1014 |
+
|
| 1015 |
+
loss = None
|
| 1016 |
+
if labels is not None:
|
| 1017 |
+
loss = self.loss_function(logits=logits, labels=labels, pooled_logits=logits, config=self.config)
|
| 1018 |
+
|
| 1019 |
+
if not return_dict:
|
| 1020 |
+
output = (logits,) + outputs[2:]
|
| 1021 |
+
return ((loss,) + output) if loss is not None else output
|
| 1022 |
+
|
| 1023 |
+
return DonutSwinImageClassifierOutput(
|
| 1024 |
+
loss=loss,
|
| 1025 |
+
logits=logits,
|
| 1026 |
+
hidden_states=outputs.hidden_states,
|
| 1027 |
+
attentions=outputs.attentions,
|
| 1028 |
+
reshaped_hidden_states=outputs.reshaped_hidden_states,
|
| 1029 |
+
)
|
| 1030 |
+
|
| 1031 |
+
|
| 1032 |
+
__all__ = ["DonutSwinModel", "DonutSwinPreTrainedModel", "DonutSwinForImageClassification"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/donut/processing_donut.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Processor class for Donut.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import re
|
| 20 |
+
import warnings
|
| 21 |
+
from contextlib import contextmanager
|
| 22 |
+
from typing import Optional, Union
|
| 23 |
+
|
| 24 |
+
from ...image_utils import ImageInput
|
| 25 |
+
from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
|
| 26 |
+
from ...tokenization_utils_base import PreTokenizedInput, TextInput
|
| 27 |
+
from ...utils import logging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class DonutProcessorKwargs(ProcessingKwargs, total=False):
|
| 31 |
+
_defaults = {}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
logger = logging.get_logger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class DonutProcessor(ProcessorMixin):
|
| 38 |
+
r"""
|
| 39 |
+
Constructs a Donut processor which wraps a Donut image processor and an XLMRoBERTa tokenizer into a single
|
| 40 |
+
processor.
|
| 41 |
+
|
| 42 |
+
[`DonutProcessor`] offers all the functionalities of [`DonutImageProcessor`] and
|
| 43 |
+
[`XLMRobertaTokenizer`/`XLMRobertaTokenizerFast`]. See the [`~DonutProcessor.__call__`] and
|
| 44 |
+
[`~DonutProcessor.decode`] for more information.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
image_processor ([`DonutImageProcessor`], *optional*):
|
| 48 |
+
An instance of [`DonutImageProcessor`]. The image processor is a required input.
|
| 49 |
+
tokenizer ([`XLMRobertaTokenizer`/`XLMRobertaTokenizerFast`], *optional*):
|
| 50 |
+
An instance of [`XLMRobertaTokenizer`/`XLMRobertaTokenizerFast`]. The tokenizer is a required input.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
attributes = ["image_processor", "tokenizer"]
|
| 54 |
+
image_processor_class = "AutoImageProcessor"
|
| 55 |
+
tokenizer_class = "AutoTokenizer"
|
| 56 |
+
|
| 57 |
+
def __init__(self, image_processor=None, tokenizer=None, **kwargs):
|
| 58 |
+
feature_extractor = None
|
| 59 |
+
if "feature_extractor" in kwargs:
|
| 60 |
+
warnings.warn(
|
| 61 |
+
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
|
| 62 |
+
" instead.",
|
| 63 |
+
FutureWarning,
|
| 64 |
+
)
|
| 65 |
+
feature_extractor = kwargs.pop("feature_extractor")
|
| 66 |
+
|
| 67 |
+
image_processor = image_processor if image_processor is not None else feature_extractor
|
| 68 |
+
if image_processor is None:
|
| 69 |
+
raise ValueError("You need to specify an `image_processor`.")
|
| 70 |
+
if tokenizer is None:
|
| 71 |
+
raise ValueError("You need to specify a `tokenizer`.")
|
| 72 |
+
|
| 73 |
+
super().__init__(image_processor, tokenizer)
|
| 74 |
+
self.current_processor = self.image_processor
|
| 75 |
+
self._in_target_context_manager = False
|
| 76 |
+
|
| 77 |
+
def __call__(
|
| 78 |
+
self,
|
| 79 |
+
images: ImageInput = None,
|
| 80 |
+
text: Optional[Union[str, list[str], TextInput, PreTokenizedInput]] = None,
|
| 81 |
+
audio=None,
|
| 82 |
+
videos=None,
|
| 83 |
+
**kwargs: Unpack[DonutProcessorKwargs],
|
| 84 |
+
):
|
| 85 |
+
"""
|
| 86 |
+
When used in normal mode, this method forwards all its arguments to AutoImageProcessor's
|
| 87 |
+
[`~AutoImageProcessor.__call__`] and returns its output. If used in the context
|
| 88 |
+
[`~DonutProcessor.as_target_processor`] this method forwards all its arguments to DonutTokenizer's
|
| 89 |
+
[`~DonutTokenizer.__call__`]. Please refer to the docstring of the above two methods for more information.
|
| 90 |
+
"""
|
| 91 |
+
if self._in_target_context_manager:
|
| 92 |
+
return self.current_processor(images, text, **kwargs)
|
| 93 |
+
|
| 94 |
+
if images is None and text is None:
|
| 95 |
+
raise ValueError("You need to specify either an `images` or `text` input to process.")
|
| 96 |
+
|
| 97 |
+
output_kwargs = self._merge_kwargs(
|
| 98 |
+
DonutProcessorKwargs,
|
| 99 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 100 |
+
**kwargs,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
if images is not None:
|
| 104 |
+
inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
|
| 105 |
+
if text is not None:
|
| 106 |
+
if images is not None:
|
| 107 |
+
output_kwargs["text_kwargs"].setdefault("add_special_tokens", False)
|
| 108 |
+
encodings = self.tokenizer(text, **output_kwargs["text_kwargs"])
|
| 109 |
+
|
| 110 |
+
if text is None:
|
| 111 |
+
return inputs
|
| 112 |
+
elif images is None:
|
| 113 |
+
return encodings
|
| 114 |
+
else:
|
| 115 |
+
inputs["labels"] = encodings["input_ids"] # for BC
|
| 116 |
+
inputs["input_ids"] = encodings["input_ids"]
|
| 117 |
+
return inputs
|
| 118 |
+
|
| 119 |
+
def batch_decode(self, *args, **kwargs):
|
| 120 |
+
"""
|
| 121 |
+
This method forwards all its arguments to DonutTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please refer
|
| 122 |
+
to the docstring of this method for more information.
|
| 123 |
+
"""
|
| 124 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
| 125 |
+
|
| 126 |
+
def decode(self, *args, **kwargs):
|
| 127 |
+
"""
|
| 128 |
+
This method forwards all its arguments to DonutTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to the
|
| 129 |
+
docstring of this method for more information.
|
| 130 |
+
"""
|
| 131 |
+
return self.tokenizer.decode(*args, **kwargs)
|
| 132 |
+
|
| 133 |
+
@contextmanager
|
| 134 |
+
def as_target_processor(self):
|
| 135 |
+
"""
|
| 136 |
+
Temporarily sets the tokenizer for processing the input. Useful for encoding the labels when fine-tuning TrOCR.
|
| 137 |
+
"""
|
| 138 |
+
warnings.warn(
|
| 139 |
+
"`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
|
| 140 |
+
"labels by using the argument `text` of the regular `__call__` method (either in the same call as "
|
| 141 |
+
"your images inputs, or in a separate call."
|
| 142 |
+
)
|
| 143 |
+
self._in_target_context_manager = True
|
| 144 |
+
self.current_processor = self.tokenizer
|
| 145 |
+
yield
|
| 146 |
+
self.current_processor = self.image_processor
|
| 147 |
+
self._in_target_context_manager = False
|
| 148 |
+
|
| 149 |
+
def token2json(self, tokens, is_inner_value=False, added_vocab=None):
|
| 150 |
+
"""
|
| 151 |
+
Convert a (generated) token sequence into an ordered JSON format.
|
| 152 |
+
"""
|
| 153 |
+
if added_vocab is None:
|
| 154 |
+
added_vocab = self.tokenizer.get_added_vocab()
|
| 155 |
+
|
| 156 |
+
output = {}
|
| 157 |
+
|
| 158 |
+
while tokens:
|
| 159 |
+
# We want r"<s_(.*?)>" but without ReDOS risk, so do it manually in two parts
|
| 160 |
+
potential_start = re.search(r"<s_", tokens, re.IGNORECASE)
|
| 161 |
+
if potential_start is None:
|
| 162 |
+
break
|
| 163 |
+
start_token = tokens[potential_start.start() :]
|
| 164 |
+
if ">" not in start_token:
|
| 165 |
+
break
|
| 166 |
+
start_token = start_token[: start_token.index(">") + 1]
|
| 167 |
+
key = start_token[len("<s_") : -len(">")]
|
| 168 |
+
key_escaped = re.escape(key)
|
| 169 |
+
|
| 170 |
+
end_token = re.search(rf"</s_{key_escaped}>", tokens, re.IGNORECASE)
|
| 171 |
+
if end_token is None:
|
| 172 |
+
tokens = tokens.replace(start_token, "")
|
| 173 |
+
else:
|
| 174 |
+
end_token = end_token.group()
|
| 175 |
+
start_token_escaped = re.escape(start_token)
|
| 176 |
+
end_token_escaped = re.escape(end_token)
|
| 177 |
+
content = re.search(
|
| 178 |
+
f"{start_token_escaped}(.*?){end_token_escaped}", tokens, re.IGNORECASE | re.DOTALL
|
| 179 |
+
)
|
| 180 |
+
if content is not None:
|
| 181 |
+
content = content.group(1).strip()
|
| 182 |
+
if r"<s_" in content and r"</s_" in content: # non-leaf node
|
| 183 |
+
value = self.token2json(content, is_inner_value=True, added_vocab=added_vocab)
|
| 184 |
+
if value:
|
| 185 |
+
if len(value) == 1:
|
| 186 |
+
value = value[0]
|
| 187 |
+
output[key] = value
|
| 188 |
+
else: # leaf nodes
|
| 189 |
+
output[key] = []
|
| 190 |
+
for leaf in content.split(r"<sep/>"):
|
| 191 |
+
leaf = leaf.strip()
|
| 192 |
+
if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>":
|
| 193 |
+
leaf = leaf[1:-2] # for categorical special tokens
|
| 194 |
+
output[key].append(leaf)
|
| 195 |
+
if len(output[key]) == 1:
|
| 196 |
+
output[key] = output[key][0]
|
| 197 |
+
|
| 198 |
+
tokens = tokens[tokens.find(end_token) + len(end_token) :].strip()
|
| 199 |
+
if tokens[:6] == r"<sep/>": # non-leaf nodes
|
| 200 |
+
return [output] + self.token2json(tokens[6:], is_inner_value=True, added_vocab=added_vocab)
|
| 201 |
+
|
| 202 |
+
if output:
|
| 203 |
+
return [output] if is_inner_value else output
|
| 204 |
+
else:
|
| 205 |
+
return [] if is_inner_value else {"text_sequence": tokens}
|
| 206 |
+
|
| 207 |
+
@property
|
| 208 |
+
def feature_extractor_class(self):
|
| 209 |
+
warnings.warn(
|
| 210 |
+
"`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
|
| 211 |
+
FutureWarning,
|
| 212 |
+
)
|
| 213 |
+
return self.image_processor_class
|
| 214 |
+
|
| 215 |
+
@property
|
| 216 |
+
def feature_extractor(self):
|
| 217 |
+
warnings.warn(
|
| 218 |
+
"`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
|
| 219 |
+
FutureWarning,
|
| 220 |
+
)
|
| 221 |
+
return self.image_processor
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
__all__ = ["DonutProcessor"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dots1/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 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_dots1 import *
|
| 22 |
+
from .modeling_dots1 import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dots1/configuration_dots1.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The rednote-hilab team and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
from ...configuration_utils import PretrainedConfig, layer_type_validation
|
| 16 |
+
from ...utils import logging
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
logger = logging.get_logger(__name__)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Dots1Config(PretrainedConfig):
|
| 23 |
+
r"""
|
| 24 |
+
This is the configuration class to store the configuration of a [`Dots1Model`]. It is used to instantiate a
|
| 25 |
+
`dots.llm1` model according to the specified arguments, defining the model architecture. Instantiating a
|
| 26 |
+
configuration with the defaults will yield a similar configuration to that of
|
| 27 |
+
[rednote-hilab/dots.llm1.base](https://huggingface.co/rednote-hilab/dots.llm1.base).
|
| 28 |
+
|
| 29 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 30 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
vocab_size (`int`, *optional*, defaults to 152064):
|
| 34 |
+
Vocabulary size of the model. Defines the number of different tokens that can be represented by the
|
| 35 |
+
`input_ids` passed when calling [`Dots1Model`].
|
| 36 |
+
hidden_size (`int`, *optional*, defaults to 4608):
|
| 37 |
+
Dimension of the hidden representations.
|
| 38 |
+
intermediate_size (`int`, *optional*, defaults to 10944):
|
| 39 |
+
Dimension of the MLP representations.
|
| 40 |
+
moe_intermediate_size (`int`, *optional*, defaults to 1408):
|
| 41 |
+
Dimension of the MoE representations.
|
| 42 |
+
num_hidden_layers (`int`, *optional*, defaults to 62):
|
| 43 |
+
Number of hidden layers in the Transformer decoder.
|
| 44 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
| 45 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 46 |
+
num_key_value_heads (`int`, *optional*, defaults to 32):
|
| 47 |
+
Number of key/value heads for Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, Multi
|
| 48 |
+
Head Attention (MHA) is used. If `num_key_value_heads=1`, Multi Query Attention (MQA) is used. Otherwise,
|
| 49 |
+
Grouped Query Attention (GQA) is used. If not specified, defaults to `num_attention_heads`.
|
| 50 |
+
n_shared_experts (`int`, *optional*, default=None):
|
| 51 |
+
Number of shared experts. None means dense model.
|
| 52 |
+
n_routed_experts (`int`, *optional*, default=None):
|
| 53 |
+
Number of routed experts. None means dense model.
|
| 54 |
+
n_group (`int`, *optional*, defaults to 1):
|
| 55 |
+
Number of groups for routed experts.
|
| 56 |
+
topk_group (`int`, *optional*, defaults to 1):
|
| 57 |
+
Number of selected groups for each token (selected experts only within `topk_group` groups).
|
| 58 |
+
num_experts_per_tok (`int`, *optional*, default=None):
|
| 59 |
+
Number of selected experts. None means dense model.
|
| 60 |
+
first_k_dense_replace (`int`, *optional*, defaults to 0):
|
| 61 |
+
Number of dense layers at the beginning of the model before the first MoE layer.
|
| 62 |
+
norm_topk_prob (`bool`, *optional*, defaults to `False`):
|
| 63 |
+
Whether to normalize the weights of the routed experts.
|
| 64 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 65 |
+
The non-linear activation function (function or string).
|
| 66 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
| 67 |
+
Maximum sequence length the model might ever be used with.
|
| 68 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 69 |
+
Standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 70 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 71 |
+
Epsilon used by the RMS normalization layers.
|
| 72 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 73 |
+
Whether or not the model should return the last key/values attentions. Only relevant if `config.is_decoder=True`.
|
| 74 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 75 |
+
Whether to tie the input and output word embeddings.
|
| 76 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
| 77 |
+
The base period of the RoPE embeddings.
|
| 78 |
+
rope_scaling (`dict`, *optional*):
|
| 79 |
+
Dictionary for scaling RoPE embeddings. Supports `{"type": strategy name, "factor": scaling factor}`.
|
| 80 |
+
attention_bias (`bool`, *optional*, defaults to `False`):
|
| 81 |
+
Whether to use a bias in the self-attention projections.
|
| 82 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 83 |
+
Dropout ratio for the attention probabilities.
|
| 84 |
+
routed_scaling_factor (`float`, *optional*, defaults to 1.0):
|
| 85 |
+
Scaling factor for routed experts.
|
| 86 |
+
sliding_window (`int`, *optional*, defaults to 4096):
|
| 87 |
+
Size of the sliding window for attention. If not specified, defaults to `4096`.
|
| 88 |
+
max_window_layers (`int`, *optional*, defaults to 62):
|
| 89 |
+
The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any
|
| 90 |
+
additional layer afterwards will use SWA (Sliding Window Attention).
|
| 91 |
+
layer_types (`list`, *optional*):
|
| 92 |
+
Attention pattern for each layer.
|
| 93 |
+
|
| 94 |
+
Examples:
|
| 95 |
+
```python
|
| 96 |
+
>>> from transformers import Dots1Model, Dots1Config
|
| 97 |
+
|
| 98 |
+
>>> # Initializing a Dots1 style configuration
|
| 99 |
+
>>> configuration = Dots1Config()
|
| 100 |
+
|
| 101 |
+
>>> # Accessing the model configuration
|
| 102 |
+
>>> configuration = model.config
|
| 103 |
+
```
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
model_type = "dots1"
|
| 107 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 108 |
+
|
| 109 |
+
base_model_tp_plan = { # TODO: only replicate attention layers when > first_k_dense_replace
|
| 110 |
+
"layers.*.self_attn.q_proj": "colwise",
|
| 111 |
+
"layers.*.self_attn.k_proj": "colwise",
|
| 112 |
+
"layers.*.self_attn.v_proj": "colwise",
|
| 113 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
| 114 |
+
"layers.*.mlp.experts.*.gate_proj": "local_colwise",
|
| 115 |
+
"layers.*.mlp.experts.*.up_proj": "local_colwise",
|
| 116 |
+
"layers.*.mlp.experts.*.down_proj": "local_rowwise",
|
| 117 |
+
"layers.*.mlp.experts.*": "local", # each expert is wrapped in a module list
|
| 118 |
+
"layers.*.mlp.shared_experts.gate_proj": "local_colwise",
|
| 119 |
+
"layers.*.mlp.shared_experts.up_proj": "local_colwise",
|
| 120 |
+
"layers.*.mlp.shared_experts.down_proj": "local_rowwise",
|
| 121 |
+
"layers.*.mlp.shared_experts": "local",
|
| 122 |
+
"layers.*.mlp.gate_proj": "local_colwise",
|
| 123 |
+
"layers.*.mlp.up_proj": "local_colwise",
|
| 124 |
+
"layers.*.mlp.down_proj": "local_rowwise",
|
| 125 |
+
"layers.*.mlp": "gather", # This is the only moment where results are gathered
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
base_model_pp_plan = {
|
| 129 |
+
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
| 130 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
| 131 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
def __init__(
|
| 135 |
+
self,
|
| 136 |
+
vocab_size=152064,
|
| 137 |
+
hidden_size=4608,
|
| 138 |
+
intermediate_size=10944,
|
| 139 |
+
moe_intermediate_size=1408,
|
| 140 |
+
num_hidden_layers=62,
|
| 141 |
+
num_attention_heads=32,
|
| 142 |
+
num_key_value_heads=32,
|
| 143 |
+
n_shared_experts=None,
|
| 144 |
+
n_routed_experts=None,
|
| 145 |
+
n_group=1,
|
| 146 |
+
topk_group=1,
|
| 147 |
+
num_experts_per_tok=None,
|
| 148 |
+
first_k_dense_replace=0,
|
| 149 |
+
norm_topk_prob=False,
|
| 150 |
+
hidden_act="silu",
|
| 151 |
+
max_position_embeddings=2048,
|
| 152 |
+
initializer_range=0.02,
|
| 153 |
+
rms_norm_eps=1e-6,
|
| 154 |
+
use_cache=True,
|
| 155 |
+
tie_word_embeddings=False,
|
| 156 |
+
rope_theta=10000.0,
|
| 157 |
+
rope_scaling=None,
|
| 158 |
+
attention_bias=False,
|
| 159 |
+
attention_dropout=0.0,
|
| 160 |
+
routed_scaling_factor=1.0,
|
| 161 |
+
sliding_window=4096,
|
| 162 |
+
max_window_layers=62,
|
| 163 |
+
layer_types=None,
|
| 164 |
+
**kwargs,
|
| 165 |
+
):
|
| 166 |
+
self.vocab_size = vocab_size
|
| 167 |
+
self.max_position_embeddings = max_position_embeddings
|
| 168 |
+
self.hidden_size = hidden_size
|
| 169 |
+
self.intermediate_size = intermediate_size
|
| 170 |
+
self.moe_intermediate_size = moe_intermediate_size
|
| 171 |
+
self.num_hidden_layers = num_hidden_layers
|
| 172 |
+
self.num_attention_heads = num_attention_heads
|
| 173 |
+
self.n_shared_experts = n_shared_experts
|
| 174 |
+
self.n_routed_experts = n_routed_experts
|
| 175 |
+
self.num_experts_per_tok = num_experts_per_tok
|
| 176 |
+
self.first_k_dense_replace = first_k_dense_replace
|
| 177 |
+
self.norm_topk_prob = norm_topk_prob
|
| 178 |
+
if num_key_value_heads is None:
|
| 179 |
+
num_key_value_heads = num_attention_heads
|
| 180 |
+
self.n_group = n_group
|
| 181 |
+
self.topk_group = topk_group
|
| 182 |
+
self.num_key_value_heads = num_key_value_heads
|
| 183 |
+
self.hidden_act = hidden_act
|
| 184 |
+
self.initializer_range = initializer_range
|
| 185 |
+
self.rms_norm_eps = rms_norm_eps
|
| 186 |
+
self.use_cache = use_cache
|
| 187 |
+
self.rope_theta = rope_theta
|
| 188 |
+
self.rope_scaling = rope_scaling
|
| 189 |
+
self.attention_bias = attention_bias
|
| 190 |
+
self.attention_dropout = attention_dropout
|
| 191 |
+
self.routed_scaling_factor = routed_scaling_factor
|
| 192 |
+
self.sliding_window = sliding_window
|
| 193 |
+
self.max_window_layers = max_window_layers
|
| 194 |
+
|
| 195 |
+
self.layer_types = layer_types
|
| 196 |
+
if self.layer_types is None:
|
| 197 |
+
self.layer_types = [
|
| 198 |
+
"sliding_attention"
|
| 199 |
+
if self.sliding_window is not None and i >= self.max_window_layers
|
| 200 |
+
else "full_attention"
|
| 201 |
+
for i in range(self.num_hidden_layers)
|
| 202 |
+
]
|
| 203 |
+
layer_type_validation(self.layer_types)
|
| 204 |
+
|
| 205 |
+
super().__init__(
|
| 206 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 207 |
+
**kwargs,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
__all__ =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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/dots1/modular_dots1.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_dots1.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 The rednote-hilab team and the HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
from typing import Callable, Optional, Union
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
import torch.nn.functional as F
|
| 25 |
+
from torch import nn
|
| 26 |
+
|
| 27 |
+
from ...activations import ACT2FN
|
| 28 |
+
from ...cache_utils import Cache, DynamicCache
|
| 29 |
+
from ...generation import GenerationMixin
|
| 30 |
+
from ...integrations import use_kernel_forward_from_hub
|
| 31 |
+
from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
|
| 32 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 33 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 34 |
+
from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 35 |
+
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 36 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 37 |
+
from ...processing_utils import Unpack
|
| 38 |
+
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
|
| 39 |
+
from ...utils.deprecation import deprecate_kwarg
|
| 40 |
+
from ...utils.generic import check_model_inputs
|
| 41 |
+
from .configuration_dots1 import Dots1Config
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
| 45 |
+
class Dots1RMSNorm(nn.Module):
|
| 46 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 47 |
+
"""
|
| 48 |
+
Dots1RMSNorm is equivalent to T5LayerNorm
|
| 49 |
+
"""
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 52 |
+
self.variance_epsilon = eps
|
| 53 |
+
|
| 54 |
+
def forward(self, hidden_states):
|
| 55 |
+
input_dtype = hidden_states.dtype
|
| 56 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 57 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 58 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 59 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 60 |
+
|
| 61 |
+
def extra_repr(self):
|
| 62 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class Dots1RotaryEmbedding(nn.Module):
|
| 66 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
| 67 |
+
|
| 68 |
+
def __init__(self, config: Dots1Config, device=None):
|
| 69 |
+
super().__init__()
|
| 70 |
+
# BC: "rope_type" was originally "type"
|
| 71 |
+
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
|
| 72 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
| 73 |
+
else:
|
| 74 |
+
self.rope_type = "default"
|
| 75 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 76 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 77 |
+
|
| 78 |
+
self.config = config
|
| 79 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 80 |
+
|
| 81 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
| 82 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 83 |
+
self.original_inv_freq = self.inv_freq
|
| 84 |
+
|
| 85 |
+
@torch.no_grad()
|
| 86 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 87 |
+
def forward(self, x, position_ids):
|
| 88 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 89 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 90 |
+
|
| 91 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 92 |
+
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
| 93 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 94 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 95 |
+
cos = emb.cos() * self.attention_scaling
|
| 96 |
+
sin = emb.sin() * self.attention_scaling
|
| 97 |
+
|
| 98 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def rotate_half(x):
|
| 102 |
+
"""Rotates half the hidden dims of the input."""
|
| 103 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 104 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 105 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 109 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 110 |
+
|
| 111 |
+
Args:
|
| 112 |
+
q (`torch.Tensor`): The query tensor.
|
| 113 |
+
k (`torch.Tensor`): The key tensor.
|
| 114 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 115 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 116 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 117 |
+
Deprecated and unused.
|
| 118 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 119 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 120 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 121 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 122 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 123 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 124 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 125 |
+
Returns:
|
| 126 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 127 |
+
"""
|
| 128 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 129 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 130 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 131 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 132 |
+
return q_embed, k_embed
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 136 |
+
"""
|
| 137 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 138 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 139 |
+
"""
|
| 140 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 141 |
+
if n_rep == 1:
|
| 142 |
+
return hidden_states
|
| 143 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 144 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def eager_attention_forward(
|
| 148 |
+
module: nn.Module,
|
| 149 |
+
query: torch.Tensor,
|
| 150 |
+
key: torch.Tensor,
|
| 151 |
+
value: torch.Tensor,
|
| 152 |
+
attention_mask: Optional[torch.Tensor],
|
| 153 |
+
scaling: float,
|
| 154 |
+
dropout: float = 0.0,
|
| 155 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 156 |
+
):
|
| 157 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 158 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 159 |
+
|
| 160 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 161 |
+
if attention_mask is not None:
|
| 162 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 163 |
+
attn_weights = attn_weights + causal_mask
|
| 164 |
+
|
| 165 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 166 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 167 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 168 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 169 |
+
|
| 170 |
+
return attn_output, attn_weights
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class Dots1Attention(nn.Module):
|
| 174 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 175 |
+
|
| 176 |
+
def __init__(self, config: Dots1Config, layer_idx: int):
|
| 177 |
+
super().__init__()
|
| 178 |
+
self.config = config
|
| 179 |
+
self.layer_idx = layer_idx
|
| 180 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 181 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 182 |
+
self.scaling = self.head_dim**-0.5
|
| 183 |
+
self.attention_dropout = config.attention_dropout
|
| 184 |
+
self.is_causal = True
|
| 185 |
+
|
| 186 |
+
self.q_proj = nn.Linear(
|
| 187 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 188 |
+
)
|
| 189 |
+
self.k_proj = nn.Linear(
|
| 190 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 191 |
+
)
|
| 192 |
+
self.v_proj = nn.Linear(
|
| 193 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 194 |
+
)
|
| 195 |
+
self.o_proj = nn.Linear(
|
| 196 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 197 |
+
)
|
| 198 |
+
self.q_norm = Dots1RMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
|
| 199 |
+
self.k_norm = Dots1RMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
|
| 200 |
+
self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
|
| 201 |
+
|
| 202 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 203 |
+
def forward(
|
| 204 |
+
self,
|
| 205 |
+
hidden_states: torch.Tensor,
|
| 206 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 207 |
+
attention_mask: Optional[torch.Tensor],
|
| 208 |
+
past_key_values: Optional[Cache] = None,
|
| 209 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 210 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 211 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 212 |
+
input_shape = hidden_states.shape[:-1]
|
| 213 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 214 |
+
|
| 215 |
+
query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 216 |
+
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 217 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 218 |
+
|
| 219 |
+
cos, sin = position_embeddings
|
| 220 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 221 |
+
|
| 222 |
+
if past_key_values is not None:
|
| 223 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 224 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 225 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 226 |
+
|
| 227 |
+
attention_interface: Callable = eager_attention_forward
|
| 228 |
+
if self.config._attn_implementation != "eager":
|
| 229 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 230 |
+
|
| 231 |
+
attn_output, attn_weights = attention_interface(
|
| 232 |
+
self,
|
| 233 |
+
query_states,
|
| 234 |
+
key_states,
|
| 235 |
+
value_states,
|
| 236 |
+
attention_mask,
|
| 237 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 238 |
+
scaling=self.scaling,
|
| 239 |
+
sliding_window=self.sliding_window, # diff with Llama
|
| 240 |
+
**kwargs,
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 244 |
+
attn_output = self.o_proj(attn_output)
|
| 245 |
+
return attn_output, attn_weights
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
class Dots1MLP(nn.Module):
|
| 249 |
+
def __init__(self, config, hidden_size=None, intermediate_size=None):
|
| 250 |
+
super().__init__()
|
| 251 |
+
self.config = config
|
| 252 |
+
self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
|
| 253 |
+
self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
|
| 254 |
+
|
| 255 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 256 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 257 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 258 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 259 |
+
|
| 260 |
+
def forward(self, x):
|
| 261 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 262 |
+
return down_proj
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
class Dots1MoE(nn.Module):
|
| 266 |
+
"""
|
| 267 |
+
A mixed expert module containing shared experts.
|
| 268 |
+
"""
|
| 269 |
+
|
| 270 |
+
def __init__(self, config):
|
| 271 |
+
super().__init__()
|
| 272 |
+
self.config = config
|
| 273 |
+
self.experts = nn.ModuleList(
|
| 274 |
+
[Dots1MLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(config.n_routed_experts)]
|
| 275 |
+
)
|
| 276 |
+
self.gate = Dots1TopkRouter(config)
|
| 277 |
+
self.shared_experts = Dots1MLP(
|
| 278 |
+
config=config, intermediate_size=config.moe_intermediate_size * config.n_shared_experts
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
def moe(self, hidden_states: torch.Tensor, topk_indices: torch.Tensor, topk_weights: torch.Tensor):
|
| 282 |
+
r"""
|
| 283 |
+
CALL FOR CONTRIBUTION! I don't have time to optimise this right now, but expert weights need to be fused
|
| 284 |
+
to not have to do a loop here (deepseek has 256 experts soooo yeah).
|
| 285 |
+
"""
|
| 286 |
+
final_hidden_states = torch.zeros_like(hidden_states, dtype=topk_weights.dtype)
|
| 287 |
+
expert_mask = torch.nn.functional.one_hot(topk_indices, num_classes=len(self.experts))
|
| 288 |
+
expert_mask = expert_mask.permute(2, 0, 1)
|
| 289 |
+
|
| 290 |
+
for expert_idx in range(len(self.experts)):
|
| 291 |
+
expert = self.experts[expert_idx]
|
| 292 |
+
mask = expert_mask[expert_idx]
|
| 293 |
+
token_indices, weight_indices = torch.where(mask)
|
| 294 |
+
|
| 295 |
+
if token_indices.numel() > 0:
|
| 296 |
+
expert_weights = topk_weights[token_indices, weight_indices]
|
| 297 |
+
expert_input = hidden_states[token_indices]
|
| 298 |
+
expert_output = expert(expert_input)
|
| 299 |
+
weighted_output = expert_output * expert_weights.unsqueeze(-1)
|
| 300 |
+
final_hidden_states.index_add_(0, token_indices, weighted_output)
|
| 301 |
+
|
| 302 |
+
# in original deepseek, the output of the experts are gathered once we leave this module
|
| 303 |
+
# thus the moe module is itelsf an IsolatedParallel module
|
| 304 |
+
# and all expert are "local" meaning we shard but we don't gather
|
| 305 |
+
return final_hidden_states.type(hidden_states.dtype)
|
| 306 |
+
|
| 307 |
+
def forward(self, hidden_states):
|
| 308 |
+
residuals = hidden_states
|
| 309 |
+
orig_shape = hidden_states.shape
|
| 310 |
+
topk_indices, topk_weights = self.gate(hidden_states)
|
| 311 |
+
hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
|
| 312 |
+
hidden_states = self.moe(hidden_states, topk_indices, topk_weights).view(*orig_shape)
|
| 313 |
+
hidden_states = hidden_states + self.shared_experts(residuals)
|
| 314 |
+
return hidden_states
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
class Dots1TopkRouter(nn.Module):
|
| 318 |
+
def __init__(self, config):
|
| 319 |
+
super().__init__()
|
| 320 |
+
self.config = config
|
| 321 |
+
self.top_k = config.num_experts_per_tok
|
| 322 |
+
self.n_routed_experts = config.n_routed_experts
|
| 323 |
+
self.routed_scaling_factor = config.routed_scaling_factor
|
| 324 |
+
self.n_group = config.n_group
|
| 325 |
+
self.topk_group = config.topk_group
|
| 326 |
+
self.norm_topk_prob = config.norm_topk_prob
|
| 327 |
+
|
| 328 |
+
self.weight = nn.Parameter(torch.empty((self.n_routed_experts, config.hidden_size)))
|
| 329 |
+
self.register_buffer("e_score_correction_bias", torch.zeros(self.n_routed_experts))
|
| 330 |
+
|
| 331 |
+
@torch.no_grad()
|
| 332 |
+
def get_topk_indices(self, scores):
|
| 333 |
+
scores_for_choice = scores.view(-1, self.n_routed_experts) + self.e_score_correction_bias.unsqueeze(0)
|
| 334 |
+
group_scores = (
|
| 335 |
+
scores_for_choice.view(-1, self.n_group, self.n_routed_experts // self.n_group)
|
| 336 |
+
.topk(2, dim=-1)[0]
|
| 337 |
+
.sum(dim=-1)
|
| 338 |
+
)
|
| 339 |
+
group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
|
| 340 |
+
group_mask = torch.zeros_like(group_scores)
|
| 341 |
+
group_mask.scatter_(1, group_idx, 1)
|
| 342 |
+
score_mask = (
|
| 343 |
+
group_mask.unsqueeze(-1)
|
| 344 |
+
.expand(-1, self.n_group, self.n_routed_experts // self.n_group)
|
| 345 |
+
.reshape(-1, self.n_routed_experts)
|
| 346 |
+
)
|
| 347 |
+
scores_for_choice = scores_for_choice.masked_fill(~score_mask.bool(), 0.0)
|
| 348 |
+
topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
|
| 349 |
+
return topk_indices
|
| 350 |
+
|
| 351 |
+
def forward(self, hidden_states):
|
| 352 |
+
hidden_states = hidden_states.view(-1, self.config.hidden_size)
|
| 353 |
+
router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
|
| 354 |
+
scores = router_logits.sigmoid()
|
| 355 |
+
topk_indices = self.get_topk_indices(scores)
|
| 356 |
+
topk_weights = scores.gather(1, topk_indices)
|
| 357 |
+
if self.norm_topk_prob:
|
| 358 |
+
denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20
|
| 359 |
+
topk_weights /= denominator
|
| 360 |
+
topk_weights = topk_weights * self.routed_scaling_factor
|
| 361 |
+
return topk_indices, topk_weights
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
class Dots1DecoderLayer(GradientCheckpointingLayer):
|
| 365 |
+
def __init__(self, config: Dots1Config, layer_idx: int):
|
| 366 |
+
super().__init__()
|
| 367 |
+
self.hidden_size = config.hidden_size
|
| 368 |
+
|
| 369 |
+
self.self_attn = Dots1Attention(config=config, layer_idx=layer_idx)
|
| 370 |
+
|
| 371 |
+
if layer_idx >= config.first_k_dense_replace:
|
| 372 |
+
self.mlp = Dots1MoE(config)
|
| 373 |
+
else:
|
| 374 |
+
self.mlp = Dots1MLP(config)
|
| 375 |
+
|
| 376 |
+
self.input_layernorm = Dots1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 377 |
+
self.post_attention_layernorm = Dots1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 378 |
+
self.attention_type = config.layer_types[layer_idx]
|
| 379 |
+
|
| 380 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 381 |
+
def forward(
|
| 382 |
+
self,
|
| 383 |
+
hidden_states: torch.Tensor,
|
| 384 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 385 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 386 |
+
past_key_values: Optional[Cache] = None,
|
| 387 |
+
use_cache: Optional[bool] = False,
|
| 388 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 389 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
| 390 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 391 |
+
) -> torch.Tensor:
|
| 392 |
+
residual = hidden_states
|
| 393 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 394 |
+
# Self Attention
|
| 395 |
+
hidden_states, _ = self.self_attn(
|
| 396 |
+
hidden_states=hidden_states,
|
| 397 |
+
attention_mask=attention_mask,
|
| 398 |
+
position_ids=position_ids,
|
| 399 |
+
past_key_values=past_key_values,
|
| 400 |
+
use_cache=use_cache,
|
| 401 |
+
cache_position=cache_position,
|
| 402 |
+
position_embeddings=position_embeddings,
|
| 403 |
+
**kwargs,
|
| 404 |
+
)
|
| 405 |
+
hidden_states = residual + hidden_states
|
| 406 |
+
|
| 407 |
+
# Fully Connected
|
| 408 |
+
residual = hidden_states
|
| 409 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 410 |
+
hidden_states = self.mlp(hidden_states)
|
| 411 |
+
hidden_states = residual + hidden_states
|
| 412 |
+
return hidden_states
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
@auto_docstring
|
| 416 |
+
class Dots1PreTrainedModel(PreTrainedModel):
|
| 417 |
+
config: Dots1Config
|
| 418 |
+
base_model_prefix = "model"
|
| 419 |
+
supports_gradient_checkpointing = True
|
| 420 |
+
_no_split_modules = ["Dots1DecoderLayer"]
|
| 421 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 422 |
+
_supports_flash_attn = True
|
| 423 |
+
_supports_sdpa = True
|
| 424 |
+
_supports_flex_attn = True
|
| 425 |
+
_can_compile_fullgraph = False
|
| 426 |
+
_supports_attention_backend = True
|
| 427 |
+
_can_record_outputs = {
|
| 428 |
+
"hidden_states": Dots1DecoderLayer,
|
| 429 |
+
"attentions": Dots1Attention,
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
def _init_weights(self, module):
|
| 433 |
+
super()._init_weights(module)
|
| 434 |
+
if isinstance(module, Dots1TopkRouter):
|
| 435 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
@auto_docstring
|
| 439 |
+
class Dots1Model(Dots1PreTrainedModel):
|
| 440 |
+
def __init__(self, config: Dots1Config):
|
| 441 |
+
super().__init__(config)
|
| 442 |
+
self.padding_idx = config.pad_token_id
|
| 443 |
+
self.vocab_size = config.vocab_size
|
| 444 |
+
|
| 445 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 446 |
+
self.layers = nn.ModuleList(
|
| 447 |
+
[Dots1DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 448 |
+
)
|
| 449 |
+
self.norm = Dots1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 450 |
+
self.rotary_emb = Dots1RotaryEmbedding(config=config)
|
| 451 |
+
self.gradient_checkpointing = False
|
| 452 |
+
self.has_sliding_layers = "sliding_attention" in self.config.layer_types
|
| 453 |
+
|
| 454 |
+
# Initialize weights and apply final processing
|
| 455 |
+
self.post_init()
|
| 456 |
+
|
| 457 |
+
@check_model_inputs
|
| 458 |
+
@auto_docstring
|
| 459 |
+
def forward(
|
| 460 |
+
self,
|
| 461 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 462 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 463 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 464 |
+
past_key_values: Optional[Cache] = None,
|
| 465 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 466 |
+
use_cache: Optional[bool] = None,
|
| 467 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 468 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 469 |
+
) -> BaseModelOutputWithPast:
|
| 470 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 471 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 472 |
+
|
| 473 |
+
if inputs_embeds is None:
|
| 474 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 475 |
+
|
| 476 |
+
if use_cache and past_key_values is None:
|
| 477 |
+
past_key_values = DynamicCache(config=self.config)
|
| 478 |
+
|
| 479 |
+
if cache_position is None:
|
| 480 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 481 |
+
cache_position = torch.arange(
|
| 482 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
if position_ids is None:
|
| 486 |
+
position_ids = cache_position.unsqueeze(0)
|
| 487 |
+
|
| 488 |
+
# It may already have been prepared by e.g. `generate`
|
| 489 |
+
if not isinstance(causal_mask_mapping := attention_mask, dict):
|
| 490 |
+
# Prepare mask arguments
|
| 491 |
+
mask_kwargs = {
|
| 492 |
+
"config": self.config,
|
| 493 |
+
"input_embeds": inputs_embeds,
|
| 494 |
+
"attention_mask": attention_mask,
|
| 495 |
+
"cache_position": cache_position,
|
| 496 |
+
"past_key_values": past_key_values,
|
| 497 |
+
"position_ids": position_ids,
|
| 498 |
+
}
|
| 499 |
+
# Create the masks
|
| 500 |
+
causal_mask_mapping = {
|
| 501 |
+
"full_attention": create_causal_mask(**mask_kwargs),
|
| 502 |
+
}
|
| 503 |
+
# The sliding window alternating layers are not always activated depending on the config
|
| 504 |
+
if self.has_sliding_layers:
|
| 505 |
+
causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
|
| 506 |
+
|
| 507 |
+
hidden_states = inputs_embeds
|
| 508 |
+
|
| 509 |
+
# create position embeddings to be shared across the decoder layers
|
| 510 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 511 |
+
|
| 512 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
| 513 |
+
hidden_states = decoder_layer(
|
| 514 |
+
hidden_states,
|
| 515 |
+
attention_mask=causal_mask_mapping[decoder_layer.attention_type],
|
| 516 |
+
position_ids=position_ids,
|
| 517 |
+
past_key_values=past_key_values,
|
| 518 |
+
use_cache=use_cache,
|
| 519 |
+
cache_position=cache_position,
|
| 520 |
+
position_embeddings=position_embeddings,
|
| 521 |
+
**kwargs,
|
| 522 |
+
)
|
| 523 |
+
|
| 524 |
+
hidden_states = self.norm(hidden_states)
|
| 525 |
+
return BaseModelOutputWithPast(
|
| 526 |
+
last_hidden_state=hidden_states,
|
| 527 |
+
past_key_values=past_key_values if use_cache else None,
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
@auto_docstring
|
| 532 |
+
class Dots1ForCausalLM(Dots1PreTrainedModel, GenerationMixin):
|
| 533 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 534 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
| 535 |
+
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
| 536 |
+
|
| 537 |
+
def __init__(self, config):
|
| 538 |
+
super().__init__(config)
|
| 539 |
+
self.model = Dots1Model(config)
|
| 540 |
+
self.vocab_size = config.vocab_size
|
| 541 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 542 |
+
|
| 543 |
+
# Initialize weights and apply final processing
|
| 544 |
+
self.post_init()
|
| 545 |
+
|
| 546 |
+
def set_decoder(self, decoder):
|
| 547 |
+
self.model = decoder
|
| 548 |
+
|
| 549 |
+
def get_decoder(self):
|
| 550 |
+
return self.model
|
| 551 |
+
|
| 552 |
+
@can_return_tuple
|
| 553 |
+
@auto_docstring
|
| 554 |
+
def forward(
|
| 555 |
+
self,
|
| 556 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 557 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 558 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 559 |
+
past_key_values: Optional[Cache] = None,
|
| 560 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 561 |
+
labels: Optional[torch.LongTensor] = None,
|
| 562 |
+
use_cache: Optional[bool] = None,
|
| 563 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 564 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 565 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 566 |
+
) -> CausalLMOutputWithPast:
|
| 567 |
+
r"""
|
| 568 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 569 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 570 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 571 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 572 |
+
|
| 573 |
+
Example:
|
| 574 |
+
|
| 575 |
+
```python
|
| 576 |
+
>>> from transformers import AutoTokenizer, Dots1ForCausalLM
|
| 577 |
+
|
| 578 |
+
>>> model = Dots1ForCausalLM.from_pretrained("rednote-hilab/dots1.llm1.inst")
|
| 579 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("rednote-hilab/dots1.llm1.inst")
|
| 580 |
+
|
| 581 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 582 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 583 |
+
|
| 584 |
+
>>> # Generate
|
| 585 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 586 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 587 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 588 |
+
```"""
|
| 589 |
+
outputs: BaseModelOutputWithPast = self.model(
|
| 590 |
+
input_ids=input_ids,
|
| 591 |
+
attention_mask=attention_mask,
|
| 592 |
+
position_ids=position_ids,
|
| 593 |
+
past_key_values=past_key_values,
|
| 594 |
+
inputs_embeds=inputs_embeds,
|
| 595 |
+
use_cache=use_cache,
|
| 596 |
+
cache_position=cache_position,
|
| 597 |
+
**kwargs,
|
| 598 |
+
)
|
| 599 |
+
|
| 600 |
+
hidden_states = outputs.last_hidden_state
|
| 601 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 602 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 603 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 604 |
+
|
| 605 |
+
loss = None
|
| 606 |
+
if labels is not None:
|
| 607 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 608 |
+
|
| 609 |
+
return CausalLMOutputWithPast(
|
| 610 |
+
loss=loss,
|
| 611 |
+
logits=logits,
|
| 612 |
+
past_key_values=outputs.past_key_values,
|
| 613 |
+
hidden_states=outputs.hidden_states,
|
| 614 |
+
attentions=outputs.attentions,
|
| 615 |
+
)
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
__all__ = ["Dots1PreTrainedModel", "Dots1Model", "Dots1ForCausalLM"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dots1/modular_dots1.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The rednote-hilab team and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
from ...modeling_outputs import CausalLMOutputWithPast
|
| 16 |
+
from ...processing_utils import Unpack
|
| 17 |
+
from ...utils import logging
|
| 18 |
+
from ..deepseek_v3.modeling_deepseek_v3 import (
|
| 19 |
+
DeepseekV3DecoderLayer,
|
| 20 |
+
DeepseekV3MLP,
|
| 21 |
+
DeepseekV3MoE,
|
| 22 |
+
DeepseekV3PreTrainedModel,
|
| 23 |
+
DeepseekV3TopkRouter,
|
| 24 |
+
)
|
| 25 |
+
from ..qwen3.modeling_qwen3 import (
|
| 26 |
+
Qwen3Attention,
|
| 27 |
+
Qwen3ForCausalLM,
|
| 28 |
+
Qwen3Model,
|
| 29 |
+
Qwen3RMSNorm,
|
| 30 |
+
Qwen3RotaryEmbedding,
|
| 31 |
+
TransformersKwargs,
|
| 32 |
+
)
|
| 33 |
+
from .configuration_dots1 import Dots1Config
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
logger = logging.get_logger(__name__)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class Dots1RMSNorm(Qwen3RMSNorm):
|
| 40 |
+
pass
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class Dots1RotaryEmbedding(Qwen3RotaryEmbedding):
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class Dots1Attention(Qwen3Attention):
|
| 48 |
+
pass
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class Dots1MLP(DeepseekV3MLP):
|
| 52 |
+
pass
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class Dots1MoE(DeepseekV3MoE):
|
| 56 |
+
pass
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class Dots1TopkRouter(DeepseekV3TopkRouter):
|
| 60 |
+
pass
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class Dots1DecoderLayer(DeepseekV3DecoderLayer):
|
| 64 |
+
def __init__(self, config: Dots1Config, layer_idx: int):
|
| 65 |
+
super().__init__()
|
| 66 |
+
self.attention_type = config.layer_types[layer_idx]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class Dots1PreTrainedModel(DeepseekV3PreTrainedModel):
|
| 70 |
+
pass
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class Dots1Model(Qwen3Model):
|
| 74 |
+
pass
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class Dots1ForCausalLM(Qwen3ForCausalLM):
|
| 78 |
+
def forward(
|
| 79 |
+
self,
|
| 80 |
+
**super_kwargs: Unpack[TransformersKwargs],
|
| 81 |
+
) -> CausalLMOutputWithPast:
|
| 82 |
+
r"""
|
| 83 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 84 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 85 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 86 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 87 |
+
|
| 88 |
+
Example:
|
| 89 |
+
|
| 90 |
+
```python
|
| 91 |
+
>>> from transformers import AutoTokenizer, Dots1ForCausalLM
|
| 92 |
+
|
| 93 |
+
>>> model = Dots1ForCausalLM.from_pretrained("rednote-hilab/dots1.llm1.inst")
|
| 94 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("rednote-hilab/dots1.llm1.inst")
|
| 95 |
+
|
| 96 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 97 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 98 |
+
|
| 99 |
+
>>> # Generate
|
| 100 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 101 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 102 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 103 |
+
```"""
|
| 104 |
+
return super().forward(**super_kwargs)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
__all__ = [
|
| 108 |
+
"Dots1PreTrainedModel",
|
| 109 |
+
"Dots1Model",
|
| 110 |
+
"Dots1ForCausalLM",
|
| 111 |
+
]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dpr/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_dpr import *
|
| 22 |
+
from .modeling_dpr import *
|
| 23 |
+
from .modeling_tf_dpr import *
|
| 24 |
+
from .tokenization_dpr import *
|
| 25 |
+
from .tokenization_dpr_fast import *
|
| 26 |
+
else:
|
| 27 |
+
import sys
|
| 28 |
+
|
| 29 |
+
_file = globals()["__file__"]
|
| 30 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dpr/configuration_dpr.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2010, DPR authors, The Hugging Face 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 |
+
"""DPR model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class DPRConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
[`DPRConfig`] is the configuration class to store the configuration of a *DPRModel*.
|
| 27 |
+
|
| 28 |
+
This is the configuration class to store the configuration of a [`DPRContextEncoder`], [`DPRQuestionEncoder`], or a
|
| 29 |
+
[`DPRReader`]. It is used to instantiate the components of the DPR model according to the specified arguments,
|
| 30 |
+
defining the model component architectures. Instantiating a configuration with the defaults will yield a similar
|
| 31 |
+
configuration to that of the DPRContextEncoder
|
| 32 |
+
[facebook/dpr-ctx_encoder-single-nq-base](https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base)
|
| 33 |
+
architecture.
|
| 34 |
+
|
| 35 |
+
This class is a subclass of [`BertConfig`]. Please check the superclass for the documentation of all kwargs.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
| 39 |
+
Vocabulary size of the DPR model. Defines the different tokens that can be represented by the *inputs_ids*
|
| 40 |
+
passed to the forward method of [`BertModel`].
|
| 41 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 42 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 43 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 44 |
+
Number of hidden layers in the Transformer encoder.
|
| 45 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 46 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 47 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 48 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 49 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 50 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 51 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 52 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 53 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 54 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 55 |
+
The dropout ratio for the attention probabilities.
|
| 56 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 57 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 58 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 59 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
| 60 |
+
The vocabulary size of the *token_type_ids* passed into [`BertModel`].
|
| 61 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 62 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 63 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 64 |
+
The epsilon used by the layer normalization layers.
|
| 65 |
+
pad_token_id (`int`, *optional*, defaults to 0):
|
| 66 |
+
Padding token id.
|
| 67 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 68 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 69 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 70 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).
|
| 71 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 72 |
+
with Better Relative Position Embeddings (Huang et al.)](https://huggingface.co/papers/2009.13658).
|
| 73 |
+
projection_dim (`int`, *optional*, defaults to 0):
|
| 74 |
+
Dimension of the projection for the context and question encoders. If it is set to zero (default), then no
|
| 75 |
+
projection is done.
|
| 76 |
+
|
| 77 |
+
Example:
|
| 78 |
+
|
| 79 |
+
```python
|
| 80 |
+
>>> from transformers import DPRConfig, DPRContextEncoder
|
| 81 |
+
|
| 82 |
+
>>> # Initializing a DPR facebook/dpr-ctx_encoder-single-nq-base style configuration
|
| 83 |
+
>>> configuration = DPRConfig()
|
| 84 |
+
|
| 85 |
+
>>> # Initializing a model (with random weights) from the facebook/dpr-ctx_encoder-single-nq-base style configuration
|
| 86 |
+
>>> model = DPRContextEncoder(configuration)
|
| 87 |
+
|
| 88 |
+
>>> # Accessing the model configuration
|
| 89 |
+
>>> configuration = model.config
|
| 90 |
+
```"""
|
| 91 |
+
|
| 92 |
+
model_type = "dpr"
|
| 93 |
+
|
| 94 |
+
def __init__(
|
| 95 |
+
self,
|
| 96 |
+
vocab_size=30522,
|
| 97 |
+
hidden_size=768,
|
| 98 |
+
num_hidden_layers=12,
|
| 99 |
+
num_attention_heads=12,
|
| 100 |
+
intermediate_size=3072,
|
| 101 |
+
hidden_act="gelu",
|
| 102 |
+
hidden_dropout_prob=0.1,
|
| 103 |
+
attention_probs_dropout_prob=0.1,
|
| 104 |
+
max_position_embeddings=512,
|
| 105 |
+
type_vocab_size=2,
|
| 106 |
+
initializer_range=0.02,
|
| 107 |
+
layer_norm_eps=1e-12,
|
| 108 |
+
pad_token_id=0,
|
| 109 |
+
position_embedding_type="absolute",
|
| 110 |
+
projection_dim: int = 0,
|
| 111 |
+
**kwargs,
|
| 112 |
+
):
|
| 113 |
+
super().__init__(pad_token_id=pad_token_id, **kwargs)
|
| 114 |
+
|
| 115 |
+
self.vocab_size = vocab_size
|
| 116 |
+
self.hidden_size = hidden_size
|
| 117 |
+
self.num_hidden_layers = num_hidden_layers
|
| 118 |
+
self.num_attention_heads = num_attention_heads
|
| 119 |
+
self.hidden_act = hidden_act
|
| 120 |
+
self.intermediate_size = intermediate_size
|
| 121 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 122 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 123 |
+
self.max_position_embeddings = max_position_embeddings
|
| 124 |
+
self.type_vocab_size = type_vocab_size
|
| 125 |
+
self.initializer_range = initializer_range
|
| 126 |
+
self.layer_norm_eps = layer_norm_eps
|
| 127 |
+
self.projection_dim = projection_dim
|
| 128 |
+
self.position_embedding_type = position_embedding_type
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
__all__ = ["DPRConfig"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dpr/convert_dpr_original_checkpoint_to_pytorch.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import collections
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from torch.serialization import default_restore_location
|
| 21 |
+
|
| 22 |
+
from transformers import BertConfig, DPRConfig, DPRContextEncoder, DPRQuestionEncoder, DPRReader
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
CheckpointState = collections.namedtuple(
|
| 26 |
+
"CheckpointState", ["model_dict", "optimizer_dict", "scheduler_dict", "offset", "epoch", "encoder_params"]
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def load_states_from_checkpoint(model_file: str) -> CheckpointState:
|
| 31 |
+
print(f"Reading saved model from {model_file}")
|
| 32 |
+
state_dict = torch.load(
|
| 33 |
+
model_file, map_location=lambda s, l: default_restore_location(s, "cpu"), weights_only=True
|
| 34 |
+
)
|
| 35 |
+
return CheckpointState(**state_dict)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class DPRState:
|
| 39 |
+
def __init__(self, src_file: Path):
|
| 40 |
+
self.src_file = src_file
|
| 41 |
+
|
| 42 |
+
def load_dpr_model(self):
|
| 43 |
+
raise NotImplementedError
|
| 44 |
+
|
| 45 |
+
@staticmethod
|
| 46 |
+
def from_type(comp_type: str, *args, **kwargs) -> "DPRState":
|
| 47 |
+
if comp_type.startswith("c"):
|
| 48 |
+
return DPRContextEncoderState(*args, **kwargs)
|
| 49 |
+
if comp_type.startswith("q"):
|
| 50 |
+
return DPRQuestionEncoderState(*args, **kwargs)
|
| 51 |
+
if comp_type.startswith("r"):
|
| 52 |
+
return DPRReaderState(*args, **kwargs)
|
| 53 |
+
else:
|
| 54 |
+
raise ValueError("Component type must be either 'ctx_encoder', 'question_encoder' or 'reader'.")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class DPRContextEncoderState(DPRState):
|
| 58 |
+
def load_dpr_model(self):
|
| 59 |
+
model = DPRContextEncoder(DPRConfig(**BertConfig.get_config_dict("google-bert/bert-base-uncased")[0]))
|
| 60 |
+
print(f"Loading DPR biencoder from {self.src_file}")
|
| 61 |
+
saved_state = load_states_from_checkpoint(self.src_file)
|
| 62 |
+
encoder, prefix = model.ctx_encoder, "ctx_model."
|
| 63 |
+
# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
|
| 64 |
+
state_dict = {"bert_model.embeddings.position_ids": model.ctx_encoder.bert_model.embeddings.position_ids}
|
| 65 |
+
for key, value in saved_state.model_dict.items():
|
| 66 |
+
if key.startswith(prefix):
|
| 67 |
+
key = key[len(prefix) :]
|
| 68 |
+
if not key.startswith("encode_proj."):
|
| 69 |
+
key = "bert_model." + key
|
| 70 |
+
state_dict[key] = value
|
| 71 |
+
encoder.load_state_dict(state_dict)
|
| 72 |
+
return model
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class DPRQuestionEncoderState(DPRState):
|
| 76 |
+
def load_dpr_model(self):
|
| 77 |
+
model = DPRQuestionEncoder(DPRConfig(**BertConfig.get_config_dict("google-bert/bert-base-uncased")[0]))
|
| 78 |
+
print(f"Loading DPR biencoder from {self.src_file}")
|
| 79 |
+
saved_state = load_states_from_checkpoint(self.src_file)
|
| 80 |
+
encoder, prefix = model.question_encoder, "question_model."
|
| 81 |
+
# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
|
| 82 |
+
state_dict = {"bert_model.embeddings.position_ids": model.question_encoder.bert_model.embeddings.position_ids}
|
| 83 |
+
for key, value in saved_state.model_dict.items():
|
| 84 |
+
if key.startswith(prefix):
|
| 85 |
+
key = key[len(prefix) :]
|
| 86 |
+
if not key.startswith("encode_proj."):
|
| 87 |
+
key = "bert_model." + key
|
| 88 |
+
state_dict[key] = value
|
| 89 |
+
encoder.load_state_dict(state_dict)
|
| 90 |
+
return model
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class DPRReaderState(DPRState):
|
| 94 |
+
def load_dpr_model(self):
|
| 95 |
+
model = DPRReader(DPRConfig(**BertConfig.get_config_dict("google-bert/bert-base-uncased")[0]))
|
| 96 |
+
print(f"Loading DPR reader from {self.src_file}")
|
| 97 |
+
saved_state = load_states_from_checkpoint(self.src_file)
|
| 98 |
+
# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
|
| 99 |
+
state_dict = {
|
| 100 |
+
"encoder.bert_model.embeddings.position_ids": model.span_predictor.encoder.bert_model.embeddings.position_ids
|
| 101 |
+
}
|
| 102 |
+
for key, value in saved_state.model_dict.items():
|
| 103 |
+
if key.startswith("encoder.") and not key.startswith("encoder.encode_proj"):
|
| 104 |
+
key = "encoder.bert_model." + key[len("encoder.") :]
|
| 105 |
+
state_dict[key] = value
|
| 106 |
+
model.span_predictor.load_state_dict(state_dict)
|
| 107 |
+
return model
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def convert(comp_type: str, src_file: Path, dest_dir: Path):
|
| 111 |
+
dest_dir = Path(dest_dir)
|
| 112 |
+
dest_dir.mkdir(exist_ok=True)
|
| 113 |
+
|
| 114 |
+
dpr_state = DPRState.from_type(comp_type, src_file=src_file)
|
| 115 |
+
model = dpr_state.load_dpr_model()
|
| 116 |
+
model.save_pretrained(dest_dir)
|
| 117 |
+
model.from_pretrained(dest_dir) # sanity check
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
if __name__ == "__main__":
|
| 121 |
+
parser = argparse.ArgumentParser()
|
| 122 |
+
# Required parameters
|
| 123 |
+
parser.add_argument(
|
| 124 |
+
"--type", type=str, help="Type of the component to convert: 'ctx_encoder', 'question_encoder' or 'reader'."
|
| 125 |
+
)
|
| 126 |
+
parser.add_argument(
|
| 127 |
+
"--src",
|
| 128 |
+
type=str,
|
| 129 |
+
help=(
|
| 130 |
+
"Path to the dpr checkpoint file. They can be downloaded from the official DPR repo"
|
| 131 |
+
" https://github.com/facebookresearch/DPR. Note that in the official repo, both encoders are stored in the"
|
| 132 |
+
" 'retriever' checkpoints."
|
| 133 |
+
),
|
| 134 |
+
)
|
| 135 |
+
parser.add_argument("--dest", type=str, default=None, help="Path to the output PyTorch model directory.")
|
| 136 |
+
args = parser.parse_args()
|
| 137 |
+
|
| 138 |
+
src_file = Path(args.src)
|
| 139 |
+
dest_dir = f"converted-{src_file.name}" if args.dest is None else args.dest
|
| 140 |
+
dest_dir = Path(dest_dir)
|
| 141 |
+
assert src_file.exists()
|
| 142 |
+
assert args.type is not None, (
|
| 143 |
+
"Please specify the component type of the DPR model to convert: 'ctx_encoder', 'question_encoder' or 'reader'."
|
| 144 |
+
)
|
| 145 |
+
convert(args.type, src_file, dest_dir)
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dpr/modeling_dpr.py
ADDED
|
@@ -0,0 +1,592 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 DPR Authors, The Hugging Face Team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch DPR model for Open Domain Question Answering."""
|
| 16 |
+
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from typing import Optional, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import Tensor, nn
|
| 22 |
+
|
| 23 |
+
from ...modeling_outputs import BaseModelOutputWithPooling
|
| 24 |
+
from ...modeling_utils import PreTrainedModel
|
| 25 |
+
from ...utils import (
|
| 26 |
+
ModelOutput,
|
| 27 |
+
auto_docstring,
|
| 28 |
+
logging,
|
| 29 |
+
)
|
| 30 |
+
from ..bert.modeling_bert import BertModel
|
| 31 |
+
from .configuration_dpr import DPRConfig
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
logger = logging.get_logger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
##########
|
| 38 |
+
# Outputs
|
| 39 |
+
##########
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass
|
| 43 |
+
@auto_docstring(
|
| 44 |
+
custom_intro="""
|
| 45 |
+
Class for outputs of [`DPRQuestionEncoder`].
|
| 46 |
+
"""
|
| 47 |
+
)
|
| 48 |
+
class DPRContextEncoderOutput(ModelOutput):
|
| 49 |
+
r"""
|
| 50 |
+
pooler_output (`torch.FloatTensor` of shape `(batch_size, embeddings_size)`):
|
| 51 |
+
The DPR encoder outputs the *pooler_output* that corresponds to the context representation. Last layer
|
| 52 |
+
hidden-state of the first token of the sequence (classification token) further processed by a Linear layer.
|
| 53 |
+
This output is to be used to embed contexts for nearest neighbors queries with questions embeddings.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
pooler_output: torch.FloatTensor
|
| 57 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 58 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@dataclass
|
| 62 |
+
@auto_docstring(
|
| 63 |
+
custom_intro="""
|
| 64 |
+
Class for outputs of [`DPRQuestionEncoder`].
|
| 65 |
+
"""
|
| 66 |
+
)
|
| 67 |
+
class DPRQuestionEncoderOutput(ModelOutput):
|
| 68 |
+
r"""
|
| 69 |
+
pooler_output (`torch.FloatTensor` of shape `(batch_size, embeddings_size)`):
|
| 70 |
+
The DPR encoder outputs the *pooler_output* that corresponds to the question representation. Last layer
|
| 71 |
+
hidden-state of the first token of the sequence (classification token) further processed by a Linear layer.
|
| 72 |
+
This output is to be used to embed questions for nearest neighbors queries with context embeddings.
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
pooler_output: torch.FloatTensor
|
| 76 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 77 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@dataclass
|
| 81 |
+
@auto_docstring(
|
| 82 |
+
custom_intro="""
|
| 83 |
+
Class for outputs of [`DPRQuestionEncoder`].
|
| 84 |
+
"""
|
| 85 |
+
)
|
| 86 |
+
class DPRReaderOutput(ModelOutput):
|
| 87 |
+
r"""
|
| 88 |
+
start_logits (`torch.FloatTensor` of shape `(n_passages, sequence_length)`):
|
| 89 |
+
Logits of the start index of the span for each passage.
|
| 90 |
+
end_logits (`torch.FloatTensor` of shape `(n_passages, sequence_length)`):
|
| 91 |
+
Logits of the end index of the span for each passage.
|
| 92 |
+
relevance_logits (`torch.FloatTensor` of shape `(n_passages, )`):
|
| 93 |
+
Outputs of the QA classifier of the DPRReader that corresponds to the scores of each passage to answer the
|
| 94 |
+
question, compared to all the other passages.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
start_logits: torch.FloatTensor
|
| 98 |
+
end_logits: Optional[torch.FloatTensor] = None
|
| 99 |
+
relevance_logits: Optional[torch.FloatTensor] = None
|
| 100 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 101 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@auto_docstring
|
| 105 |
+
class DPRPreTrainedModel(PreTrainedModel):
|
| 106 |
+
_supports_sdpa = True
|
| 107 |
+
|
| 108 |
+
def _init_weights(self, module):
|
| 109 |
+
"""Initialize the weights"""
|
| 110 |
+
if isinstance(module, nn.Linear):
|
| 111 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 112 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 113 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 114 |
+
if module.bias is not None:
|
| 115 |
+
module.bias.data.zero_()
|
| 116 |
+
elif isinstance(module, nn.Embedding):
|
| 117 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 118 |
+
if module.padding_idx is not None:
|
| 119 |
+
module.weight.data[module.padding_idx].zero_()
|
| 120 |
+
elif isinstance(module, nn.LayerNorm):
|
| 121 |
+
module.bias.data.zero_()
|
| 122 |
+
module.weight.data.fill_(1.0)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class DPREncoder(DPRPreTrainedModel):
|
| 126 |
+
base_model_prefix = "bert_model"
|
| 127 |
+
|
| 128 |
+
def __init__(self, config: DPRConfig):
|
| 129 |
+
super().__init__(config)
|
| 130 |
+
self.bert_model = BertModel(config, add_pooling_layer=False)
|
| 131 |
+
if self.bert_model.config.hidden_size <= 0:
|
| 132 |
+
raise ValueError("Encoder hidden_size can't be zero")
|
| 133 |
+
self.projection_dim = config.projection_dim
|
| 134 |
+
if self.projection_dim > 0:
|
| 135 |
+
self.encode_proj = nn.Linear(self.bert_model.config.hidden_size, config.projection_dim)
|
| 136 |
+
# Initialize weights and apply final processing
|
| 137 |
+
self.post_init()
|
| 138 |
+
|
| 139 |
+
def forward(
|
| 140 |
+
self,
|
| 141 |
+
input_ids: Tensor,
|
| 142 |
+
attention_mask: Optional[Tensor] = None,
|
| 143 |
+
token_type_ids: Optional[Tensor] = None,
|
| 144 |
+
inputs_embeds: Optional[Tensor] = None,
|
| 145 |
+
output_attentions: bool = False,
|
| 146 |
+
output_hidden_states: bool = False,
|
| 147 |
+
return_dict: bool = False,
|
| 148 |
+
) -> Union[BaseModelOutputWithPooling, tuple[Tensor, ...]]:
|
| 149 |
+
outputs = self.bert_model(
|
| 150 |
+
input_ids=input_ids,
|
| 151 |
+
attention_mask=attention_mask,
|
| 152 |
+
token_type_ids=token_type_ids,
|
| 153 |
+
inputs_embeds=inputs_embeds,
|
| 154 |
+
output_attentions=output_attentions,
|
| 155 |
+
output_hidden_states=output_hidden_states,
|
| 156 |
+
return_dict=return_dict,
|
| 157 |
+
)
|
| 158 |
+
sequence_output = outputs[0]
|
| 159 |
+
pooled_output = sequence_output[:, 0, :]
|
| 160 |
+
|
| 161 |
+
if self.projection_dim > 0:
|
| 162 |
+
pooled_output = self.encode_proj(pooled_output)
|
| 163 |
+
|
| 164 |
+
if not return_dict:
|
| 165 |
+
return (sequence_output, pooled_output) + outputs[2:]
|
| 166 |
+
|
| 167 |
+
return BaseModelOutputWithPooling(
|
| 168 |
+
last_hidden_state=sequence_output,
|
| 169 |
+
pooler_output=pooled_output,
|
| 170 |
+
hidden_states=outputs.hidden_states,
|
| 171 |
+
attentions=outputs.attentions,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
@property
|
| 175 |
+
def embeddings_size(self) -> int:
|
| 176 |
+
if self.projection_dim > 0:
|
| 177 |
+
return self.encode_proj.out_features
|
| 178 |
+
return self.bert_model.config.hidden_size
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class DPRSpanPredictor(DPRPreTrainedModel):
|
| 182 |
+
base_model_prefix = "encoder"
|
| 183 |
+
|
| 184 |
+
def __init__(self, config: DPRConfig):
|
| 185 |
+
super().__init__(config)
|
| 186 |
+
self.encoder = DPREncoder(config)
|
| 187 |
+
self.qa_outputs = nn.Linear(self.encoder.embeddings_size, 2)
|
| 188 |
+
self.qa_classifier = nn.Linear(self.encoder.embeddings_size, 1)
|
| 189 |
+
# Initialize weights and apply final processing
|
| 190 |
+
self.post_init()
|
| 191 |
+
|
| 192 |
+
def forward(
|
| 193 |
+
self,
|
| 194 |
+
input_ids: Tensor,
|
| 195 |
+
attention_mask: Tensor,
|
| 196 |
+
inputs_embeds: Optional[Tensor] = None,
|
| 197 |
+
output_attentions: bool = False,
|
| 198 |
+
output_hidden_states: bool = False,
|
| 199 |
+
return_dict: bool = False,
|
| 200 |
+
) -> Union[DPRReaderOutput, tuple[Tensor, ...]]:
|
| 201 |
+
# notations: N - number of questions in a batch, M - number of passages per questions, L - sequence length
|
| 202 |
+
n_passages, sequence_length = input_ids.size() if input_ids is not None else inputs_embeds.size()[:2]
|
| 203 |
+
# feed encoder
|
| 204 |
+
outputs = self.encoder(
|
| 205 |
+
input_ids,
|
| 206 |
+
attention_mask=attention_mask,
|
| 207 |
+
inputs_embeds=inputs_embeds,
|
| 208 |
+
output_attentions=output_attentions,
|
| 209 |
+
output_hidden_states=output_hidden_states,
|
| 210 |
+
return_dict=return_dict,
|
| 211 |
+
)
|
| 212 |
+
sequence_output = outputs[0]
|
| 213 |
+
|
| 214 |
+
# compute logits
|
| 215 |
+
logits = self.qa_outputs(sequence_output)
|
| 216 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 217 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 218 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 219 |
+
relevance_logits = self.qa_classifier(sequence_output[:, 0, :])
|
| 220 |
+
|
| 221 |
+
# resize
|
| 222 |
+
start_logits = start_logits.view(n_passages, sequence_length)
|
| 223 |
+
end_logits = end_logits.view(n_passages, sequence_length)
|
| 224 |
+
relevance_logits = relevance_logits.view(n_passages)
|
| 225 |
+
|
| 226 |
+
if not return_dict:
|
| 227 |
+
return (start_logits, end_logits, relevance_logits) + outputs[2:]
|
| 228 |
+
|
| 229 |
+
return DPRReaderOutput(
|
| 230 |
+
start_logits=start_logits,
|
| 231 |
+
end_logits=end_logits,
|
| 232 |
+
relevance_logits=relevance_logits,
|
| 233 |
+
hidden_states=outputs.hidden_states,
|
| 234 |
+
attentions=outputs.attentions,
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
##################
|
| 239 |
+
# PreTrainedModel
|
| 240 |
+
##################
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class DPRPretrainedContextEncoder(DPRPreTrainedModel):
|
| 244 |
+
"""
|
| 245 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 246 |
+
models.
|
| 247 |
+
"""
|
| 248 |
+
|
| 249 |
+
config: DPRConfig
|
| 250 |
+
load_tf_weights = None
|
| 251 |
+
base_model_prefix = "ctx_encoder"
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class DPRPretrainedQuestionEncoder(DPRPreTrainedModel):
|
| 255 |
+
"""
|
| 256 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 257 |
+
models.
|
| 258 |
+
"""
|
| 259 |
+
|
| 260 |
+
config: DPRConfig
|
| 261 |
+
load_tf_weights = None
|
| 262 |
+
base_model_prefix = "question_encoder"
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
class DPRPretrainedReader(DPRPreTrainedModel):
|
| 266 |
+
"""
|
| 267 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 268 |
+
models.
|
| 269 |
+
"""
|
| 270 |
+
|
| 271 |
+
config: DPRConfig
|
| 272 |
+
load_tf_weights = None
|
| 273 |
+
base_model_prefix = "span_predictor"
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
###############
|
| 277 |
+
# Actual Models
|
| 278 |
+
###############
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
@auto_docstring(
|
| 282 |
+
custom_intro="""
|
| 283 |
+
The bare DPRContextEncoder transformer outputting pooler outputs as context representations.
|
| 284 |
+
"""
|
| 285 |
+
)
|
| 286 |
+
class DPRContextEncoder(DPRPretrainedContextEncoder):
|
| 287 |
+
def __init__(self, config: DPRConfig):
|
| 288 |
+
super().__init__(config)
|
| 289 |
+
self.config = config
|
| 290 |
+
self.ctx_encoder = DPREncoder(config)
|
| 291 |
+
# Initialize weights and apply final processing
|
| 292 |
+
self.post_init()
|
| 293 |
+
|
| 294 |
+
@auto_docstring
|
| 295 |
+
def forward(
|
| 296 |
+
self,
|
| 297 |
+
input_ids: Optional[Tensor] = None,
|
| 298 |
+
attention_mask: Optional[Tensor] = None,
|
| 299 |
+
token_type_ids: Optional[Tensor] = None,
|
| 300 |
+
inputs_embeds: Optional[Tensor] = None,
|
| 301 |
+
output_attentions: Optional[bool] = None,
|
| 302 |
+
output_hidden_states: Optional[bool] = None,
|
| 303 |
+
return_dict: Optional[bool] = None,
|
| 304 |
+
) -> Union[DPRContextEncoderOutput, tuple[Tensor, ...]]:
|
| 305 |
+
r"""
|
| 306 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 307 |
+
Indices of input sequence tokens in the vocabulary. To match pretraining, DPR input sequence should be
|
| 308 |
+
formatted with [CLS] and [SEP] tokens as follows:
|
| 309 |
+
|
| 310 |
+
(a) For sequence pairs (for a pair title+text for example):
|
| 311 |
+
|
| 312 |
+
```
|
| 313 |
+
tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
|
| 314 |
+
token_type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
|
| 315 |
+
```
|
| 316 |
+
|
| 317 |
+
(b) For single sequences (for a question for example):
|
| 318 |
+
|
| 319 |
+
```
|
| 320 |
+
tokens: [CLS] the dog is hairy . [SEP]
|
| 321 |
+
token_type_ids: 0 0 0 0 0 0 0
|
| 322 |
+
```
|
| 323 |
+
|
| 324 |
+
DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
|
| 325 |
+
rather than the left.
|
| 326 |
+
|
| 327 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 328 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 329 |
+
|
| 330 |
+
[What are input IDs?](../glossary#input-ids)
|
| 331 |
+
|
| 332 |
+
Examples:
|
| 333 |
+
|
| 334 |
+
```python
|
| 335 |
+
>>> from transformers import DPRContextEncoder, DPRContextEncoderTokenizer
|
| 336 |
+
|
| 337 |
+
>>> tokenizer = DPRContextEncoderTokenizer.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base")
|
| 338 |
+
>>> model = DPRContextEncoder.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base")
|
| 339 |
+
>>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="pt")["input_ids"]
|
| 340 |
+
>>> embeddings = model(input_ids).pooler_output
|
| 341 |
+
```"""
|
| 342 |
+
|
| 343 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 344 |
+
output_hidden_states = (
|
| 345 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 346 |
+
)
|
| 347 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 348 |
+
|
| 349 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 350 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 351 |
+
elif input_ids is not None:
|
| 352 |
+
input_shape = input_ids.size()
|
| 353 |
+
elif inputs_embeds is not None:
|
| 354 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 355 |
+
else:
|
| 356 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 357 |
+
|
| 358 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 359 |
+
|
| 360 |
+
if attention_mask is None:
|
| 361 |
+
attention_mask = (
|
| 362 |
+
torch.ones(input_shape, device=device)
|
| 363 |
+
if input_ids is None
|
| 364 |
+
else (input_ids != self.config.pad_token_id)
|
| 365 |
+
)
|
| 366 |
+
if token_type_ids is None:
|
| 367 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 368 |
+
|
| 369 |
+
outputs = self.ctx_encoder(
|
| 370 |
+
input_ids=input_ids,
|
| 371 |
+
attention_mask=attention_mask,
|
| 372 |
+
token_type_ids=token_type_ids,
|
| 373 |
+
inputs_embeds=inputs_embeds,
|
| 374 |
+
output_attentions=output_attentions,
|
| 375 |
+
output_hidden_states=output_hidden_states,
|
| 376 |
+
return_dict=return_dict,
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
if not return_dict:
|
| 380 |
+
return outputs[1:]
|
| 381 |
+
return DPRContextEncoderOutput(
|
| 382 |
+
pooler_output=outputs.pooler_output, hidden_states=outputs.hidden_states, attentions=outputs.attentions
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
@auto_docstring(
|
| 387 |
+
custom_intro="""
|
| 388 |
+
The bare DPRQuestionEncoder transformer outputting pooler outputs as question representations.
|
| 389 |
+
"""
|
| 390 |
+
)
|
| 391 |
+
class DPRQuestionEncoder(DPRPretrainedQuestionEncoder):
|
| 392 |
+
def __init__(self, config: DPRConfig):
|
| 393 |
+
super().__init__(config)
|
| 394 |
+
self.config = config
|
| 395 |
+
self.question_encoder = DPREncoder(config)
|
| 396 |
+
# Initialize weights and apply final processing
|
| 397 |
+
self.post_init()
|
| 398 |
+
|
| 399 |
+
@auto_docstring
|
| 400 |
+
def forward(
|
| 401 |
+
self,
|
| 402 |
+
input_ids: Optional[Tensor] = None,
|
| 403 |
+
attention_mask: Optional[Tensor] = None,
|
| 404 |
+
token_type_ids: Optional[Tensor] = None,
|
| 405 |
+
inputs_embeds: Optional[Tensor] = None,
|
| 406 |
+
output_attentions: Optional[bool] = None,
|
| 407 |
+
output_hidden_states: Optional[bool] = None,
|
| 408 |
+
return_dict: Optional[bool] = None,
|
| 409 |
+
) -> Union[DPRQuestionEncoderOutput, tuple[Tensor, ...]]:
|
| 410 |
+
r"""
|
| 411 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 412 |
+
Indices of input sequence tokens in the vocabulary. To match pretraining, DPR input sequence should be
|
| 413 |
+
formatted with [CLS] and [SEP] tokens as follows:
|
| 414 |
+
|
| 415 |
+
(a) For sequence pairs (for a pair title+text for example):
|
| 416 |
+
|
| 417 |
+
```
|
| 418 |
+
tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
|
| 419 |
+
token_type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
|
| 420 |
+
```
|
| 421 |
+
|
| 422 |
+
(b) For single sequences (for a question for example):
|
| 423 |
+
|
| 424 |
+
```
|
| 425 |
+
tokens: [CLS] the dog is hairy . [SEP]
|
| 426 |
+
token_type_ids: 0 0 0 0 0 0 0
|
| 427 |
+
```
|
| 428 |
+
|
| 429 |
+
DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
|
| 430 |
+
rather than the left.
|
| 431 |
+
|
| 432 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 433 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 434 |
+
|
| 435 |
+
[What are input IDs?](../glossary#input-ids)
|
| 436 |
+
|
| 437 |
+
Examples:
|
| 438 |
+
|
| 439 |
+
```python
|
| 440 |
+
>>> from transformers import DPRQuestionEncoder, DPRQuestionEncoderTokenizer
|
| 441 |
+
|
| 442 |
+
>>> tokenizer = DPRQuestionEncoderTokenizer.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
|
| 443 |
+
>>> model = DPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
|
| 444 |
+
>>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="pt")["input_ids"]
|
| 445 |
+
>>> embeddings = model(input_ids).pooler_output
|
| 446 |
+
```
|
| 447 |
+
"""
|
| 448 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 449 |
+
output_hidden_states = (
|
| 450 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 451 |
+
)
|
| 452 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 453 |
+
|
| 454 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 455 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 456 |
+
elif input_ids is not None:
|
| 457 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 458 |
+
input_shape = input_ids.size()
|
| 459 |
+
elif inputs_embeds is not None:
|
| 460 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 461 |
+
else:
|
| 462 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 463 |
+
|
| 464 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 465 |
+
|
| 466 |
+
if attention_mask is None:
|
| 467 |
+
attention_mask = (
|
| 468 |
+
torch.ones(input_shape, device=device)
|
| 469 |
+
if input_ids is None
|
| 470 |
+
else (input_ids != self.config.pad_token_id)
|
| 471 |
+
)
|
| 472 |
+
if token_type_ids is None:
|
| 473 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 474 |
+
|
| 475 |
+
outputs = self.question_encoder(
|
| 476 |
+
input_ids=input_ids,
|
| 477 |
+
attention_mask=attention_mask,
|
| 478 |
+
token_type_ids=token_type_ids,
|
| 479 |
+
inputs_embeds=inputs_embeds,
|
| 480 |
+
output_attentions=output_attentions,
|
| 481 |
+
output_hidden_states=output_hidden_states,
|
| 482 |
+
return_dict=return_dict,
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
if not return_dict:
|
| 486 |
+
return outputs[1:]
|
| 487 |
+
return DPRQuestionEncoderOutput(
|
| 488 |
+
pooler_output=outputs.pooler_output, hidden_states=outputs.hidden_states, attentions=outputs.attentions
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
@auto_docstring(
|
| 493 |
+
custom_intro="""
|
| 494 |
+
The bare DPRReader transformer outputting span predictions.
|
| 495 |
+
"""
|
| 496 |
+
)
|
| 497 |
+
class DPRReader(DPRPretrainedReader):
|
| 498 |
+
def __init__(self, config: DPRConfig):
|
| 499 |
+
super().__init__(config)
|
| 500 |
+
self.config = config
|
| 501 |
+
self.span_predictor = DPRSpanPredictor(config)
|
| 502 |
+
# Initialize weights and apply final processing
|
| 503 |
+
self.post_init()
|
| 504 |
+
|
| 505 |
+
@auto_docstring
|
| 506 |
+
def forward(
|
| 507 |
+
self,
|
| 508 |
+
input_ids: Optional[Tensor] = None,
|
| 509 |
+
attention_mask: Optional[Tensor] = None,
|
| 510 |
+
inputs_embeds: Optional[Tensor] = None,
|
| 511 |
+
output_attentions: Optional[bool] = None,
|
| 512 |
+
output_hidden_states: Optional[bool] = None,
|
| 513 |
+
return_dict: Optional[bool] = None,
|
| 514 |
+
) -> Union[DPRReaderOutput, tuple[Tensor, ...]]:
|
| 515 |
+
r"""
|
| 516 |
+
input_ids (`tuple[torch.LongTensor]` of shapes `(n_passages, sequence_length)`):
|
| 517 |
+
Indices of input sequence tokens in the vocabulary. It has to be a sequence triplet with 1) the question
|
| 518 |
+
and 2) the passages titles and 3) the passages texts To match pretraining, DPR `input_ids` sequence should
|
| 519 |
+
be formatted with [CLS] and [SEP] with the format:
|
| 520 |
+
|
| 521 |
+
`[CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>`
|
| 522 |
+
|
| 523 |
+
DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
|
| 524 |
+
rather than the left.
|
| 525 |
+
|
| 526 |
+
Indices can be obtained using [`DPRReaderTokenizer`]. See this class documentation for more details.
|
| 527 |
+
|
| 528 |
+
[What are input IDs?](../glossary#input-ids)
|
| 529 |
+
inputs_embeds (`torch.FloatTensor` of shape `(n_passages, sequence_length, hidden_size)`, *optional*):
|
| 530 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 531 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 532 |
+
model's internal embedding lookup matrix.
|
| 533 |
+
|
| 534 |
+
Examples:
|
| 535 |
+
|
| 536 |
+
```python
|
| 537 |
+
>>> from transformers import DPRReader, DPRReaderTokenizer
|
| 538 |
+
|
| 539 |
+
>>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
|
| 540 |
+
>>> model = DPRReader.from_pretrained("facebook/dpr-reader-single-nq-base")
|
| 541 |
+
>>> encoded_inputs = tokenizer(
|
| 542 |
+
... questions=["What is love ?"],
|
| 543 |
+
... titles=["Haddaway"],
|
| 544 |
+
... texts=["'What Is Love' is a song recorded by the artist Haddaway"],
|
| 545 |
+
... return_tensors="pt",
|
| 546 |
+
... )
|
| 547 |
+
>>> outputs = model(**encoded_inputs)
|
| 548 |
+
>>> start_logits = outputs.start_logits
|
| 549 |
+
>>> end_logits = outputs.end_logits
|
| 550 |
+
>>> relevance_logits = outputs.relevance_logits
|
| 551 |
+
```
|
| 552 |
+
"""
|
| 553 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 554 |
+
output_hidden_states = (
|
| 555 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 556 |
+
)
|
| 557 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 558 |
+
|
| 559 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 560 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 561 |
+
elif input_ids is not None:
|
| 562 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 563 |
+
input_shape = input_ids.size()
|
| 564 |
+
elif inputs_embeds is not None:
|
| 565 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 566 |
+
else:
|
| 567 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 568 |
+
|
| 569 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 570 |
+
|
| 571 |
+
if attention_mask is None:
|
| 572 |
+
attention_mask = torch.ones(input_shape, device=device)
|
| 573 |
+
|
| 574 |
+
return self.span_predictor(
|
| 575 |
+
input_ids,
|
| 576 |
+
attention_mask,
|
| 577 |
+
inputs_embeds=inputs_embeds,
|
| 578 |
+
output_attentions=output_attentions,
|
| 579 |
+
output_hidden_states=output_hidden_states,
|
| 580 |
+
return_dict=return_dict,
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
__all__ = [
|
| 585 |
+
"DPRContextEncoder",
|
| 586 |
+
"DPRPretrainedContextEncoder",
|
| 587 |
+
"DPRPreTrainedModel",
|
| 588 |
+
"DPRPretrainedQuestionEncoder",
|
| 589 |
+
"DPRPretrainedReader",
|
| 590 |
+
"DPRQuestionEncoder",
|
| 591 |
+
"DPRReader",
|
| 592 |
+
]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dpr/modeling_tf_dpr.py
ADDED
|
@@ -0,0 +1,799 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 DPR Authors, The Hugging Face Team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
"""TensorFlow DPR model for Open Domain Question Answering."""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
|
| 22 |
+
import tensorflow as tf
|
| 23 |
+
|
| 24 |
+
from ...modeling_tf_outputs import TFBaseModelOutputWithPooling
|
| 25 |
+
from ...modeling_tf_utils import TFModelInputType, TFPreTrainedModel, get_initializer, keras, shape_list, unpack_inputs
|
| 26 |
+
from ...utils import (
|
| 27 |
+
ModelOutput,
|
| 28 |
+
add_start_docstrings,
|
| 29 |
+
add_start_docstrings_to_model_forward,
|
| 30 |
+
logging,
|
| 31 |
+
replace_return_docstrings,
|
| 32 |
+
)
|
| 33 |
+
from ..bert.modeling_tf_bert import TFBertMainLayer
|
| 34 |
+
from .configuration_dpr import DPRConfig
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
logger = logging.get_logger(__name__)
|
| 38 |
+
|
| 39 |
+
_CONFIG_FOR_DOC = "DPRConfig"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
##########
|
| 43 |
+
# Outputs
|
| 44 |
+
##########
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclass
|
| 48 |
+
class TFDPRContextEncoderOutput(ModelOutput):
|
| 49 |
+
r"""
|
| 50 |
+
Class for outputs of [`TFDPRContextEncoder`].
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
pooler_output (`tf.Tensor` of shape `(batch_size, embeddings_size)`):
|
| 54 |
+
The DPR encoder outputs the *pooler_output* that corresponds to the context representation. Last layer
|
| 55 |
+
hidden-state of the first token of the sequence (classification token) further processed by a Linear layer.
|
| 56 |
+
This output is to be used to embed contexts for nearest neighbors queries with questions embeddings.
|
| 57 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 58 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 59 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 60 |
+
|
| 61 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 62 |
+
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 63 |
+
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 64 |
+
sequence_length)`.
|
| 65 |
+
|
| 66 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 67 |
+
heads.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
pooler_output: tf.Tensor | None = None
|
| 71 |
+
hidden_states: tuple[tf.Tensor, ...] | None = None
|
| 72 |
+
attentions: tuple[tf.Tensor, ...] | None = None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@dataclass
|
| 76 |
+
class TFDPRQuestionEncoderOutput(ModelOutput):
|
| 77 |
+
"""
|
| 78 |
+
Class for outputs of [`TFDPRQuestionEncoder`].
|
| 79 |
+
|
| 80 |
+
Args:
|
| 81 |
+
pooler_output (`tf.Tensor` of shape `(batch_size, embeddings_size)`):
|
| 82 |
+
The DPR encoder outputs the *pooler_output* that corresponds to the question representation. Last layer
|
| 83 |
+
hidden-state of the first token of the sequence (classification token) further processed by a Linear layer.
|
| 84 |
+
This output is to be used to embed questions for nearest neighbors queries with context embeddings.
|
| 85 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 86 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 87 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 88 |
+
|
| 89 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 90 |
+
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 91 |
+
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 92 |
+
sequence_length)`.
|
| 93 |
+
|
| 94 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 95 |
+
heads.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
pooler_output: tf.Tensor | None = None
|
| 99 |
+
hidden_states: tuple[tf.Tensor, ...] | None = None
|
| 100 |
+
attentions: tuple[tf.Tensor, ...] | None = None
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@dataclass
|
| 104 |
+
class TFDPRReaderOutput(ModelOutput):
|
| 105 |
+
"""
|
| 106 |
+
Class for outputs of [`TFDPRReaderEncoder`].
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
start_logits (`tf.Tensor` of shape `(n_passages, sequence_length)`):
|
| 110 |
+
Logits of the start index of the span for each passage.
|
| 111 |
+
end_logits (`tf.Tensor` of shape `(n_passages, sequence_length)`):
|
| 112 |
+
Logits of the end index of the span for each passage.
|
| 113 |
+
relevance_logits (`tf.Tensor` of shape `(n_passages, )`):
|
| 114 |
+
Outputs of the QA classifier of the DPRReader that corresponds to the scores of each passage to answer the
|
| 115 |
+
question, compared to all the other passages.
|
| 116 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 117 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 118 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 119 |
+
|
| 120 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 121 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 122 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 123 |
+
sequence_length)`.
|
| 124 |
+
|
| 125 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 126 |
+
heads.
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
start_logits: tf.Tensor | None = None
|
| 130 |
+
end_logits: tf.Tensor | None = None
|
| 131 |
+
relevance_logits: tf.Tensor | None = None
|
| 132 |
+
hidden_states: tuple[tf.Tensor, ...] | None = None
|
| 133 |
+
attentions: tuple[tf.Tensor, ...] | None = None
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class TFDPREncoderLayer(keras.layers.Layer):
|
| 137 |
+
base_model_prefix = "bert_model"
|
| 138 |
+
|
| 139 |
+
def __init__(self, config: DPRConfig, **kwargs):
|
| 140 |
+
super().__init__(**kwargs)
|
| 141 |
+
|
| 142 |
+
# resolve name conflict with TFBertMainLayer instead of TFBertModel
|
| 143 |
+
self.bert_model = TFBertMainLayer(config, add_pooling_layer=False, name="bert_model")
|
| 144 |
+
self.config = config
|
| 145 |
+
|
| 146 |
+
if self.config.hidden_size <= 0:
|
| 147 |
+
raise ValueError("Encoder hidden_size can't be zero")
|
| 148 |
+
self.projection_dim = config.projection_dim
|
| 149 |
+
if self.projection_dim > 0:
|
| 150 |
+
self.encode_proj = keras.layers.Dense(
|
| 151 |
+
config.projection_dim, kernel_initializer=get_initializer(config.initializer_range), name="encode_proj"
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
@unpack_inputs
|
| 155 |
+
def call(
|
| 156 |
+
self,
|
| 157 |
+
input_ids: tf.Tensor | None = None,
|
| 158 |
+
attention_mask: tf.Tensor | None = None,
|
| 159 |
+
token_type_ids: tf.Tensor | None = None,
|
| 160 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 161 |
+
output_attentions: bool | None = None,
|
| 162 |
+
output_hidden_states: bool | None = None,
|
| 163 |
+
return_dict: bool | None = None,
|
| 164 |
+
training: bool = False,
|
| 165 |
+
) -> TFBaseModelOutputWithPooling | tuple[tf.Tensor, ...]:
|
| 166 |
+
outputs = self.bert_model(
|
| 167 |
+
input_ids=input_ids,
|
| 168 |
+
attention_mask=attention_mask,
|
| 169 |
+
token_type_ids=token_type_ids,
|
| 170 |
+
inputs_embeds=inputs_embeds,
|
| 171 |
+
output_attentions=output_attentions,
|
| 172 |
+
output_hidden_states=output_hidden_states,
|
| 173 |
+
return_dict=return_dict,
|
| 174 |
+
training=training,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
sequence_output = outputs[0]
|
| 178 |
+
pooled_output = sequence_output[:, 0, :]
|
| 179 |
+
if self.projection_dim > 0:
|
| 180 |
+
pooled_output = self.encode_proj(pooled_output)
|
| 181 |
+
|
| 182 |
+
if not return_dict:
|
| 183 |
+
return (sequence_output, pooled_output) + outputs[1:]
|
| 184 |
+
|
| 185 |
+
return TFBaseModelOutputWithPooling(
|
| 186 |
+
last_hidden_state=sequence_output,
|
| 187 |
+
pooler_output=pooled_output,
|
| 188 |
+
hidden_states=outputs.hidden_states,
|
| 189 |
+
attentions=outputs.attentions,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
@property
|
| 193 |
+
def embeddings_size(self) -> int:
|
| 194 |
+
if self.projection_dim > 0:
|
| 195 |
+
return self.projection_dim
|
| 196 |
+
return self.bert_model.config.hidden_size
|
| 197 |
+
|
| 198 |
+
def build(self, input_shape=None):
|
| 199 |
+
if self.built:
|
| 200 |
+
return
|
| 201 |
+
self.built = True
|
| 202 |
+
if getattr(self, "bert_model", None) is not None:
|
| 203 |
+
with tf.name_scope(self.bert_model.name):
|
| 204 |
+
self.bert_model.build(None)
|
| 205 |
+
if getattr(self, "encode_proj", None) is not None:
|
| 206 |
+
with tf.name_scope(self.encode_proj.name):
|
| 207 |
+
self.encode_proj.build(None)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class TFDPRSpanPredictorLayer(keras.layers.Layer):
|
| 211 |
+
base_model_prefix = "encoder"
|
| 212 |
+
|
| 213 |
+
def __init__(self, config: DPRConfig, **kwargs):
|
| 214 |
+
super().__init__(**kwargs)
|
| 215 |
+
self.config = config
|
| 216 |
+
self.encoder = TFDPREncoderLayer(config, name="encoder")
|
| 217 |
+
|
| 218 |
+
self.qa_outputs = keras.layers.Dense(
|
| 219 |
+
2, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
|
| 220 |
+
)
|
| 221 |
+
self.qa_classifier = keras.layers.Dense(
|
| 222 |
+
1, kernel_initializer=get_initializer(config.initializer_range), name="qa_classifier"
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
@unpack_inputs
|
| 226 |
+
def call(
|
| 227 |
+
self,
|
| 228 |
+
input_ids: tf.Tensor | None = None,
|
| 229 |
+
attention_mask: tf.Tensor | None = None,
|
| 230 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 231 |
+
output_attentions: bool = False,
|
| 232 |
+
output_hidden_states: bool = False,
|
| 233 |
+
return_dict: bool = False,
|
| 234 |
+
training: bool = False,
|
| 235 |
+
) -> TFDPRReaderOutput | tuple[tf.Tensor, ...]:
|
| 236 |
+
# notations: N - number of questions in a batch, M - number of passages per questions, L - sequence length
|
| 237 |
+
n_passages, sequence_length = shape_list(input_ids) if input_ids is not None else shape_list(inputs_embeds)[:2]
|
| 238 |
+
# feed encoder
|
| 239 |
+
outputs = self.encoder(
|
| 240 |
+
input_ids=input_ids,
|
| 241 |
+
attention_mask=attention_mask,
|
| 242 |
+
inputs_embeds=inputs_embeds,
|
| 243 |
+
output_attentions=output_attentions,
|
| 244 |
+
output_hidden_states=output_hidden_states,
|
| 245 |
+
return_dict=return_dict,
|
| 246 |
+
training=training,
|
| 247 |
+
)
|
| 248 |
+
sequence_output = outputs[0]
|
| 249 |
+
|
| 250 |
+
# compute logits
|
| 251 |
+
logits = self.qa_outputs(sequence_output)
|
| 252 |
+
start_logits, end_logits = tf.split(logits, 2, axis=-1)
|
| 253 |
+
start_logits = tf.squeeze(start_logits, axis=-1)
|
| 254 |
+
end_logits = tf.squeeze(end_logits, axis=-1)
|
| 255 |
+
relevance_logits = self.qa_classifier(sequence_output[:, 0, :])
|
| 256 |
+
|
| 257 |
+
# resize
|
| 258 |
+
start_logits = tf.reshape(start_logits, [n_passages, sequence_length])
|
| 259 |
+
end_logits = tf.reshape(end_logits, [n_passages, sequence_length])
|
| 260 |
+
relevance_logits = tf.reshape(relevance_logits, [n_passages])
|
| 261 |
+
|
| 262 |
+
if not return_dict:
|
| 263 |
+
return (start_logits, end_logits, relevance_logits) + outputs[2:]
|
| 264 |
+
|
| 265 |
+
return TFDPRReaderOutput(
|
| 266 |
+
start_logits=start_logits,
|
| 267 |
+
end_logits=end_logits,
|
| 268 |
+
relevance_logits=relevance_logits,
|
| 269 |
+
hidden_states=outputs.hidden_states,
|
| 270 |
+
attentions=outputs.attentions,
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
def build(self, input_shape=None):
|
| 274 |
+
if self.built:
|
| 275 |
+
return
|
| 276 |
+
self.built = True
|
| 277 |
+
if getattr(self, "encoder", None) is not None:
|
| 278 |
+
with tf.name_scope(self.encoder.name):
|
| 279 |
+
self.encoder.build(None)
|
| 280 |
+
if getattr(self, "qa_outputs", None) is not None:
|
| 281 |
+
with tf.name_scope(self.qa_outputs.name):
|
| 282 |
+
self.qa_outputs.build([None, None, self.encoder.embeddings_size])
|
| 283 |
+
if getattr(self, "qa_classifier", None) is not None:
|
| 284 |
+
with tf.name_scope(self.qa_classifier.name):
|
| 285 |
+
self.qa_classifier.build([None, None, self.encoder.embeddings_size])
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class TFDPRSpanPredictor(TFPreTrainedModel):
|
| 289 |
+
base_model_prefix = "encoder"
|
| 290 |
+
|
| 291 |
+
def __init__(self, config: DPRConfig, **kwargs):
|
| 292 |
+
super().__init__(config, **kwargs)
|
| 293 |
+
self.encoder = TFDPRSpanPredictorLayer(config)
|
| 294 |
+
|
| 295 |
+
@unpack_inputs
|
| 296 |
+
def call(
|
| 297 |
+
self,
|
| 298 |
+
input_ids: tf.Tensor | None = None,
|
| 299 |
+
attention_mask: tf.Tensor | None = None,
|
| 300 |
+
token_type_ids: tf.Tensor | None = None,
|
| 301 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 302 |
+
output_attentions: bool = False,
|
| 303 |
+
output_hidden_states: bool = False,
|
| 304 |
+
return_dict: bool = False,
|
| 305 |
+
training: bool = False,
|
| 306 |
+
) -> TFDPRReaderOutput | tuple[tf.Tensor, ...]:
|
| 307 |
+
outputs = self.encoder(
|
| 308 |
+
input_ids=input_ids,
|
| 309 |
+
attention_mask=attention_mask,
|
| 310 |
+
inputs_embeds=inputs_embeds,
|
| 311 |
+
output_attentions=output_attentions,
|
| 312 |
+
output_hidden_states=output_hidden_states,
|
| 313 |
+
return_dict=return_dict,
|
| 314 |
+
training=training,
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
return outputs
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
class TFDPREncoder(TFPreTrainedModel):
|
| 321 |
+
base_model_prefix = "encoder"
|
| 322 |
+
|
| 323 |
+
def __init__(self, config: DPRConfig, **kwargs):
|
| 324 |
+
super().__init__(config, **kwargs)
|
| 325 |
+
|
| 326 |
+
self.encoder = TFDPREncoderLayer(config)
|
| 327 |
+
|
| 328 |
+
@unpack_inputs
|
| 329 |
+
def call(
|
| 330 |
+
self,
|
| 331 |
+
input_ids: tf.Tensor | None = None,
|
| 332 |
+
attention_mask: tf.Tensor | None = None,
|
| 333 |
+
token_type_ids: tf.Tensor | None = None,
|
| 334 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 335 |
+
output_attentions: bool = False,
|
| 336 |
+
output_hidden_states: bool = False,
|
| 337 |
+
return_dict: bool = False,
|
| 338 |
+
training: bool = False,
|
| 339 |
+
) -> TFDPRReaderOutput | tuple[tf.Tensor, ...]:
|
| 340 |
+
outputs = self.encoder(
|
| 341 |
+
input_ids=input_ids,
|
| 342 |
+
attention_mask=attention_mask,
|
| 343 |
+
inputs_embeds=inputs_embeds,
|
| 344 |
+
output_attentions=output_attentions,
|
| 345 |
+
output_hidden_states=output_hidden_states,
|
| 346 |
+
return_dict=return_dict,
|
| 347 |
+
training=training,
|
| 348 |
+
)
|
| 349 |
+
return outputs
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
##################
|
| 353 |
+
# PreTrainedModel
|
| 354 |
+
##################
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
class TFDPRPretrainedContextEncoder(TFPreTrainedModel):
|
| 358 |
+
"""
|
| 359 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 360 |
+
models.
|
| 361 |
+
"""
|
| 362 |
+
|
| 363 |
+
config_class = DPRConfig
|
| 364 |
+
base_model_prefix = "ctx_encoder"
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
class TFDPRPretrainedQuestionEncoder(TFPreTrainedModel):
|
| 368 |
+
"""
|
| 369 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 370 |
+
models.
|
| 371 |
+
"""
|
| 372 |
+
|
| 373 |
+
config_class = DPRConfig
|
| 374 |
+
base_model_prefix = "question_encoder"
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
class TFDPRPretrainedReader(TFPreTrainedModel):
|
| 378 |
+
"""
|
| 379 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 380 |
+
models.
|
| 381 |
+
"""
|
| 382 |
+
|
| 383 |
+
config_class = DPRConfig
|
| 384 |
+
base_model_prefix = "reader"
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
###############
|
| 388 |
+
# Actual Models
|
| 389 |
+
###############
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
TF_DPR_START_DOCSTRING = r"""
|
| 393 |
+
|
| 394 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 395 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 396 |
+
etc.)
|
| 397 |
+
|
| 398 |
+
This model is also a Tensorflow [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model)
|
| 399 |
+
subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to
|
| 400 |
+
general usage and behavior.
|
| 401 |
+
|
| 402 |
+
<Tip>
|
| 403 |
+
|
| 404 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
| 405 |
+
|
| 406 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 407 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
| 408 |
+
|
| 409 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
| 410 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
| 411 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
| 412 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
| 413 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
| 414 |
+
positional argument:
|
| 415 |
+
|
| 416 |
+
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
|
| 417 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
| 418 |
+
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
|
| 419 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
| 420 |
+
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
|
| 421 |
+
|
| 422 |
+
Note that when creating models and layers with
|
| 423 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
| 424 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
| 425 |
+
|
| 426 |
+
</Tip>
|
| 427 |
+
|
| 428 |
+
Parameters:
|
| 429 |
+
config ([`DPRConfig`]): Model configuration class with all the parameters of the model.
|
| 430 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 431 |
+
configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 432 |
+
"""
|
| 433 |
+
|
| 434 |
+
TF_DPR_ENCODERS_INPUTS_DOCSTRING = r"""
|
| 435 |
+
Args:
|
| 436 |
+
input_ids (`Numpy array` or `tf.Tensor` of shape `(batch_size, sequence_length)`):
|
| 437 |
+
Indices of input sequence tokens in the vocabulary. To match pretraining, DPR input sequence should be
|
| 438 |
+
formatted with [CLS] and [SEP] tokens as follows:
|
| 439 |
+
|
| 440 |
+
(a) For sequence pairs (for a pair title+text for example):
|
| 441 |
+
|
| 442 |
+
```
|
| 443 |
+
tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
|
| 444 |
+
token_type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
|
| 445 |
+
```
|
| 446 |
+
|
| 447 |
+
(b) For single sequences (for a question for example):
|
| 448 |
+
|
| 449 |
+
```
|
| 450 |
+
tokens: [CLS] the dog is hairy . [SEP]
|
| 451 |
+
token_type_ids: 0 0 0 0 0 0 0
|
| 452 |
+
```
|
| 453 |
+
|
| 454 |
+
DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
|
| 455 |
+
rather than the left.
|
| 456 |
+
|
| 457 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 458 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 459 |
+
|
| 460 |
+
[What are input IDs?](../glossary#input-ids)
|
| 461 |
+
attention_mask (`Numpy array` or `tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 462 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 463 |
+
|
| 464 |
+
- 1 for tokens that are **not masked**,
|
| 465 |
+
- 0 for tokens that are **masked**.
|
| 466 |
+
|
| 467 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 468 |
+
token_type_ids (`Numpy array` or `tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 469 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 470 |
+
1]`:
|
| 471 |
+
|
| 472 |
+
- 0 corresponds to a *sentence A* token,
|
| 473 |
+
- 1 corresponds to a *sentence B* token.
|
| 474 |
+
|
| 475 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 476 |
+
inputs_embeds (`Numpy array` or `tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 477 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 478 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 479 |
+
model's internal embedding lookup matrix.
|
| 480 |
+
output_attentions (`bool`, *optional*):
|
| 481 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 482 |
+
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
|
| 483 |
+
config will be used instead.
|
| 484 |
+
output_hidden_states (`bool`, *optional*):
|
| 485 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 486 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 487 |
+
used instead.
|
| 488 |
+
return_dict (`bool`, *optional*):
|
| 489 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 490 |
+
eager mode, in graph mode the value will always be set to True.
|
| 491 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 492 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 493 |
+
behaviors between training and evaluation).
|
| 494 |
+
"""
|
| 495 |
+
|
| 496 |
+
TF_DPR_READER_INPUTS_DOCSTRING = r"""
|
| 497 |
+
Args:
|
| 498 |
+
input_ids (`Numpy array` or `tf.Tensor` of shapes `(n_passages, sequence_length)`):
|
| 499 |
+
Indices of input sequence tokens in the vocabulary. It has to be a sequence triplet with 1) the question
|
| 500 |
+
and 2) the passages titles and 3) the passages texts To match pretraining, DPR `input_ids` sequence should
|
| 501 |
+
be formatted with [CLS] and [SEP] with the format:
|
| 502 |
+
|
| 503 |
+
`[CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>`
|
| 504 |
+
|
| 505 |
+
DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
|
| 506 |
+
rather than the left.
|
| 507 |
+
|
| 508 |
+
Indices can be obtained using [`DPRReaderTokenizer`]. See this class documentation for more details.
|
| 509 |
+
attention_mask (`Numpy array` or `tf.Tensor` of shape `(n_passages, sequence_length)`, *optional*):
|
| 510 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 511 |
+
|
| 512 |
+
- 1 for tokens that are **not masked**,
|
| 513 |
+
- 0 for tokens that are **masked**.
|
| 514 |
+
|
| 515 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 516 |
+
inputs_embeds (`Numpy array` or `tf.Tensor` of shape `(n_passages, sequence_length, hidden_size)`, *optional*):
|
| 517 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 518 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 519 |
+
model's internal embedding lookup matrix.
|
| 520 |
+
output_hidden_states (`bool`, *optional*):
|
| 521 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 522 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 523 |
+
used instead.
|
| 524 |
+
return_dict (`bool`, *optional*):
|
| 525 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 526 |
+
eager mode, in graph mode the value will always be set to True.
|
| 527 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 528 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 529 |
+
behaviors between training and evaluation).
|
| 530 |
+
"""
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
@add_start_docstrings(
|
| 534 |
+
"The bare DPRContextEncoder transformer outputting pooler outputs as context representations.",
|
| 535 |
+
TF_DPR_START_DOCSTRING,
|
| 536 |
+
)
|
| 537 |
+
class TFDPRContextEncoder(TFDPRPretrainedContextEncoder):
|
| 538 |
+
def __init__(self, config: DPRConfig, *args, **kwargs):
|
| 539 |
+
super().__init__(config, *args, **kwargs)
|
| 540 |
+
self.ctx_encoder = TFDPREncoderLayer(config, name="ctx_encoder")
|
| 541 |
+
|
| 542 |
+
def get_input_embeddings(self):
|
| 543 |
+
try:
|
| 544 |
+
return self.ctx_encoder.bert_model.get_input_embeddings()
|
| 545 |
+
except AttributeError:
|
| 546 |
+
self.build()
|
| 547 |
+
return self.ctx_encoder.bert_model.get_input_embeddings()
|
| 548 |
+
|
| 549 |
+
@unpack_inputs
|
| 550 |
+
@add_start_docstrings_to_model_forward(TF_DPR_ENCODERS_INPUTS_DOCSTRING)
|
| 551 |
+
@replace_return_docstrings(output_type=TFDPRContextEncoderOutput, config_class=_CONFIG_FOR_DOC)
|
| 552 |
+
def call(
|
| 553 |
+
self,
|
| 554 |
+
input_ids: TFModelInputType | None = None,
|
| 555 |
+
attention_mask: tf.Tensor | None = None,
|
| 556 |
+
token_type_ids: tf.Tensor | None = None,
|
| 557 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 558 |
+
output_attentions: bool | None = None,
|
| 559 |
+
output_hidden_states: bool | None = None,
|
| 560 |
+
return_dict: bool | None = None,
|
| 561 |
+
training: bool = False,
|
| 562 |
+
) -> TFDPRContextEncoderOutput | tuple[tf.Tensor, ...]:
|
| 563 |
+
r"""
|
| 564 |
+
Return:
|
| 565 |
+
|
| 566 |
+
Examples:
|
| 567 |
+
|
| 568 |
+
```python
|
| 569 |
+
>>> from transformers import TFDPRContextEncoder, DPRContextEncoderTokenizer
|
| 570 |
+
|
| 571 |
+
>>> tokenizer = DPRContextEncoderTokenizer.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base")
|
| 572 |
+
>>> model = TFDPRContextEncoder.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base", from_pt=True)
|
| 573 |
+
>>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="tf")["input_ids"]
|
| 574 |
+
>>> embeddings = model(input_ids).pooler_output
|
| 575 |
+
```
|
| 576 |
+
"""
|
| 577 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 578 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 579 |
+
elif input_ids is not None:
|
| 580 |
+
input_shape = shape_list(input_ids)
|
| 581 |
+
elif inputs_embeds is not None:
|
| 582 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 583 |
+
else:
|
| 584 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 585 |
+
|
| 586 |
+
if attention_mask is None:
|
| 587 |
+
attention_mask = (
|
| 588 |
+
tf.ones(input_shape, dtype=tf.dtypes.int32)
|
| 589 |
+
if input_ids is None
|
| 590 |
+
else (input_ids != self.config.pad_token_id)
|
| 591 |
+
)
|
| 592 |
+
if token_type_ids is None:
|
| 593 |
+
token_type_ids = tf.zeros(input_shape, dtype=tf.dtypes.int32)
|
| 594 |
+
|
| 595 |
+
outputs = self.ctx_encoder(
|
| 596 |
+
input_ids=input_ids,
|
| 597 |
+
attention_mask=attention_mask,
|
| 598 |
+
token_type_ids=token_type_ids,
|
| 599 |
+
inputs_embeds=inputs_embeds,
|
| 600 |
+
output_attentions=output_attentions,
|
| 601 |
+
output_hidden_states=output_hidden_states,
|
| 602 |
+
return_dict=return_dict,
|
| 603 |
+
training=training,
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
if not return_dict:
|
| 607 |
+
return outputs[1:]
|
| 608 |
+
|
| 609 |
+
return TFDPRContextEncoderOutput(
|
| 610 |
+
pooler_output=outputs.pooler_output, hidden_states=outputs.hidden_states, attentions=outputs.attentions
|
| 611 |
+
)
|
| 612 |
+
|
| 613 |
+
def build(self, input_shape=None):
|
| 614 |
+
if self.built:
|
| 615 |
+
return
|
| 616 |
+
self.built = True
|
| 617 |
+
if getattr(self, "ctx_encoder", None) is not None:
|
| 618 |
+
with tf.name_scope(self.ctx_encoder.name):
|
| 619 |
+
self.ctx_encoder.build(None)
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
@add_start_docstrings(
|
| 623 |
+
"The bare DPRQuestionEncoder transformer outputting pooler outputs as question representations.",
|
| 624 |
+
TF_DPR_START_DOCSTRING,
|
| 625 |
+
)
|
| 626 |
+
class TFDPRQuestionEncoder(TFDPRPretrainedQuestionEncoder):
|
| 627 |
+
def __init__(self, config: DPRConfig, *args, **kwargs):
|
| 628 |
+
super().__init__(config, *args, **kwargs)
|
| 629 |
+
self.question_encoder = TFDPREncoderLayer(config, name="question_encoder")
|
| 630 |
+
|
| 631 |
+
def get_input_embeddings(self):
|
| 632 |
+
try:
|
| 633 |
+
return self.question_encoder.bert_model.get_input_embeddings()
|
| 634 |
+
except AttributeError:
|
| 635 |
+
self.build()
|
| 636 |
+
return self.question_encoder.bert_model.get_input_embeddings()
|
| 637 |
+
|
| 638 |
+
@unpack_inputs
|
| 639 |
+
@add_start_docstrings_to_model_forward(TF_DPR_ENCODERS_INPUTS_DOCSTRING)
|
| 640 |
+
@replace_return_docstrings(output_type=TFDPRQuestionEncoderOutput, config_class=_CONFIG_FOR_DOC)
|
| 641 |
+
def call(
|
| 642 |
+
self,
|
| 643 |
+
input_ids: TFModelInputType | None = None,
|
| 644 |
+
attention_mask: tf.Tensor | None = None,
|
| 645 |
+
token_type_ids: tf.Tensor | None = None,
|
| 646 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 647 |
+
output_attentions: bool | None = None,
|
| 648 |
+
output_hidden_states: bool | None = None,
|
| 649 |
+
return_dict: bool | None = None,
|
| 650 |
+
training: bool = False,
|
| 651 |
+
) -> TFDPRQuestionEncoderOutput | tuple[tf.Tensor, ...]:
|
| 652 |
+
r"""
|
| 653 |
+
Return:
|
| 654 |
+
|
| 655 |
+
Examples:
|
| 656 |
+
|
| 657 |
+
```python
|
| 658 |
+
>>> from transformers import TFDPRQuestionEncoder, DPRQuestionEncoderTokenizer
|
| 659 |
+
|
| 660 |
+
>>> tokenizer = DPRQuestionEncoderTokenizer.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
|
| 661 |
+
>>> model = TFDPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base", from_pt=True)
|
| 662 |
+
>>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="tf")["input_ids"]
|
| 663 |
+
>>> embeddings = model(input_ids).pooler_output
|
| 664 |
+
```
|
| 665 |
+
"""
|
| 666 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 667 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 668 |
+
elif input_ids is not None:
|
| 669 |
+
input_shape = shape_list(input_ids)
|
| 670 |
+
elif inputs_embeds is not None:
|
| 671 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 672 |
+
else:
|
| 673 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 674 |
+
|
| 675 |
+
if attention_mask is None:
|
| 676 |
+
attention_mask = (
|
| 677 |
+
tf.ones(input_shape, dtype=tf.dtypes.int32)
|
| 678 |
+
if input_ids is None
|
| 679 |
+
else (input_ids != self.config.pad_token_id)
|
| 680 |
+
)
|
| 681 |
+
if token_type_ids is None:
|
| 682 |
+
token_type_ids = tf.zeros(input_shape, dtype=tf.dtypes.int32)
|
| 683 |
+
|
| 684 |
+
outputs = self.question_encoder(
|
| 685 |
+
input_ids=input_ids,
|
| 686 |
+
attention_mask=attention_mask,
|
| 687 |
+
token_type_ids=token_type_ids,
|
| 688 |
+
inputs_embeds=inputs_embeds,
|
| 689 |
+
output_attentions=output_attentions,
|
| 690 |
+
output_hidden_states=output_hidden_states,
|
| 691 |
+
return_dict=return_dict,
|
| 692 |
+
training=training,
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
if not return_dict:
|
| 696 |
+
return outputs[1:]
|
| 697 |
+
return TFDPRQuestionEncoderOutput(
|
| 698 |
+
pooler_output=outputs.pooler_output, hidden_states=outputs.hidden_states, attentions=outputs.attentions
|
| 699 |
+
)
|
| 700 |
+
|
| 701 |
+
def build(self, input_shape=None):
|
| 702 |
+
if self.built:
|
| 703 |
+
return
|
| 704 |
+
self.built = True
|
| 705 |
+
if getattr(self, "question_encoder", None) is not None:
|
| 706 |
+
with tf.name_scope(self.question_encoder.name):
|
| 707 |
+
self.question_encoder.build(None)
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
@add_start_docstrings(
|
| 711 |
+
"The bare DPRReader transformer outputting span predictions.",
|
| 712 |
+
TF_DPR_START_DOCSTRING,
|
| 713 |
+
)
|
| 714 |
+
class TFDPRReader(TFDPRPretrainedReader):
|
| 715 |
+
def __init__(self, config: DPRConfig, *args, **kwargs):
|
| 716 |
+
super().__init__(config, *args, **kwargs)
|
| 717 |
+
self.span_predictor = TFDPRSpanPredictorLayer(config, name="span_predictor")
|
| 718 |
+
|
| 719 |
+
def get_input_embeddings(self):
|
| 720 |
+
try:
|
| 721 |
+
return self.span_predictor.encoder.bert_model.get_input_embeddings()
|
| 722 |
+
except AttributeError:
|
| 723 |
+
self.build()
|
| 724 |
+
return self.span_predictor.encoder.bert_model.get_input_embeddings()
|
| 725 |
+
|
| 726 |
+
@unpack_inputs
|
| 727 |
+
@add_start_docstrings_to_model_forward(TF_DPR_READER_INPUTS_DOCSTRING)
|
| 728 |
+
@replace_return_docstrings(output_type=TFDPRReaderOutput, config_class=_CONFIG_FOR_DOC)
|
| 729 |
+
def call(
|
| 730 |
+
self,
|
| 731 |
+
input_ids: TFModelInputType | None = None,
|
| 732 |
+
attention_mask: tf.Tensor | None = None,
|
| 733 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 734 |
+
output_attentions: bool | None = None,
|
| 735 |
+
output_hidden_states: bool | None = None,
|
| 736 |
+
return_dict: bool | None = None,
|
| 737 |
+
training: bool = False,
|
| 738 |
+
) -> TFDPRReaderOutput | tuple[tf.Tensor, ...]:
|
| 739 |
+
r"""
|
| 740 |
+
Return:
|
| 741 |
+
|
| 742 |
+
Examples:
|
| 743 |
+
|
| 744 |
+
```python
|
| 745 |
+
>>> from transformers import TFDPRReader, DPRReaderTokenizer
|
| 746 |
+
|
| 747 |
+
>>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
|
| 748 |
+
>>> model = TFDPRReader.from_pretrained("facebook/dpr-reader-single-nq-base", from_pt=True)
|
| 749 |
+
>>> encoded_inputs = tokenizer(
|
| 750 |
+
... questions=["What is love ?"],
|
| 751 |
+
... titles=["Haddaway"],
|
| 752 |
+
... texts=["'What Is Love' is a song recorded by the artist Haddaway"],
|
| 753 |
+
... return_tensors="tf",
|
| 754 |
+
... )
|
| 755 |
+
>>> outputs = model(encoded_inputs)
|
| 756 |
+
>>> start_logits = outputs.start_logits
|
| 757 |
+
>>> end_logits = outputs.end_logits
|
| 758 |
+
>>> relevance_logits = outputs.relevance_logits
|
| 759 |
+
```
|
| 760 |
+
"""
|
| 761 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 762 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 763 |
+
elif input_ids is not None:
|
| 764 |
+
input_shape = shape_list(input_ids)
|
| 765 |
+
elif inputs_embeds is not None:
|
| 766 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 767 |
+
else:
|
| 768 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 769 |
+
|
| 770 |
+
if attention_mask is None:
|
| 771 |
+
attention_mask = tf.ones(input_shape, dtype=tf.dtypes.int32)
|
| 772 |
+
|
| 773 |
+
return self.span_predictor(
|
| 774 |
+
input_ids=input_ids,
|
| 775 |
+
attention_mask=attention_mask,
|
| 776 |
+
inputs_embeds=inputs_embeds,
|
| 777 |
+
output_attentions=output_attentions,
|
| 778 |
+
output_hidden_states=output_hidden_states,
|
| 779 |
+
return_dict=return_dict,
|
| 780 |
+
training=training,
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
def build(self, input_shape=None):
|
| 784 |
+
if self.built:
|
| 785 |
+
return
|
| 786 |
+
self.built = True
|
| 787 |
+
if getattr(self, "span_predictor", None) is not None:
|
| 788 |
+
with tf.name_scope(self.span_predictor.name):
|
| 789 |
+
self.span_predictor.build(None)
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
__all__ = [
|
| 793 |
+
"TFDPRContextEncoder",
|
| 794 |
+
"TFDPRPretrainedContextEncoder",
|
| 795 |
+
"TFDPRPretrainedQuestionEncoder",
|
| 796 |
+
"TFDPRPretrainedReader",
|
| 797 |
+
"TFDPRQuestionEncoder",
|
| 798 |
+
"TFDPRReader",
|
| 799 |
+
]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dpr/tokenization_dpr.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The HuggingFace Inc. team, The Hugging Face 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 DPR."""
|
| 16 |
+
|
| 17 |
+
import collections
|
| 18 |
+
from typing import Optional, Union
|
| 19 |
+
|
| 20 |
+
from ...tokenization_utils_base import BatchEncoding
|
| 21 |
+
from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging
|
| 22 |
+
from ..bert.tokenization_bert import BertTokenizer
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class DPRContextEncoderTokenizer(BertTokenizer):
|
| 31 |
+
r"""
|
| 32 |
+
Construct a DPRContextEncoder tokenizer.
|
| 33 |
+
|
| 34 |
+
[`DPRContextEncoderTokenizer`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation
|
| 35 |
+
splitting and wordpiece.
|
| 36 |
+
|
| 37 |
+
Refer to superclass [`BertTokenizer`] for usage examples and documentation concerning parameters.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class DPRQuestionEncoderTokenizer(BertTokenizer):
|
| 44 |
+
r"""
|
| 45 |
+
Constructs a DPRQuestionEncoder tokenizer.
|
| 46 |
+
|
| 47 |
+
[`DPRQuestionEncoderTokenizer`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation
|
| 48 |
+
splitting and wordpiece.
|
| 49 |
+
|
| 50 |
+
Refer to superclass [`BertTokenizer`] for usage examples and documentation concerning parameters.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
DPRSpanPrediction = collections.namedtuple(
|
| 57 |
+
"DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"]
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
DPRReaderOutput = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"])
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
CUSTOM_DPR_READER_DOCSTRING = r"""
|
| 64 |
+
Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.
|
| 65 |
+
It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),
|
| 66 |
+
using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`
|
| 67 |
+
with the format:
|
| 68 |
+
|
| 69 |
+
```
|
| 70 |
+
[CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
questions (`str` or `list[str]`):
|
| 75 |
+
The questions to be encoded. You can specify one question for many passages. In this case, the question
|
| 76 |
+
will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in
|
| 77 |
+
`titles` or `texts`.
|
| 78 |
+
titles (`str` or `list[str]`):
|
| 79 |
+
The passages titles to be encoded. This can be a string or a list of strings if there are several passages.
|
| 80 |
+
texts (`str` or `list[str]`):
|
| 81 |
+
The passages texts to be encoded. This can be a string or a list of strings if there are several passages.
|
| 82 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
|
| 83 |
+
Activates and controls padding. Accepts the following values:
|
| 84 |
+
|
| 85 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence
|
| 86 |
+
if provided).
|
| 87 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
| 88 |
+
acceptable input length for the model if that argument is not provided.
|
| 89 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
| 90 |
+
lengths).
|
| 91 |
+
truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
|
| 92 |
+
Activates and controls truncation. Accepts the following values:
|
| 93 |
+
|
| 94 |
+
- `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to
|
| 95 |
+
the maximum acceptable input length for the model if that argument is not provided. This will truncate
|
| 96 |
+
token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch
|
| 97 |
+
of pairs) is provided.
|
| 98 |
+
- `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
|
| 99 |
+
acceptable input length for the model if that argument is not provided. This will only truncate the first
|
| 100 |
+
sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
|
| 101 |
+
- `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
|
| 102 |
+
acceptable input length for the model if that argument is not provided. This will only truncate the
|
| 103 |
+
second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
|
| 104 |
+
- `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
|
| 105 |
+
greater than the model maximum admissible input size).
|
| 106 |
+
max_length (`int`, *optional*):
|
| 107 |
+
Controls the maximum length to use by one of the truncation/padding parameters.
|
| 108 |
+
|
| 109 |
+
If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
|
| 110 |
+
is required by one of the truncation/padding parameters. If the model has no specific maximum input
|
| 111 |
+
length (like XLNet) truncation/padding to a maximum length will be deactivated.
|
| 112 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 113 |
+
If set, will return tensors instead of list of python integers. Acceptable values are:
|
| 114 |
+
|
| 115 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 116 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 117 |
+
- `'np'`: Return Numpy `np.ndarray` objects.
|
| 118 |
+
return_attention_mask (`bool`, *optional*):
|
| 119 |
+
Whether or not to return the attention mask. If not set, will return the attention mask according to the
|
| 120 |
+
specific tokenizer's default, defined by the `return_outputs` attribute.
|
| 121 |
+
|
| 122 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 123 |
+
|
| 124 |
+
Returns:
|
| 125 |
+
`dict[str, list[list[int]]]`: A dictionary with the following keys:
|
| 126 |
+
|
| 127 |
+
- `input_ids`: List of token ids to be fed to a model.
|
| 128 |
+
- `attention_mask`: List of indices specifying which tokens should be attended to by the model.
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@add_start_docstrings(CUSTOM_DPR_READER_DOCSTRING)
|
| 133 |
+
class CustomDPRReaderTokenizerMixin:
|
| 134 |
+
def __call__(
|
| 135 |
+
self,
|
| 136 |
+
questions,
|
| 137 |
+
titles: Optional[str] = None,
|
| 138 |
+
texts: Optional[str] = None,
|
| 139 |
+
padding: Union[bool, str] = False,
|
| 140 |
+
truncation: Union[bool, str] = False,
|
| 141 |
+
max_length: Optional[int] = None,
|
| 142 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 143 |
+
return_attention_mask: Optional[bool] = None,
|
| 144 |
+
**kwargs,
|
| 145 |
+
) -> BatchEncoding:
|
| 146 |
+
if titles is None and texts is None:
|
| 147 |
+
return super().__call__(
|
| 148 |
+
questions,
|
| 149 |
+
padding=padding,
|
| 150 |
+
truncation=truncation,
|
| 151 |
+
max_length=max_length,
|
| 152 |
+
return_tensors=return_tensors,
|
| 153 |
+
return_attention_mask=return_attention_mask,
|
| 154 |
+
**kwargs,
|
| 155 |
+
)
|
| 156 |
+
elif titles is None or texts is None:
|
| 157 |
+
text_pair = titles if texts is None else texts
|
| 158 |
+
return super().__call__(
|
| 159 |
+
questions,
|
| 160 |
+
text_pair,
|
| 161 |
+
padding=padding,
|
| 162 |
+
truncation=truncation,
|
| 163 |
+
max_length=max_length,
|
| 164 |
+
return_tensors=return_tensors,
|
| 165 |
+
return_attention_mask=return_attention_mask,
|
| 166 |
+
**kwargs,
|
| 167 |
+
)
|
| 168 |
+
titles = titles if not isinstance(titles, str) else [titles]
|
| 169 |
+
texts = texts if not isinstance(texts, str) else [texts]
|
| 170 |
+
n_passages = len(titles)
|
| 171 |
+
questions = questions if not isinstance(questions, str) else [questions] * n_passages
|
| 172 |
+
if len(titles) != len(texts):
|
| 173 |
+
raise ValueError(
|
| 174 |
+
f"There should be as many titles than texts but got {len(titles)} titles and {len(texts)} texts."
|
| 175 |
+
)
|
| 176 |
+
encoded_question_and_titles = super().__call__(questions, titles, padding=False, truncation=False)["input_ids"]
|
| 177 |
+
encoded_texts = super().__call__(texts, add_special_tokens=False, padding=False, truncation=False)["input_ids"]
|
| 178 |
+
encoded_inputs = {
|
| 179 |
+
"input_ids": [
|
| 180 |
+
(encoded_question_and_title + encoded_text)[:max_length]
|
| 181 |
+
if max_length is not None and truncation
|
| 182 |
+
else encoded_question_and_title + encoded_text
|
| 183 |
+
for encoded_question_and_title, encoded_text in zip(encoded_question_and_titles, encoded_texts)
|
| 184 |
+
]
|
| 185 |
+
}
|
| 186 |
+
if return_attention_mask is not False:
|
| 187 |
+
attention_mask = []
|
| 188 |
+
for input_ids in encoded_inputs["input_ids"]:
|
| 189 |
+
attention_mask.append([int(input_id != self.pad_token_id) for input_id in input_ids])
|
| 190 |
+
encoded_inputs["attention_mask"] = attention_mask
|
| 191 |
+
return self.pad(encoded_inputs, padding=padding, max_length=max_length, return_tensors=return_tensors)
|
| 192 |
+
|
| 193 |
+
def decode_best_spans(
|
| 194 |
+
self,
|
| 195 |
+
reader_input: BatchEncoding,
|
| 196 |
+
reader_output: DPRReaderOutput,
|
| 197 |
+
num_spans: int = 16,
|
| 198 |
+
max_answer_length: int = 64,
|
| 199 |
+
num_spans_per_passage: int = 4,
|
| 200 |
+
) -> list[DPRSpanPrediction]:
|
| 201 |
+
"""
|
| 202 |
+
Get the span predictions for the extractive Q&A model.
|
| 203 |
+
|
| 204 |
+
Returns: *List* of *DPRReaderOutput* sorted by descending *(relevance_score, span_score)*. Each
|
| 205 |
+
*DPRReaderOutput* is a *Tuple* with:
|
| 206 |
+
|
| 207 |
+
- **span_score**: `float` that corresponds to the score given by the reader for this span compared to other
|
| 208 |
+
spans in the same passage. It corresponds to the sum of the start and end logits of the span.
|
| 209 |
+
- **relevance_score**: `float` that corresponds to the score of the each passage to answer the question,
|
| 210 |
+
compared to all the other passages. It corresponds to the output of the QA classifier of the DPRReader.
|
| 211 |
+
- **doc_id**: `int` the id of the passage. - **start_index**: `int` the start index of the span
|
| 212 |
+
(inclusive). - **end_index**: `int` the end index of the span (inclusive).
|
| 213 |
+
|
| 214 |
+
Examples:
|
| 215 |
+
|
| 216 |
+
```python
|
| 217 |
+
>>> from transformers import DPRReader, DPRReaderTokenizer
|
| 218 |
+
|
| 219 |
+
>>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
|
| 220 |
+
>>> model = DPRReader.from_pretrained("facebook/dpr-reader-single-nq-base")
|
| 221 |
+
>>> encoded_inputs = tokenizer(
|
| 222 |
+
... questions=["What is love ?"],
|
| 223 |
+
... titles=["Haddaway"],
|
| 224 |
+
... texts=["'What Is Love' is a song recorded by the artist Haddaway"],
|
| 225 |
+
... return_tensors="pt",
|
| 226 |
+
... )
|
| 227 |
+
>>> outputs = model(**encoded_inputs)
|
| 228 |
+
>>> predicted_spans = tokenizer.decode_best_spans(encoded_inputs, outputs)
|
| 229 |
+
>>> print(predicted_spans[0].text) # best span
|
| 230 |
+
a song
|
| 231 |
+
```"""
|
| 232 |
+
input_ids = reader_input["input_ids"]
|
| 233 |
+
start_logits, end_logits, relevance_logits = reader_output[:3]
|
| 234 |
+
n_passages = len(relevance_logits)
|
| 235 |
+
sorted_docs = sorted(range(n_passages), reverse=True, key=relevance_logits.__getitem__)
|
| 236 |
+
nbest_spans_predictions: list[DPRReaderOutput] = []
|
| 237 |
+
for doc_id in sorted_docs:
|
| 238 |
+
sequence_ids = list(input_ids[doc_id])
|
| 239 |
+
# assuming question & title information is at the beginning of the sequence
|
| 240 |
+
passage_offset = sequence_ids.index(self.sep_token_id, 2) + 1 # second sep id
|
| 241 |
+
if sequence_ids[-1] == self.pad_token_id:
|
| 242 |
+
sequence_len = sequence_ids.index(self.pad_token_id)
|
| 243 |
+
else:
|
| 244 |
+
sequence_len = len(sequence_ids)
|
| 245 |
+
|
| 246 |
+
best_spans = self._get_best_spans(
|
| 247 |
+
start_logits=start_logits[doc_id][passage_offset:sequence_len],
|
| 248 |
+
end_logits=end_logits[doc_id][passage_offset:sequence_len],
|
| 249 |
+
max_answer_length=max_answer_length,
|
| 250 |
+
top_spans=num_spans_per_passage,
|
| 251 |
+
)
|
| 252 |
+
for start_index, end_index in best_spans:
|
| 253 |
+
start_index += passage_offset
|
| 254 |
+
end_index += passage_offset
|
| 255 |
+
nbest_spans_predictions.append(
|
| 256 |
+
DPRSpanPrediction(
|
| 257 |
+
span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index],
|
| 258 |
+
relevance_score=relevance_logits[doc_id],
|
| 259 |
+
doc_id=doc_id,
|
| 260 |
+
start_index=start_index,
|
| 261 |
+
end_index=end_index,
|
| 262 |
+
text=self.decode(sequence_ids[start_index : end_index + 1]),
|
| 263 |
+
)
|
| 264 |
+
)
|
| 265 |
+
if len(nbest_spans_predictions) >= num_spans:
|
| 266 |
+
break
|
| 267 |
+
return nbest_spans_predictions[:num_spans]
|
| 268 |
+
|
| 269 |
+
def _get_best_spans(
|
| 270 |
+
self,
|
| 271 |
+
start_logits: list[int],
|
| 272 |
+
end_logits: list[int],
|
| 273 |
+
max_answer_length: int,
|
| 274 |
+
top_spans: int,
|
| 275 |
+
) -> list[DPRSpanPrediction]:
|
| 276 |
+
"""
|
| 277 |
+
Finds the best answer span for the extractive Q&A model for one passage. It returns the best span by descending
|
| 278 |
+
`span_score` order and keeping max `top_spans` spans. Spans longer that `max_answer_length` are ignored.
|
| 279 |
+
"""
|
| 280 |
+
scores = []
|
| 281 |
+
for start_index, start_score in enumerate(start_logits):
|
| 282 |
+
for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]):
|
| 283 |
+
scores.append(((start_index, start_index + answer_length), start_score + end_score))
|
| 284 |
+
scores = sorted(scores, key=lambda x: x[1], reverse=True)
|
| 285 |
+
chosen_span_intervals = []
|
| 286 |
+
for (start_index, end_index), score in scores:
|
| 287 |
+
if start_index > end_index:
|
| 288 |
+
raise ValueError(f"Wrong span indices: [{start_index}:{end_index}]")
|
| 289 |
+
length = end_index - start_index + 1
|
| 290 |
+
if length > max_answer_length:
|
| 291 |
+
raise ValueError(f"Span is too long: {length} > {max_answer_length}")
|
| 292 |
+
if any(
|
| 293 |
+
start_index <= prev_start_index <= prev_end_index <= end_index
|
| 294 |
+
or prev_start_index <= start_index <= end_index <= prev_end_index
|
| 295 |
+
for (prev_start_index, prev_end_index) in chosen_span_intervals
|
| 296 |
+
):
|
| 297 |
+
continue
|
| 298 |
+
chosen_span_intervals.append((start_index, end_index))
|
| 299 |
+
|
| 300 |
+
if len(chosen_span_intervals) == top_spans:
|
| 301 |
+
break
|
| 302 |
+
return chosen_span_intervals
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
@add_end_docstrings(CUSTOM_DPR_READER_DOCSTRING)
|
| 306 |
+
class DPRReaderTokenizer(CustomDPRReaderTokenizerMixin, BertTokenizer):
|
| 307 |
+
r"""
|
| 308 |
+
Construct a DPRReader tokenizer.
|
| 309 |
+
|
| 310 |
+
[`DPRReaderTokenizer`] is almost identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation
|
| 311 |
+
splitting and wordpiece. The difference is that is has three inputs strings: question, titles and texts that are
|
| 312 |
+
combined to be fed to the [`DPRReader`] model.
|
| 313 |
+
|
| 314 |
+
Refer to superclass [`BertTokenizer`] for usage examples and documentation concerning parameters.
|
| 315 |
+
"""
|
| 316 |
+
|
| 317 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 318 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
__all__ = ["DPRContextEncoderTokenizer", "DPRQuestionEncoderTokenizer", "DPRReaderOutput", "DPRReaderTokenizer"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dpr/tokenization_dpr_fast.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The HuggingFace Inc. team, The Hugging Face 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 DPR."""
|
| 16 |
+
|
| 17 |
+
import collections
|
| 18 |
+
from typing import Optional, Union
|
| 19 |
+
|
| 20 |
+
from ...tokenization_utils_base import BatchEncoding
|
| 21 |
+
from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging
|
| 22 |
+
from ..bert.tokenization_bert_fast import BertTokenizerFast
|
| 23 |
+
from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class DPRContextEncoderTokenizerFast(BertTokenizerFast):
|
| 32 |
+
r"""
|
| 33 |
+
Construct a "fast" DPRContextEncoder tokenizer (backed by HuggingFace's *tokenizers* library).
|
| 34 |
+
|
| 35 |
+
[`DPRContextEncoderTokenizerFast`] is identical to [`BertTokenizerFast`] and runs end-to-end tokenization:
|
| 36 |
+
punctuation splitting and wordpiece.
|
| 37 |
+
|
| 38 |
+
Refer to superclass [`BertTokenizerFast`] for usage examples and documentation concerning parameters.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 42 |
+
slow_tokenizer_class = DPRContextEncoderTokenizer
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class DPRQuestionEncoderTokenizerFast(BertTokenizerFast):
|
| 46 |
+
r"""
|
| 47 |
+
Constructs a "fast" DPRQuestionEncoder tokenizer (backed by HuggingFace's *tokenizers* library).
|
| 48 |
+
|
| 49 |
+
[`DPRQuestionEncoderTokenizerFast`] is identical to [`BertTokenizerFast`] and runs end-to-end tokenization:
|
| 50 |
+
punctuation splitting and wordpiece.
|
| 51 |
+
|
| 52 |
+
Refer to superclass [`BertTokenizerFast`] for usage examples and documentation concerning parameters.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 56 |
+
slow_tokenizer_class = DPRQuestionEncoderTokenizer
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
DPRSpanPrediction = collections.namedtuple(
|
| 60 |
+
"DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"]
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
DPRReaderOutput = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"])
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
CUSTOM_DPR_READER_DOCSTRING = r"""
|
| 67 |
+
Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.
|
| 68 |
+
It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),
|
| 69 |
+
using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`
|
| 70 |
+
with the format:
|
| 71 |
+
|
| 72 |
+
[CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
questions (`str` or `list[str]`):
|
| 76 |
+
The questions to be encoded. You can specify one question for many passages. In this case, the question
|
| 77 |
+
will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in
|
| 78 |
+
`titles` or `texts`.
|
| 79 |
+
titles (`str` or `list[str]`):
|
| 80 |
+
The passages titles to be encoded. This can be a string or a list of strings if there are several passages.
|
| 81 |
+
texts (`str` or `list[str]`):
|
| 82 |
+
The passages texts to be encoded. This can be a string or a list of strings if there are several passages.
|
| 83 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
|
| 84 |
+
Activates and controls padding. Accepts the following values:
|
| 85 |
+
|
| 86 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence
|
| 87 |
+
if provided).
|
| 88 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
| 89 |
+
acceptable input length for the model if that argument is not provided.
|
| 90 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
| 91 |
+
lengths).
|
| 92 |
+
truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
|
| 93 |
+
Activates and controls truncation. Accepts the following values:
|
| 94 |
+
|
| 95 |
+
- `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to
|
| 96 |
+
the maximum acceptable input length for the model if that argument is not provided. This will truncate
|
| 97 |
+
token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch
|
| 98 |
+
of pairs) is provided.
|
| 99 |
+
- `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
|
| 100 |
+
acceptable input length for the model if that argument is not provided. This will only truncate the first
|
| 101 |
+
sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
|
| 102 |
+
- `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
|
| 103 |
+
acceptable input length for the model if that argument is not provided. This will only truncate the
|
| 104 |
+
second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
|
| 105 |
+
- `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
|
| 106 |
+
greater than the model maximum admissible input size).
|
| 107 |
+
max_length (`int`, *optional*):
|
| 108 |
+
Controls the maximum length to use by one of the truncation/padding parameters.
|
| 109 |
+
|
| 110 |
+
If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
|
| 111 |
+
is required by one of the truncation/padding parameters. If the model has no specific maximum input
|
| 112 |
+
length (like XLNet) truncation/padding to a maximum length will be deactivated.
|
| 113 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 114 |
+
If set, will return tensors instead of list of python integers. Acceptable values are:
|
| 115 |
+
|
| 116 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 117 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 118 |
+
- `'np'`: Return Numpy `np.ndarray` objects.
|
| 119 |
+
return_attention_mask (`bool`, *optional*):
|
| 120 |
+
Whether or not to return the attention mask. If not set, will return the attention mask according to the
|
| 121 |
+
specific tokenizer's default, defined by the `return_outputs` attribute.
|
| 122 |
+
|
| 123 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 124 |
+
|
| 125 |
+
Return:
|
| 126 |
+
`dict[str, list[list[int]]]`: A dictionary with the following keys:
|
| 127 |
+
|
| 128 |
+
- `input_ids`: List of token ids to be fed to a model.
|
| 129 |
+
- `attention_mask`: List of indices specifying which tokens should be attended to by the model.
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@add_start_docstrings(CUSTOM_DPR_READER_DOCSTRING)
|
| 134 |
+
class CustomDPRReaderTokenizerMixin:
|
| 135 |
+
def __call__(
|
| 136 |
+
self,
|
| 137 |
+
questions,
|
| 138 |
+
titles: Optional[str] = None,
|
| 139 |
+
texts: Optional[str] = None,
|
| 140 |
+
padding: Union[bool, str] = False,
|
| 141 |
+
truncation: Union[bool, str] = False,
|
| 142 |
+
max_length: Optional[int] = None,
|
| 143 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 144 |
+
return_attention_mask: Optional[bool] = None,
|
| 145 |
+
**kwargs,
|
| 146 |
+
) -> BatchEncoding:
|
| 147 |
+
if titles is None and texts is None:
|
| 148 |
+
return super().__call__(
|
| 149 |
+
questions,
|
| 150 |
+
padding=padding,
|
| 151 |
+
truncation=truncation,
|
| 152 |
+
max_length=max_length,
|
| 153 |
+
return_tensors=return_tensors,
|
| 154 |
+
return_attention_mask=return_attention_mask,
|
| 155 |
+
**kwargs,
|
| 156 |
+
)
|
| 157 |
+
elif titles is None or texts is None:
|
| 158 |
+
text_pair = titles if texts is None else texts
|
| 159 |
+
return super().__call__(
|
| 160 |
+
questions,
|
| 161 |
+
text_pair,
|
| 162 |
+
padding=padding,
|
| 163 |
+
truncation=truncation,
|
| 164 |
+
max_length=max_length,
|
| 165 |
+
return_tensors=return_tensors,
|
| 166 |
+
return_attention_mask=return_attention_mask,
|
| 167 |
+
**kwargs,
|
| 168 |
+
)
|
| 169 |
+
titles = titles if not isinstance(titles, str) else [titles]
|
| 170 |
+
texts = texts if not isinstance(texts, str) else [texts]
|
| 171 |
+
n_passages = len(titles)
|
| 172 |
+
questions = questions if not isinstance(questions, str) else [questions] * n_passages
|
| 173 |
+
assert len(titles) == len(texts), (
|
| 174 |
+
f"There should be as many titles than texts but got {len(titles)} titles and {len(texts)} texts."
|
| 175 |
+
)
|
| 176 |
+
encoded_question_and_titles = super().__call__(questions, titles, padding=False, truncation=False)["input_ids"]
|
| 177 |
+
encoded_texts = super().__call__(texts, add_special_tokens=False, padding=False, truncation=False)["input_ids"]
|
| 178 |
+
encoded_inputs = {
|
| 179 |
+
"input_ids": [
|
| 180 |
+
(encoded_question_and_title + encoded_text)[:max_length]
|
| 181 |
+
if max_length is not None and truncation
|
| 182 |
+
else encoded_question_and_title + encoded_text
|
| 183 |
+
for encoded_question_and_title, encoded_text in zip(encoded_question_and_titles, encoded_texts)
|
| 184 |
+
]
|
| 185 |
+
}
|
| 186 |
+
if return_attention_mask is not False:
|
| 187 |
+
attention_mask = []
|
| 188 |
+
for input_ids in encoded_inputs["input_ids"]:
|
| 189 |
+
attention_mask.append([int(input_id != self.pad_token_id) for input_id in input_ids])
|
| 190 |
+
encoded_inputs["attention_mask"] = attention_mask
|
| 191 |
+
return self.pad(encoded_inputs, padding=padding, max_length=max_length, return_tensors=return_tensors)
|
| 192 |
+
|
| 193 |
+
def decode_best_spans(
|
| 194 |
+
self,
|
| 195 |
+
reader_input: BatchEncoding,
|
| 196 |
+
reader_output: DPRReaderOutput,
|
| 197 |
+
num_spans: int = 16,
|
| 198 |
+
max_answer_length: int = 64,
|
| 199 |
+
num_spans_per_passage: int = 4,
|
| 200 |
+
) -> list[DPRSpanPrediction]:
|
| 201 |
+
"""
|
| 202 |
+
Get the span predictions for the extractive Q&A model.
|
| 203 |
+
|
| 204 |
+
Returns: *List* of *DPRReaderOutput* sorted by descending *(relevance_score, span_score)*. Each
|
| 205 |
+
*DPRReaderOutput* is a *Tuple* with:
|
| 206 |
+
|
| 207 |
+
- **span_score**: `float` that corresponds to the score given by the reader for this span compared to other
|
| 208 |
+
spans in the same passage. It corresponds to the sum of the start and end logits of the span.
|
| 209 |
+
- **relevance_score**: `float` that corresponds to the score of the each passage to answer the question,
|
| 210 |
+
compared to all the other passages. It corresponds to the output of the QA classifier of the DPRReader.
|
| 211 |
+
- **doc_id**: `int` the id of the passage. - ***start_index**: `int` the start index of the span
|
| 212 |
+
(inclusive). - **end_index**: `int` the end index of the span (inclusive).
|
| 213 |
+
|
| 214 |
+
Examples:
|
| 215 |
+
|
| 216 |
+
```python
|
| 217 |
+
>>> from transformers import DPRReader, DPRReaderTokenizer
|
| 218 |
+
|
| 219 |
+
>>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
|
| 220 |
+
>>> model = DPRReader.from_pretrained("facebook/dpr-reader-single-nq-base")
|
| 221 |
+
>>> encoded_inputs = tokenizer(
|
| 222 |
+
... questions=["What is love ?"],
|
| 223 |
+
... titles=["Haddaway"],
|
| 224 |
+
... texts=["'What Is Love' is a song recorded by the artist Haddaway"],
|
| 225 |
+
... return_tensors="pt",
|
| 226 |
+
... )
|
| 227 |
+
>>> outputs = model(**encoded_inputs)
|
| 228 |
+
>>> predicted_spans = tokenizer.decode_best_spans(encoded_inputs, outputs)
|
| 229 |
+
>>> print(predicted_spans[0].text) # best span
|
| 230 |
+
a song
|
| 231 |
+
```"""
|
| 232 |
+
input_ids = reader_input["input_ids"]
|
| 233 |
+
start_logits, end_logits, relevance_logits = reader_output[:3]
|
| 234 |
+
n_passages = len(relevance_logits)
|
| 235 |
+
sorted_docs = sorted(range(n_passages), reverse=True, key=relevance_logits.__getitem__)
|
| 236 |
+
nbest_spans_predictions: list[DPRReaderOutput] = []
|
| 237 |
+
for doc_id in sorted_docs:
|
| 238 |
+
sequence_ids = list(input_ids[doc_id])
|
| 239 |
+
# assuming question & title information is at the beginning of the sequence
|
| 240 |
+
passage_offset = sequence_ids.index(self.sep_token_id, 2) + 1 # second sep id
|
| 241 |
+
if sequence_ids[-1] == self.pad_token_id:
|
| 242 |
+
sequence_len = sequence_ids.index(self.pad_token_id)
|
| 243 |
+
else:
|
| 244 |
+
sequence_len = len(sequence_ids)
|
| 245 |
+
|
| 246 |
+
best_spans = self._get_best_spans(
|
| 247 |
+
start_logits=start_logits[doc_id][passage_offset:sequence_len],
|
| 248 |
+
end_logits=end_logits[doc_id][passage_offset:sequence_len],
|
| 249 |
+
max_answer_length=max_answer_length,
|
| 250 |
+
top_spans=num_spans_per_passage,
|
| 251 |
+
)
|
| 252 |
+
for start_index, end_index in best_spans:
|
| 253 |
+
start_index += passage_offset
|
| 254 |
+
end_index += passage_offset
|
| 255 |
+
nbest_spans_predictions.append(
|
| 256 |
+
DPRSpanPrediction(
|
| 257 |
+
span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index],
|
| 258 |
+
relevance_score=relevance_logits[doc_id],
|
| 259 |
+
doc_id=doc_id,
|
| 260 |
+
start_index=start_index,
|
| 261 |
+
end_index=end_index,
|
| 262 |
+
text=self.decode(sequence_ids[start_index : end_index + 1]),
|
| 263 |
+
)
|
| 264 |
+
)
|
| 265 |
+
if len(nbest_spans_predictions) >= num_spans:
|
| 266 |
+
break
|
| 267 |
+
return nbest_spans_predictions[:num_spans]
|
| 268 |
+
|
| 269 |
+
def _get_best_spans(
|
| 270 |
+
self,
|
| 271 |
+
start_logits: list[int],
|
| 272 |
+
end_logits: list[int],
|
| 273 |
+
max_answer_length: int,
|
| 274 |
+
top_spans: int,
|
| 275 |
+
) -> list[DPRSpanPrediction]:
|
| 276 |
+
"""
|
| 277 |
+
Finds the best answer span for the extractive Q&A model for one passage. It returns the best span by descending
|
| 278 |
+
`span_score` order and keeping max `top_spans` spans. Spans longer that `max_answer_length` are ignored.
|
| 279 |
+
"""
|
| 280 |
+
scores = []
|
| 281 |
+
for start_index, start_score in enumerate(start_logits):
|
| 282 |
+
for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]):
|
| 283 |
+
scores.append(((start_index, start_index + answer_length), start_score + end_score))
|
| 284 |
+
scores = sorted(scores, key=lambda x: x[1], reverse=True)
|
| 285 |
+
chosen_span_intervals = []
|
| 286 |
+
for (start_index, end_index), score in scores:
|
| 287 |
+
assert start_index <= end_index, f"Wrong span indices: [{start_index}:{end_index}]"
|
| 288 |
+
length = end_index - start_index + 1
|
| 289 |
+
assert length <= max_answer_length, f"Span is too long: {length} > {max_answer_length}"
|
| 290 |
+
if any(
|
| 291 |
+
start_index <= prev_start_index <= prev_end_index <= end_index
|
| 292 |
+
or prev_start_index <= start_index <= end_index <= prev_end_index
|
| 293 |
+
for (prev_start_index, prev_end_index) in chosen_span_intervals
|
| 294 |
+
):
|
| 295 |
+
continue
|
| 296 |
+
chosen_span_intervals.append((start_index, end_index))
|
| 297 |
+
|
| 298 |
+
if len(chosen_span_intervals) == top_spans:
|
| 299 |
+
break
|
| 300 |
+
return chosen_span_intervals
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
@add_end_docstrings(CUSTOM_DPR_READER_DOCSTRING)
|
| 304 |
+
class DPRReaderTokenizerFast(CustomDPRReaderTokenizerMixin, BertTokenizerFast):
|
| 305 |
+
r"""
|
| 306 |
+
Constructs a "fast" DPRReader tokenizer (backed by HuggingFace's *tokenizers* library).
|
| 307 |
+
|
| 308 |
+
[`DPRReaderTokenizerFast`] is almost identical to [`BertTokenizerFast`] and runs end-to-end tokenization:
|
| 309 |
+
punctuation splitting and wordpiece. The difference is that is has three inputs strings: question, titles and texts
|
| 310 |
+
that are combined to be fed to the [`DPRReader`] model.
|
| 311 |
+
|
| 312 |
+
Refer to superclass [`BertTokenizerFast`] for usage examples and documentation concerning parameters.
|
| 313 |
+
|
| 314 |
+
"""
|
| 315 |
+
|
| 316 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 317 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 318 |
+
slow_tokenizer_class = DPRReaderTokenizer
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
__all__ = ["DPRContextEncoderTokenizerFast", "DPRQuestionEncoderTokenizerFast", "DPRReaderTokenizerFast"]
|
tasks/tasksmith-5cbfd9f64dbc/environment/source/src/transformers/models/dpt/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_dpt import *
|
| 22 |
+
from .feature_extraction_dpt import *
|
| 23 |
+
from .image_processing_dpt import *
|
| 24 |
+
from .image_processing_dpt_fast import *
|
| 25 |
+
from .modeling_dpt import *
|
| 26 |
+
else:
|
| 27 |
+
import sys
|
| 28 |
+
|
| 29 |
+
_file = globals()["__file__"]
|
| 30 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|