Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- lib/python3.11/site-packages/transformers/models/modernvbert/__pycache__/configuration_modernvbert.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/modernvbert/__pycache__/modeling_modernvbert.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/modernvbert/__pycache__/modular_modernvbert.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/modernvbert/modeling_modernvbert.py +696 -0
- lib/python3.11/site-packages/transformers/models/modernvbert/modular_modernvbert.py +626 -0
- lib/python3.11/site-packages/transformers/models/moonshine/__init__.py +27 -0
- lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/__init__.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/configuration_moonshine.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/modeling_moonshine.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/modular_moonshine.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/moonshine/configuration_moonshine.py +116 -0
- lib/python3.11/site-packages/transformers/models/moonshine/modeling_moonshine.py +953 -0
- lib/python3.11/site-packages/transformers/models/moonshine/modular_moonshine.py +795 -0
- lib/python3.11/site-packages/transformers/models/moonshine_streaming/__init__.py +28 -0
- lib/python3.11/site-packages/transformers/models/moonshine_streaming/__pycache__/__init__.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/moonshine_streaming/__pycache__/configuration_moonshine_streaming.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/moonshine_streaming/__pycache__/modeling_moonshine_streaming.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/moonshine_streaming/__pycache__/modular_moonshine_streaming.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/moonshine_streaming/__pycache__/processing_moonshine_streaming.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/moonshine_streaming/configuration_moonshine_streaming.py +142 -0
- lib/python3.11/site-packages/transformers/models/moonshine_streaming/modeling_moonshine_streaming.py +1121 -0
- lib/python3.11/site-packages/transformers/models/moonshine_streaming/modular_moonshine_streaming.py +419 -0
- lib/python3.11/site-packages/transformers/models/moonshine_streaming/processing_moonshine_streaming.py +114 -0
- lib/python3.11/site-packages/transformers/models/moshi/__init__.py +27 -0
- lib/python3.11/site-packages/transformers/models/moshi/__pycache__/__init__.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/moshi/__pycache__/configuration_moshi.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/moshi/configuration_moshi.py +220 -0
- lib/python3.11/site-packages/transformers/models/moshi/modeling_moshi.py +0 -0
- lib/python3.11/site-packages/transformers/models/mpnet/__init__.py +28 -0
- lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/__init__.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/configuration_mpnet.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/modeling_mpnet.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/tokenization_mpnet.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/mpnet/configuration_mpnet.py +65 -0
- lib/python3.11/site-packages/transformers/models/mpnet/modeling_mpnet.py +895 -0
- lib/python3.11/site-packages/transformers/models/mpnet/tokenization_mpnet.py +195 -0
- lib/python3.11/site-packages/transformers/models/mpt/__init__.py +27 -0
- lib/python3.11/site-packages/transformers/models/mpt/__pycache__/__init__.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/mpt/__pycache__/configuration_mpt.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/mpt/__pycache__/modeling_mpt.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/mpt/configuration_mpt.py +150 -0
- lib/python3.11/site-packages/transformers/models/mpt/modeling_mpt.py +761 -0
- lib/python3.11/site-packages/transformers/models/mra/__init__.py +27 -0
- lib/python3.11/site-packages/transformers/models/mra/__pycache__/__init__.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/mra/__pycache__/configuration_mra.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/mra/__pycache__/modeling_mra.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/transformers/models/mra/configuration_mra.py +76 -0
- lib/python3.11/site-packages/transformers/models/mra/modeling_mra.py +1338 -0
- lib/python3.11/site-packages/transformers/models/mt5/__init__.py +28 -0
- lib/python3.11/site-packages/transformers/models/mt5/__pycache__/__init__.cpython-311.pyc +0 -0
lib/python3.11/site-packages/transformers/models/modernvbert/__pycache__/configuration_modernvbert.cpython-311.pyc
ADDED
|
Binary file (3.82 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/modernvbert/__pycache__/modeling_modernvbert.cpython-311.pyc
ADDED
|
Binary file (35.5 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/modernvbert/__pycache__/modular_modernvbert.cpython-311.pyc
ADDED
|
Binary file (30.4 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/modernvbert/modeling_modernvbert.py
ADDED
|
@@ -0,0 +1,696 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/modernvbert/modular_modernvbert.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_modernvbert.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2026 Illuin Technology and contributors, and The HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
import math
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
import torch.nn as nn
|
| 26 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 27 |
+
|
| 28 |
+
from ... import initialization as init
|
| 29 |
+
from ...activations import ACT2FN
|
| 30 |
+
from ...modeling_outputs import (
|
| 31 |
+
BaseModelOutput,
|
| 32 |
+
BaseModelOutputWithPooling,
|
| 33 |
+
MaskedLMOutput,
|
| 34 |
+
SequenceClassifierOutput,
|
| 35 |
+
TokenClassifierOutput,
|
| 36 |
+
)
|
| 37 |
+
from ...modeling_utils import PreTrainedModel
|
| 38 |
+
from ...processing_utils import Unpack
|
| 39 |
+
from ...utils import TransformersKwargs, auto_docstring, torch_compilable_check
|
| 40 |
+
from ...utils.generic import can_return_tuple
|
| 41 |
+
from ..auto import AutoModel
|
| 42 |
+
from .configuration_modernvbert import ModernVBertConfig
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@dataclass
|
| 46 |
+
class ModernVBertBaseModelOutput(BaseModelOutput):
|
| 47 |
+
"""
|
| 48 |
+
Base class for ModernVBERT model's outputs.
|
| 49 |
+
Args:
|
| 50 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 51 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 52 |
+
If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
|
| 53 |
+
hidden_size)` is output.
|
| 54 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 55 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 56 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 57 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 58 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 59 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 60 |
+
sequence_length)`.
|
| 61 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 62 |
+
heads.
|
| 63 |
+
image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
|
| 64 |
+
Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
|
| 65 |
+
sequence_length, hidden_size)`.
|
| 66 |
+
image_hidden_states of the model produced by the vision encoder
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
last_hidden_state: torch.FloatTensor = None
|
| 70 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 71 |
+
attentions: tuple[torch.FloatTensor] | None = None
|
| 72 |
+
image_hidden_states: tuple[torch.FloatTensor] | None = None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@dataclass
|
| 76 |
+
class ModernVBertMaskedLMOutput(MaskedLMOutput):
|
| 77 |
+
"""
|
| 78 |
+
Base class for ModernVBERT model's outputs with masked language modeling loss.
|
| 79 |
+
Args:
|
| 80 |
+
loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided):
|
| 81 |
+
Masked language modeling (MLM) loss.
|
| 82 |
+
logits (`torch.FloatTensor`):
|
| 83 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 84 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 85 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 86 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 87 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 88 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 89 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 90 |
+
sequence_length)`.
|
| 91 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 92 |
+
heads.
|
| 93 |
+
image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
|
| 94 |
+
Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
|
| 95 |
+
sequence_length, hidden_size)`.
|
| 96 |
+
image_hidden_states of the model produced by the vision encoder
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
loss: torch.FloatTensor | None = None
|
| 100 |
+
logits: torch.FloatTensor = None
|
| 101 |
+
hidden_states: tuple[torch.FloatTensor, ...] | None = None
|
| 102 |
+
attentions: tuple[torch.FloatTensor, ...] | None = None
|
| 103 |
+
image_hidden_states: torch.FloatTensor | None = None
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class ModernVBertConnector(nn.Module):
|
| 107 |
+
"""
|
| 108 |
+
Connector module for ModernVBERT. It performs a pixel shuffle operation followed by a linear projection to match the text model's hidden size.
|
| 109 |
+
Based on https://pytorch.org/docs/stable/generated/torch.nn.PixelShuffle.html
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def __init__(self, config):
|
| 113 |
+
super().__init__()
|
| 114 |
+
self.pixel_shuffle_factor = config.pixel_shuffle_factor
|
| 115 |
+
self.modality_projection = nn.Linear(
|
| 116 |
+
config.vision_config.hidden_size * (config.pixel_shuffle_factor**2),
|
| 117 |
+
config.text_config.hidden_size,
|
| 118 |
+
bias=False,
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
def pixel_shuffle(self, image_hidden_states, pixel_shuffle_factor):
|
| 122 |
+
batch_size, seq_length, embed_dim = image_hidden_states.size()
|
| 123 |
+
height = width = int(seq_length**0.5)
|
| 124 |
+
image_hidden_states = image_hidden_states.view(batch_size, height, width, embed_dim)
|
| 125 |
+
image_hidden_states = image_hidden_states.view(
|
| 126 |
+
batch_size, height, int(width / pixel_shuffle_factor), embed_dim * pixel_shuffle_factor
|
| 127 |
+
)
|
| 128 |
+
image_hidden_states = image_hidden_states.permute(0, 2, 1, 3)
|
| 129 |
+
image_hidden_states = image_hidden_states.reshape(
|
| 130 |
+
batch_size,
|
| 131 |
+
int(width / pixel_shuffle_factor),
|
| 132 |
+
int(height / pixel_shuffle_factor),
|
| 133 |
+
embed_dim * (pixel_shuffle_factor**2),
|
| 134 |
+
)
|
| 135 |
+
image_hidden_states = image_hidden_states.permute(0, 2, 1, 3)
|
| 136 |
+
return image_hidden_states.reshape(
|
| 137 |
+
batch_size, int(seq_length / (pixel_shuffle_factor**2)), embed_dim * (pixel_shuffle_factor**2)
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
def forward(self, image_hidden_states):
|
| 141 |
+
image_hidden_states = self.pixel_shuffle(image_hidden_states, self.pixel_shuffle_factor)
|
| 142 |
+
return self.modality_projection(image_hidden_states)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@auto_docstring
|
| 146 |
+
class ModernVBertPreTrainedModel(PreTrainedModel):
|
| 147 |
+
config: ModernVBertConfig
|
| 148 |
+
base_model_prefix = "model"
|
| 149 |
+
input_modalities = ("image", "text")
|
| 150 |
+
supports_gradient_checkpointing = True
|
| 151 |
+
_no_split_modules = []
|
| 152 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 153 |
+
_supports_flash_attn = True
|
| 154 |
+
_supports_sdpa = True
|
| 155 |
+
_supports_flex_attn = True
|
| 156 |
+
_supports_attention_backend = True
|
| 157 |
+
config_class = ModernVBertConfig
|
| 158 |
+
|
| 159 |
+
@torch.no_grad()
|
| 160 |
+
def _init_weights(self, module):
|
| 161 |
+
super()._init_weights(module)
|
| 162 |
+
|
| 163 |
+
def init_weight(module: nn.Module, std: float):
|
| 164 |
+
cutoff_factor = getattr(self.config, "initializer_cutoff_factor", 2.0)
|
| 165 |
+
init.trunc_normal_(
|
| 166 |
+
module.weight,
|
| 167 |
+
mean=0.0,
|
| 168 |
+
std=std,
|
| 169 |
+
a=-cutoff_factor * std,
|
| 170 |
+
b=cutoff_factor * std,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 174 |
+
if module.bias is not None:
|
| 175 |
+
init.zeros_(module.bias)
|
| 176 |
+
|
| 177 |
+
if isinstance(module, ModernVBertConnector):
|
| 178 |
+
out_std = self.config.initializer_range / math.sqrt(2.0 * self.config.text_config.num_hidden_layers)
|
| 179 |
+
init_weight(module.modality_projection, out_std)
|
| 180 |
+
elif isinstance(module, ModernVBertForMaskedLM):
|
| 181 |
+
out_std = self.config.initializer_range / math.sqrt(2.0 * self.config.text_config.num_hidden_layers)
|
| 182 |
+
init_weight(module.lm_head, out_std)
|
| 183 |
+
elif isinstance(
|
| 184 |
+
module,
|
| 185 |
+
(
|
| 186 |
+
ModernVBertForSequenceClassification,
|
| 187 |
+
ModernVBertForTokenClassification,
|
| 188 |
+
),
|
| 189 |
+
):
|
| 190 |
+
final_out_std = self.config.initializer_range / math.sqrt(self.config.text_config.hidden_size)
|
| 191 |
+
init_weight(module.classifier, final_out_std)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@auto_docstring(
|
| 195 |
+
custom_intro="""
|
| 196 |
+
ModernVBertModel is a model that combines a vision encoder (SigLIP) and a text encoder (ModernBert).
|
| 197 |
+
|
| 198 |
+
ModernVBert is the base model of the visual retriver ColModernVBert, and was introduced in the following paper:
|
| 199 |
+
[*ModernVBERT: Towards Smaller Visual Document Retrievers*](https://arxiv.org/abs/2510.01149).
|
| 200 |
+
"""
|
| 201 |
+
)
|
| 202 |
+
class ModernVBertModel(ModernVBertPreTrainedModel):
|
| 203 |
+
"""
|
| 204 |
+
A subclass of Idefics3Model. We do *not* remove or block the call to inputs_merger
|
| 205 |
+
in forward. Instead, we override inputs_merger here with custom logic.
|
| 206 |
+
"""
|
| 207 |
+
|
| 208 |
+
def __init__(self, config: ModernVBertConfig):
|
| 209 |
+
super().__init__(config)
|
| 210 |
+
self.padding_idx = self.config.text_config.pad_token_id
|
| 211 |
+
self.vocab_size = self.config.text_config.vocab_size
|
| 212 |
+
self.vision_model = AutoModel.from_config(config.vision_config)
|
| 213 |
+
|
| 214 |
+
# init components
|
| 215 |
+
self.connector = ModernVBertConnector(config)
|
| 216 |
+
self.text_model = AutoModel.from_config(config.text_config)
|
| 217 |
+
|
| 218 |
+
self.image_seq_len = int(
|
| 219 |
+
((config.vision_config.image_size // config.vision_config.patch_size) ** 2)
|
| 220 |
+
/ (config.pixel_shuffle_factor**2)
|
| 221 |
+
)
|
| 222 |
+
self.image_token_id = self.config.image_token_id
|
| 223 |
+
|
| 224 |
+
self.post_init()
|
| 225 |
+
|
| 226 |
+
def get_input_embeddings(self):
|
| 227 |
+
return self.text_model.get_input_embeddings()
|
| 228 |
+
|
| 229 |
+
def set_input_embeddings(self, value):
|
| 230 |
+
self.text_model.set_input_embeddings(value)
|
| 231 |
+
|
| 232 |
+
def inputs_merger(
|
| 233 |
+
self, input_ids: torch.LongTensor, inputs_embeds: torch.Tensor, image_hidden_states: torch.Tensor
|
| 234 |
+
):
|
| 235 |
+
"""
|
| 236 |
+
This method aims at merging the token embeddings with the image hidden states into one single sequence of vectors that are fed to the transformer LM.
|
| 237 |
+
The merging happens as follows:
|
| 238 |
+
- The text token sequence is: `tok_1 tok_2 tok_3 <fake_token_around_image> <image> <image> ... <image> <fake_token_around_image> tok_4`.
|
| 239 |
+
- We get the image hidden states for the image through the vision encoder and that hidden state, after a pixel shuffle operation, is then projected into the text embedding space.
|
| 240 |
+
We thus have a sequence of image hidden states of size (1, image_seq_len, hidden_dim), where 1 is for batch_size of 1 image and hidden_dim is the hidden_dim of the LM transformer.
|
| 241 |
+
- The merging happens so that we obtain the following sequence: `vector_tok_1 vector_tok_2 vector_tok_3 vector_fake_tok_around_image {sequence of image_seq_len image hidden states} vector_fake_toke_around_image vector_tok_4`. That sequence is fed to the LM.
|
| 242 |
+
- To fit the format of that sequence, `input_ids`, `inputs_embeds`, `attention_mask` are all 3 adapted to insert the image hidden states.
|
| 243 |
+
"""
|
| 244 |
+
_, patch_size, _ = image_hidden_states.shape
|
| 245 |
+
|
| 246 |
+
if input_ids is None:
|
| 247 |
+
image_mask = inputs_embeds == self.get_input_embeddings()(
|
| 248 |
+
torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
|
| 249 |
+
)
|
| 250 |
+
image_mask = image_mask[..., 0] # slice off the hidden dim
|
| 251 |
+
else:
|
| 252 |
+
image_mask = input_ids == self.config.image_token_id
|
| 253 |
+
|
| 254 |
+
num_image_tokens = image_mask.sum(dim=1)
|
| 255 |
+
torch_compilable_check(
|
| 256 |
+
torch.all(num_image_tokens % patch_size == 0),
|
| 257 |
+
"At least one sample has <image> tokens not divisible by patch_size.",
|
| 258 |
+
)
|
| 259 |
+
blocks_per_sample = num_image_tokens // patch_size
|
| 260 |
+
|
| 261 |
+
offsets = torch.nn.functional.pad(blocks_per_sample.cumsum(dim=0), (1, 0), value=0)
|
| 262 |
+
block_offset = offsets[:-1]
|
| 263 |
+
row_cum = image_mask.cumsum(dim=-1)
|
| 264 |
+
chunk_idx = (row_cum - 1) // patch_size
|
| 265 |
+
local_idx = (row_cum - 1) % patch_size
|
| 266 |
+
block_idx = block_offset.unsqueeze(1) + chunk_idx
|
| 267 |
+
|
| 268 |
+
image_embeds = torch.zeros_like(inputs_embeds)
|
| 269 |
+
image_embeds[image_mask] = image_hidden_states[block_idx[image_mask], local_idx[image_mask], :]
|
| 270 |
+
|
| 271 |
+
merged_embeds = torch.where(image_mask.unsqueeze(-1), image_embeds, inputs_embeds)
|
| 272 |
+
return merged_embeds
|
| 273 |
+
|
| 274 |
+
@can_return_tuple
|
| 275 |
+
@auto_docstring(
|
| 276 |
+
custom_intro="Encodes images into continuous embeddings that can be forwarded to the language model."
|
| 277 |
+
)
|
| 278 |
+
def get_image_features(
|
| 279 |
+
self,
|
| 280 |
+
pixel_values: torch.FloatTensor,
|
| 281 |
+
pixel_attention_mask: torch.LongTensor | None = None,
|
| 282 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 283 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 284 |
+
r"""
|
| 285 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 286 |
+
The tensors corresponding to the input images.
|
| 287 |
+
pixel_attention_mask (`torch.LongTensor`, *optional*):
|
| 288 |
+
The attention mask indicating padded regions in the image.
|
| 289 |
+
"""
|
| 290 |
+
batch_size, num_images, num_channels, height, width = pixel_values.shape
|
| 291 |
+
pixel_values = pixel_values.to(dtype=self.dtype) # fp16 compatibility
|
| 292 |
+
pixel_values = pixel_values.view(batch_size * num_images, *pixel_values.shape[2:])
|
| 293 |
+
|
| 294 |
+
# Remove padding images - padding images are full 0.
|
| 295 |
+
nb_values_per_image = pixel_values.shape[1:].numel()
|
| 296 |
+
real_images_inds = (pixel_values == 0.0).sum(dim=(-1, -2, -3)) != nb_values_per_image
|
| 297 |
+
|
| 298 |
+
# If no images, leave one empty image.
|
| 299 |
+
real_images_inds[0] |= ~torch.any(real_images_inds)
|
| 300 |
+
|
| 301 |
+
pixel_values = pixel_values[real_images_inds].contiguous()
|
| 302 |
+
# Handle the vision attention mask
|
| 303 |
+
if pixel_attention_mask is None:
|
| 304 |
+
pixel_attention_mask = torch.ones(
|
| 305 |
+
size=[pixel_values.shape[i] for i in (0, 2, 3)],
|
| 306 |
+
dtype=torch.bool,
|
| 307 |
+
device=pixel_values.device,
|
| 308 |
+
)
|
| 309 |
+
else:
|
| 310 |
+
# Remove padding images from the mask
|
| 311 |
+
pixel_attention_mask = pixel_attention_mask.view(batch_size * num_images, *pixel_attention_mask.shape[2:])
|
| 312 |
+
pixel_attention_mask = pixel_attention_mask[real_images_inds].contiguous()
|
| 313 |
+
patch_size = self.config.vision_config.patch_size
|
| 314 |
+
patches_subgrid = pixel_attention_mask.unfold(dimension=1, size=patch_size, step=patch_size)
|
| 315 |
+
patches_subgrid = patches_subgrid.unfold(dimension=2, size=patch_size, step=patch_size)
|
| 316 |
+
patch_attention_mask = (patches_subgrid.sum(dim=(-1, -2)) > 0).bool()
|
| 317 |
+
|
| 318 |
+
# Get sequence from the vision encoder
|
| 319 |
+
image_outputs = self.vision_model(
|
| 320 |
+
pixel_values=pixel_values, patch_attention_mask=patch_attention_mask, return_dict=True, **kwargs
|
| 321 |
+
)
|
| 322 |
+
image_hidden_states = image_outputs.last_hidden_state
|
| 323 |
+
|
| 324 |
+
# Modality projection & resampling
|
| 325 |
+
image_features = self.connector(image_hidden_states)
|
| 326 |
+
image_outputs.pooler_output = image_features
|
| 327 |
+
|
| 328 |
+
return image_outputs
|
| 329 |
+
|
| 330 |
+
@can_return_tuple
|
| 331 |
+
@auto_docstring(
|
| 332 |
+
custom_intro="""
|
| 333 |
+
Inputs fed to the model can have an arbitrary number of images. To account for this, pixel_values fed to
|
| 334 |
+
the model have image padding -> (batch_size, max_num_images, 3, max_heights, max_widths) where
|
| 335 |
+
max_num_images is the maximum number of images among the batch_size samples in the batch.
|
| 336 |
+
Padding images are not needed beyond padding the pixel_values at the entrance of the model.
|
| 337 |
+
For efficiency, we only pass through the vision_model's forward the real images by
|
| 338 |
+
discarding the padding images i.e. pixel_values of size (image_batch_size, 3, height, width) where
|
| 339 |
+
image_batch_size would be 7 when num_images_per_sample=[1, 3, 1, 2] and max_num_images would be 3.
|
| 340 |
+
""",
|
| 341 |
+
checkpoint="ModernVBERT/modernvbert",
|
| 342 |
+
)
|
| 343 |
+
def forward(
|
| 344 |
+
self,
|
| 345 |
+
input_ids: torch.LongTensor = None,
|
| 346 |
+
attention_mask: torch.Tensor | None = None,
|
| 347 |
+
position_ids: torch.LongTensor | None = None,
|
| 348 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 349 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 350 |
+
pixel_attention_mask: torch.BoolTensor | None = None,
|
| 351 |
+
image_hidden_states: torch.FloatTensor | None = None,
|
| 352 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 353 |
+
) -> tuple | ModernVBertBaseModelOutput:
|
| 354 |
+
r"""
|
| 355 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 356 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 357 |
+
image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 358 |
+
The hidden states of the image encoder after modality projection.
|
| 359 |
+
"""
|
| 360 |
+
|
| 361 |
+
if inputs_embeds is None:
|
| 362 |
+
inputs_embeds = self.text_model.get_input_embeddings()(input_ids).to(input_ids.device)
|
| 363 |
+
|
| 364 |
+
# Images processing
|
| 365 |
+
if pixel_values is not None:
|
| 366 |
+
image_hidden_states = self.get_image_features(
|
| 367 |
+
pixel_values=pixel_values, pixel_attention_mask=pixel_attention_mask
|
| 368 |
+
).pooler_output
|
| 369 |
+
|
| 370 |
+
# Merge image and text embeddings
|
| 371 |
+
if image_hidden_states is not None:
|
| 372 |
+
image_hidden_states = image_hidden_states.to(dtype=inputs_embeds.dtype, device=inputs_embeds.device)
|
| 373 |
+
inputs_embeds = self.inputs_merger(
|
| 374 |
+
input_ids=input_ids, inputs_embeds=inputs_embeds, image_hidden_states=image_hidden_states
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
# Language model pass
|
| 378 |
+
outputs = self.text_model(
|
| 379 |
+
inputs_embeds=inputs_embeds,
|
| 380 |
+
attention_mask=attention_mask,
|
| 381 |
+
position_ids=position_ids,
|
| 382 |
+
**kwargs,
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
return ModernVBertBaseModelOutput(
|
| 386 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 387 |
+
hidden_states=outputs.hidden_states,
|
| 388 |
+
attentions=outputs.attentions,
|
| 389 |
+
image_hidden_states=image_hidden_states,
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
class ModernVBertPredictionHead(nn.Module):
|
| 394 |
+
def __init__(self, config: ModernVBertConfig):
|
| 395 |
+
super().__init__()
|
| 396 |
+
self.config = config
|
| 397 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size, config.classifier_bias)
|
| 398 |
+
self.act = ACT2FN[config.classifier_activation]
|
| 399 |
+
self.norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=config.norm_bias)
|
| 400 |
+
|
| 401 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 402 |
+
return self.norm(self.act(self.dense(hidden_states)))
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
@auto_docstring
|
| 406 |
+
class ModernVBertForMaskedLM(ModernVBertPreTrainedModel):
|
| 407 |
+
_tied_weights_keys = {"lm_head.weight": "model.text_model.embeddings.tok_embeddings.weight"}
|
| 408 |
+
|
| 409 |
+
def __init__(self, config: ModernVBertConfig):
|
| 410 |
+
super().__init__(config)
|
| 411 |
+
|
| 412 |
+
self.vocab_size = config.text_config.vocab_size
|
| 413 |
+
|
| 414 |
+
self.model = ModernVBertModel(config)
|
| 415 |
+
self.projection_head = ModernVBertPredictionHead(config.text_config)
|
| 416 |
+
self.lm_head = nn.Linear(config.text_config.hidden_size, self.vocab_size, bias=config.text_config.decoder_bias)
|
| 417 |
+
|
| 418 |
+
# Initialize weights and apply final processing
|
| 419 |
+
self.post_init()
|
| 420 |
+
|
| 421 |
+
def get_output_embeddings(self):
|
| 422 |
+
return self.lm_head
|
| 423 |
+
|
| 424 |
+
def set_output_embeddings(self, new_embeddings):
|
| 425 |
+
self.lm_head = new_embeddings
|
| 426 |
+
|
| 427 |
+
@can_return_tuple
|
| 428 |
+
@auto_docstring(
|
| 429 |
+
custom_intro="""
|
| 430 |
+
Inputs fed to the model can have an arbitrary number of images. To account for this, pixel_values fed to
|
| 431 |
+
the model have image padding -> (batch_size, max_num_images, 3, max_heights, max_widths) where
|
| 432 |
+
max_num_images is the maximum number of images among the batch_size samples in the batch.
|
| 433 |
+
Padding images are not needed beyond padding the pixel_values at the entrance of the model.
|
| 434 |
+
For efficiency, we only pass through the vision_model's forward the real images by
|
| 435 |
+
discarding the padding images i.e. pixel_values of size (image_batch_size, 3, height, width) where
|
| 436 |
+
image_batch_size would be 7 when num_images_per_sample=[1, 3, 1, 2] and max_num_images would be 3.
|
| 437 |
+
""",
|
| 438 |
+
checkpoint="ModernVBERT/modernvbert",
|
| 439 |
+
)
|
| 440 |
+
def forward(
|
| 441 |
+
self,
|
| 442 |
+
input_ids: torch.LongTensor = None,
|
| 443 |
+
attention_mask: torch.Tensor | None = None,
|
| 444 |
+
position_ids: torch.LongTensor | None = None,
|
| 445 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 446 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 447 |
+
pixel_attention_mask: torch.BoolTensor | None = None,
|
| 448 |
+
image_hidden_states: torch.FloatTensor | None = None,
|
| 449 |
+
labels: torch.LongTensor | None = None,
|
| 450 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 451 |
+
) -> tuple | ModernVBertMaskedLMOutput:
|
| 452 |
+
r"""
|
| 453 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 454 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 455 |
+
image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 456 |
+
The hidden states of the image encoder after modality projection.
|
| 457 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 458 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 459 |
+
text_config.]` or `model.image_token_id`. Tokens with indices set to `model.image_token_id` are
|
| 460 |
+
ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., text_config.]`.
|
| 461 |
+
"""
|
| 462 |
+
|
| 463 |
+
outputs = self.model(
|
| 464 |
+
input_ids=input_ids,
|
| 465 |
+
attention_mask=attention_mask,
|
| 466 |
+
position_ids=position_ids,
|
| 467 |
+
inputs_embeds=inputs_embeds,
|
| 468 |
+
pixel_values=pixel_values,
|
| 469 |
+
pixel_attention_mask=pixel_attention_mask,
|
| 470 |
+
image_hidden_states=image_hidden_states,
|
| 471 |
+
**kwargs,
|
| 472 |
+
)
|
| 473 |
+
hidden_states = outputs[0]
|
| 474 |
+
|
| 475 |
+
logits = self.lm_head(self.projection_head(hidden_states))
|
| 476 |
+
|
| 477 |
+
loss = None
|
| 478 |
+
if labels is not None:
|
| 479 |
+
criterion = CrossEntropyLoss()
|
| 480 |
+
loss = criterion(logits.view(-1, self.vocab_size), labels.view(-1))
|
| 481 |
+
|
| 482 |
+
return ModernVBertMaskedLMOutput(
|
| 483 |
+
loss=loss,
|
| 484 |
+
logits=logits,
|
| 485 |
+
hidden_states=outputs.hidden_states,
|
| 486 |
+
attentions=outputs.attentions,
|
| 487 |
+
image_hidden_states=outputs.image_hidden_states,
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
@auto_docstring(
|
| 492 |
+
custom_intro="""
|
| 493 |
+
The ModernVBert Model with a sequence classification head on top that performs pooling.
|
| 494 |
+
"""
|
| 495 |
+
)
|
| 496 |
+
class ModernVBertForSequenceClassification(ModernVBertPreTrainedModel):
|
| 497 |
+
def __init__(self, config: ModernVBertConfig):
|
| 498 |
+
super().__init__(config)
|
| 499 |
+
self.num_labels = config.num_labels
|
| 500 |
+
self.config = config
|
| 501 |
+
|
| 502 |
+
self.model = ModernVBertModel(config)
|
| 503 |
+
self.head = ModernVBertPredictionHead(config.text_config)
|
| 504 |
+
self.drop = nn.Dropout(config.classifier_dropout)
|
| 505 |
+
self.classifier = nn.Linear(config.text_config.hidden_size, config.num_labels)
|
| 506 |
+
|
| 507 |
+
# Initialize weights and apply final processing
|
| 508 |
+
self.post_init()
|
| 509 |
+
|
| 510 |
+
@can_return_tuple
|
| 511 |
+
@auto_docstring(
|
| 512 |
+
custom_intro="""
|
| 513 |
+
Inputs fed to the model can have an arbitrary number of images. To account for this, pixel_values fed to
|
| 514 |
+
the model have image padding -> (batch_size, max_num_images, 3, max_heights, max_widths) where
|
| 515 |
+
max_num_images is the maximum number of images among the batch_size samples in the batch.
|
| 516 |
+
Padding images are not needed beyond padding the pixel_values at the entrance of the model.
|
| 517 |
+
For efficiency, we only pass through the vision_model's forward the real images by
|
| 518 |
+
discarding the padding images i.e. pixel_values of size (image_batch_size, 3, height, width) where
|
| 519 |
+
image_batch_size would be 7 when num_images_per_sample=[1, 3, 1, 2] and max_num_images would be 3.
|
| 520 |
+
""",
|
| 521 |
+
checkpoint="ModernVBERT/modernvbert",
|
| 522 |
+
)
|
| 523 |
+
def forward(
|
| 524 |
+
self,
|
| 525 |
+
input_ids: torch.LongTensor = None,
|
| 526 |
+
attention_mask: torch.Tensor | None = None,
|
| 527 |
+
position_ids: torch.LongTensor | None = None,
|
| 528 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 529 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 530 |
+
pixel_attention_mask: torch.BoolTensor | None = None,
|
| 531 |
+
image_hidden_states: torch.FloatTensor | None = None,
|
| 532 |
+
labels: torch.LongTensor | None = None,
|
| 533 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 534 |
+
) -> tuple | SequenceClassifierOutput:
|
| 535 |
+
r"""
|
| 536 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 537 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 538 |
+
image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 539 |
+
The hidden states of the image encoder after modality projection.
|
| 540 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 541 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 542 |
+
text_config.]` or `model.image_token_id`. Tokens with indices set to `model.image_token_id` are
|
| 543 |
+
ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., text_config.]`.
|
| 544 |
+
"""
|
| 545 |
+
outputs = self.model(
|
| 546 |
+
input_ids=input_ids,
|
| 547 |
+
attention_mask=attention_mask,
|
| 548 |
+
position_ids=position_ids,
|
| 549 |
+
inputs_embeds=inputs_embeds,
|
| 550 |
+
pixel_values=pixel_values,
|
| 551 |
+
pixel_attention_mask=pixel_attention_mask,
|
| 552 |
+
image_hidden_states=image_hidden_states,
|
| 553 |
+
**kwargs,
|
| 554 |
+
)
|
| 555 |
+
last_hidden_state = outputs[0]
|
| 556 |
+
|
| 557 |
+
if self.config.classifier_pooling == "cls":
|
| 558 |
+
last_hidden_state = last_hidden_state[:, 0]
|
| 559 |
+
elif self.config.classifier_pooling == "mean":
|
| 560 |
+
if inputs_embeds is not None:
|
| 561 |
+
batch_size, seq_len = inputs_embeds.shape[:2]
|
| 562 |
+
else:
|
| 563 |
+
batch_size, seq_len = input_ids.shape[:2]
|
| 564 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 565 |
+
|
| 566 |
+
if attention_mask is None:
|
| 567 |
+
attention_mask = torch.ones((batch_size, seq_len), device=device, dtype=torch.bool)
|
| 568 |
+
last_hidden_state = (last_hidden_state * attention_mask.unsqueeze(-1)).sum(dim=1) / attention_mask.sum(
|
| 569 |
+
dim=1, keepdim=True
|
| 570 |
+
)
|
| 571 |
+
|
| 572 |
+
pooled_output = self.head(last_hidden_state)
|
| 573 |
+
pooled_output = self.drop(pooled_output)
|
| 574 |
+
logits = self.classifier(pooled_output)
|
| 575 |
+
|
| 576 |
+
loss = None
|
| 577 |
+
if labels is not None:
|
| 578 |
+
if self.config.problem_type is None:
|
| 579 |
+
if self.num_labels == 1:
|
| 580 |
+
self.config.problem_type = "regression"
|
| 581 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 582 |
+
self.config.problem_type = "single_label_classification"
|
| 583 |
+
else:
|
| 584 |
+
self.config.problem_type = "multi_label_classification"
|
| 585 |
+
|
| 586 |
+
if self.config.problem_type == "regression":
|
| 587 |
+
loss_fct = MSELoss()
|
| 588 |
+
if self.num_labels == 1:
|
| 589 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 590 |
+
else:
|
| 591 |
+
loss = loss_fct(logits, labels)
|
| 592 |
+
elif self.config.problem_type == "single_label_classification":
|
| 593 |
+
loss_fct = CrossEntropyLoss()
|
| 594 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 595 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 596 |
+
loss_fct = BCEWithLogitsLoss()
|
| 597 |
+
loss = loss_fct(logits, labels)
|
| 598 |
+
|
| 599 |
+
return SequenceClassifierOutput(
|
| 600 |
+
loss=loss,
|
| 601 |
+
logits=logits,
|
| 602 |
+
hidden_states=outputs.hidden_states,
|
| 603 |
+
attentions=outputs.attentions,
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
@auto_docstring(
|
| 608 |
+
custom_intro="""
|
| 609 |
+
The ModernVBert Model with a token classification head on top, e.g. for Named Entity Recognition (NER) tasks.
|
| 610 |
+
"""
|
| 611 |
+
)
|
| 612 |
+
class ModernVBertForTokenClassification(ModernVBertPreTrainedModel):
|
| 613 |
+
def __init__(self, config: ModernVBertConfig):
|
| 614 |
+
super().__init__(config)
|
| 615 |
+
self.num_labels = config.num_labels
|
| 616 |
+
|
| 617 |
+
self.model = ModernVBertModel(config)
|
| 618 |
+
self.head = ModernVBertPredictionHead(config.text_config)
|
| 619 |
+
self.drop = nn.Dropout(config.classifier_dropout)
|
| 620 |
+
self.classifier = nn.Linear(config.text_config.hidden_size, config.num_labels)
|
| 621 |
+
|
| 622 |
+
# Initialize weights and apply final processing
|
| 623 |
+
self.post_init()
|
| 624 |
+
|
| 625 |
+
@can_return_tuple
|
| 626 |
+
@auto_docstring(
|
| 627 |
+
custom_intro="""
|
| 628 |
+
Inputs fed to the model can have an arbitrary number of images. To account for this, pixel_values fed to
|
| 629 |
+
the model have image padding -> (batch_size, max_num_images, 3, max_heights, max_widths) where
|
| 630 |
+
max_num_images is the maximum number of images among the batch_size samples in the batch.
|
| 631 |
+
Padding images are not needed beyond padding the pixel_values at the entrance of the model.
|
| 632 |
+
For efficiency, we only pass through the vision_model's forward the real images by
|
| 633 |
+
discarding the padding images i.e. pixel_values of size (image_batch_size, 3, height, width) where
|
| 634 |
+
image_batch_size would be 7 when num_images_per_sample=[1, 3, 1, 2] and max_num_images would be 3.
|
| 635 |
+
""",
|
| 636 |
+
checkpoint="ModernVBERT/modernvbert",
|
| 637 |
+
)
|
| 638 |
+
def forward(
|
| 639 |
+
self,
|
| 640 |
+
input_ids: torch.LongTensor = None,
|
| 641 |
+
attention_mask: torch.Tensor | None = None,
|
| 642 |
+
position_ids: torch.LongTensor | None = None,
|
| 643 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 644 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 645 |
+
pixel_attention_mask: torch.BoolTensor | None = None,
|
| 646 |
+
image_hidden_states: torch.FloatTensor | None = None,
|
| 647 |
+
labels: torch.LongTensor | None = None,
|
| 648 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 649 |
+
) -> tuple | TokenClassifierOutput:
|
| 650 |
+
r"""
|
| 651 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 652 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 653 |
+
image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 654 |
+
The hidden states of the image encoder after modality projection.
|
| 655 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 656 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 657 |
+
text_config.]` or `model.image_token_id`. Tokens with indices set to `model.image_token_id` are
|
| 658 |
+
ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., text_config.]`.
|
| 659 |
+
"""
|
| 660 |
+
|
| 661 |
+
outputs = self.model(
|
| 662 |
+
input_ids=input_ids,
|
| 663 |
+
attention_mask=attention_mask,
|
| 664 |
+
position_ids=position_ids,
|
| 665 |
+
inputs_embeds=inputs_embeds,
|
| 666 |
+
pixel_values=pixel_values,
|
| 667 |
+
pixel_attention_mask=pixel_attention_mask,
|
| 668 |
+
image_hidden_states=image_hidden_states,
|
| 669 |
+
**kwargs,
|
| 670 |
+
)
|
| 671 |
+
last_hidden_state = outputs[0]
|
| 672 |
+
|
| 673 |
+
last_hidden_state = self.head(last_hidden_state)
|
| 674 |
+
last_hidden_state = self.drop(last_hidden_state)
|
| 675 |
+
logits = self.classifier(last_hidden_state)
|
| 676 |
+
|
| 677 |
+
loss = None
|
| 678 |
+
if labels is not None:
|
| 679 |
+
loss_fct = CrossEntropyLoss()
|
| 680 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 681 |
+
|
| 682 |
+
return TokenClassifierOutput(
|
| 683 |
+
loss=loss,
|
| 684 |
+
logits=logits,
|
| 685 |
+
hidden_states=outputs.hidden_states,
|
| 686 |
+
attentions=outputs.attentions,
|
| 687 |
+
)
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
__all__ = [
|
| 691 |
+
"ModernVBertPreTrainedModel",
|
| 692 |
+
"ModernVBertModel",
|
| 693 |
+
"ModernVBertForMaskedLM",
|
| 694 |
+
"ModernVBertForSequenceClassification",
|
| 695 |
+
"ModernVBertForTokenClassification",
|
| 696 |
+
]
|
lib/python3.11/site-packages/transformers/models/modernvbert/modular_modernvbert.py
ADDED
|
@@ -0,0 +1,626 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Illuin Technology and contributors, and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import math
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
from typing import Literal
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
from huggingface_hub.dataclasses import strict
|
| 22 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 23 |
+
|
| 24 |
+
from ... import initialization as init
|
| 25 |
+
from ...configuration_utils import PreTrainedConfig
|
| 26 |
+
from ...modeling_outputs import (
|
| 27 |
+
BaseModelOutput,
|
| 28 |
+
MaskedLMOutput,
|
| 29 |
+
SequenceClassifierOutput,
|
| 30 |
+
TokenClassifierOutput,
|
| 31 |
+
)
|
| 32 |
+
from ...modeling_utils import PreTrainedModel
|
| 33 |
+
from ...processing_utils import Unpack
|
| 34 |
+
from ...utils import TransformersKwargs, auto_docstring, logging
|
| 35 |
+
from ...utils.generic import can_return_tuple
|
| 36 |
+
from ..auto import CONFIG_MAPPING, AutoConfig, AutoModel
|
| 37 |
+
from ..modernbert.modeling_modernbert import ModernBertPredictionHead
|
| 38 |
+
from ..smolvlm.modeling_smolvlm import SmolVLMModel, SmolVLMPreTrainedModel
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
logger = logging.get_logger(__name__)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@auto_docstring(checkpoint="ModernVBERT/modernvbert")
|
| 45 |
+
@strict
|
| 46 |
+
class ModernVBertConfig(PreTrainedConfig):
|
| 47 |
+
r"""
|
| 48 |
+
pixel_shuffle_factor (`int | None`, *optional*, defaults to 4):
|
| 49 |
+
Scale factor used by any pixel-shuffle / upsampling operations in the vision head.
|
| 50 |
+
initializer_cutoff_factor (`float | None`, *optional*, defaults to 2.0):
|
| 51 |
+
The cutoff factor for the truncated_normal_initializer for initializing all weight matrices.
|
| 52 |
+
classifier_pooling (`Literal["cls", "mean"]`, *optional*, defaults to `"cls"`):
|
| 53 |
+
The pooling strategy to use for classification tasks.
|
| 54 |
+
classifier_bias (`bool | None`, *optional*, defaults to `False`):
|
| 55 |
+
Whether to add a bias term to the classification head
|
| 56 |
+
|
| 57 |
+
Example:
|
| 58 |
+
```python
|
| 59 |
+
>>> from transformers import ModernVBertConfig
|
| 60 |
+
|
| 61 |
+
>>> # Initializing configuration
|
| 62 |
+
>>> configuration = ModernVBertConfig()
|
| 63 |
+
|
| 64 |
+
>>> # Initializing a model from the configuration (model class is implemented in
|
| 65 |
+
>>> # `modernvbert.modeling_modernvbert`)
|
| 66 |
+
|
| 67 |
+
>>> from transformers import ModernVBertModel
|
| 68 |
+
>>> model = ModernVBertModel(configuration)
|
| 69 |
+
|
| 70 |
+
>>> # Accessing the model configuration
|
| 71 |
+
>>> cfg = model.config
|
| 72 |
+
```"""
|
| 73 |
+
|
| 74 |
+
model_type = "modernvbert"
|
| 75 |
+
sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
|
| 76 |
+
|
| 77 |
+
text_config: PreTrainedConfig | dict | None = None
|
| 78 |
+
vision_config: PreTrainedConfig | dict | None = None
|
| 79 |
+
image_token_id: int = 50407
|
| 80 |
+
pixel_shuffle_factor: int = 4
|
| 81 |
+
initializer_range: float = 0.02
|
| 82 |
+
initializer_cutoff_factor: float = 2.0
|
| 83 |
+
classifier_pooling: Literal["cls", "mean"] = "cls"
|
| 84 |
+
classifier_dropout: float | int = 0.0
|
| 85 |
+
classifier_bias: bool = False
|
| 86 |
+
tie_word_embeddings: bool = False
|
| 87 |
+
|
| 88 |
+
def __post_init__(self, **kwargs):
|
| 89 |
+
if self.text_config is None:
|
| 90 |
+
self.text_config = CONFIG_MAPPING["modernbert"]()
|
| 91 |
+
elif isinstance(self.text_config, dict):
|
| 92 |
+
self.text_config = CONFIG_MAPPING["modernbert"](**self.text_config)
|
| 93 |
+
|
| 94 |
+
if self.vision_config is None:
|
| 95 |
+
self.vision_config = CONFIG_MAPPING["siglip_vision_model"]()
|
| 96 |
+
elif isinstance(self.vision_config, dict):
|
| 97 |
+
self.vision_config = CONFIG_MAPPING["siglip_vision_model"](**self.vision_config)
|
| 98 |
+
|
| 99 |
+
super().__post_init__(**kwargs)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@dataclass
|
| 103 |
+
class ModernVBertBaseModelOutput(BaseModelOutput):
|
| 104 |
+
"""
|
| 105 |
+
Base class for ModernVBERT model's outputs.
|
| 106 |
+
Args:
|
| 107 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 108 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 109 |
+
If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
|
| 110 |
+
hidden_size)` is output.
|
| 111 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 112 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 113 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 114 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 115 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 116 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 117 |
+
sequence_length)`.
|
| 118 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 119 |
+
heads.
|
| 120 |
+
image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
|
| 121 |
+
Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
|
| 122 |
+
sequence_length, hidden_size)`.
|
| 123 |
+
image_hidden_states of the model produced by the vision encoder
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
last_hidden_state: torch.FloatTensor = None
|
| 127 |
+
hidden_states: tuple[torch.FloatTensor] | None = None
|
| 128 |
+
attentions: tuple[torch.FloatTensor] | None = None
|
| 129 |
+
image_hidden_states: tuple[torch.FloatTensor] | None = None
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@dataclass
|
| 133 |
+
class ModernVBertMaskedLMOutput(MaskedLMOutput):
|
| 134 |
+
"""
|
| 135 |
+
Base class for ModernVBERT model's outputs with masked language modeling loss.
|
| 136 |
+
Args:
|
| 137 |
+
loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided):
|
| 138 |
+
Masked language modeling (MLM) loss.
|
| 139 |
+
logits (`torch.FloatTensor`):
|
| 140 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 141 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 142 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 143 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 144 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 145 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 146 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 147 |
+
sequence_length)`.
|
| 148 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 149 |
+
heads.
|
| 150 |
+
image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
|
| 151 |
+
Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
|
| 152 |
+
sequence_length, hidden_size)`.
|
| 153 |
+
image_hidden_states of the model produced by the vision encoder
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
loss: torch.FloatTensor | None = None
|
| 157 |
+
logits: torch.FloatTensor = None
|
| 158 |
+
hidden_states: tuple[torch.FloatTensor, ...] | None = None
|
| 159 |
+
attentions: tuple[torch.FloatTensor, ...] | None = None
|
| 160 |
+
image_hidden_states: torch.FloatTensor | None = None
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class ModernVBertConnector(nn.Module):
|
| 164 |
+
"""
|
| 165 |
+
Connector module for ModernVBERT. It performs a pixel shuffle operation followed by a linear projection to match the text model's hidden size.
|
| 166 |
+
Based on https://pytorch.org/docs/stable/generated/torch.nn.PixelShuffle.html
|
| 167 |
+
"""
|
| 168 |
+
|
| 169 |
+
def __init__(self, config):
|
| 170 |
+
super().__init__()
|
| 171 |
+
self.pixel_shuffle_factor = config.pixel_shuffle_factor
|
| 172 |
+
self.modality_projection = nn.Linear(
|
| 173 |
+
config.vision_config.hidden_size * (config.pixel_shuffle_factor**2),
|
| 174 |
+
config.text_config.hidden_size,
|
| 175 |
+
bias=False,
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
def pixel_shuffle(self, image_hidden_states, pixel_shuffle_factor):
|
| 179 |
+
batch_size, seq_length, embed_dim = image_hidden_states.size()
|
| 180 |
+
height = width = int(seq_length**0.5)
|
| 181 |
+
image_hidden_states = image_hidden_states.view(batch_size, height, width, embed_dim)
|
| 182 |
+
image_hidden_states = image_hidden_states.view(
|
| 183 |
+
batch_size, height, int(width / pixel_shuffle_factor), embed_dim * pixel_shuffle_factor
|
| 184 |
+
)
|
| 185 |
+
image_hidden_states = image_hidden_states.permute(0, 2, 1, 3)
|
| 186 |
+
image_hidden_states = image_hidden_states.reshape(
|
| 187 |
+
batch_size,
|
| 188 |
+
int(width / pixel_shuffle_factor),
|
| 189 |
+
int(height / pixel_shuffle_factor),
|
| 190 |
+
embed_dim * (pixel_shuffle_factor**2),
|
| 191 |
+
)
|
| 192 |
+
image_hidden_states = image_hidden_states.permute(0, 2, 1, 3)
|
| 193 |
+
return image_hidden_states.reshape(
|
| 194 |
+
batch_size, int(seq_length / (pixel_shuffle_factor**2)), embed_dim * (pixel_shuffle_factor**2)
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
def forward(self, image_hidden_states):
|
| 198 |
+
image_hidden_states = self.pixel_shuffle(image_hidden_states, self.pixel_shuffle_factor)
|
| 199 |
+
return self.modality_projection(image_hidden_states)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
@auto_docstring
|
| 203 |
+
class ModernVBertPreTrainedModel(SmolVLMPreTrainedModel):
|
| 204 |
+
config_class = ModernVBertConfig
|
| 205 |
+
_no_split_modules = []
|
| 206 |
+
|
| 207 |
+
@torch.no_grad()
|
| 208 |
+
def _init_weights(self, module):
|
| 209 |
+
PreTrainedModel._init_weights(self, module)
|
| 210 |
+
|
| 211 |
+
def init_weight(module: nn.Module, std: float):
|
| 212 |
+
cutoff_factor = getattr(self.config, "initializer_cutoff_factor", 2.0)
|
| 213 |
+
init.trunc_normal_(
|
| 214 |
+
module.weight,
|
| 215 |
+
mean=0.0,
|
| 216 |
+
std=std,
|
| 217 |
+
a=-cutoff_factor * std,
|
| 218 |
+
b=cutoff_factor * std,
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 222 |
+
if module.bias is not None:
|
| 223 |
+
init.zeros_(module.bias)
|
| 224 |
+
|
| 225 |
+
if isinstance(module, ModernVBertConnector):
|
| 226 |
+
out_std = self.config.initializer_range / math.sqrt(2.0 * self.config.text_config.num_hidden_layers)
|
| 227 |
+
init_weight(module.modality_projection, out_std)
|
| 228 |
+
elif isinstance(module, ModernVBertForMaskedLM):
|
| 229 |
+
out_std = self.config.initializer_range / math.sqrt(2.0 * self.config.text_config.num_hidden_layers)
|
| 230 |
+
init_weight(module.lm_head, out_std)
|
| 231 |
+
elif isinstance(
|
| 232 |
+
module,
|
| 233 |
+
(
|
| 234 |
+
ModernVBertForSequenceClassification,
|
| 235 |
+
ModernVBertForTokenClassification,
|
| 236 |
+
),
|
| 237 |
+
):
|
| 238 |
+
final_out_std = self.config.initializer_range / math.sqrt(self.config.text_config.hidden_size)
|
| 239 |
+
init_weight(module.classifier, final_out_std)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
@auto_docstring(
|
| 243 |
+
custom_intro="""
|
| 244 |
+
ModernVBertModel is a model that combines a vision encoder (SigLIP) and a text encoder (ModernBert).
|
| 245 |
+
|
| 246 |
+
ModernVBert is the base model of the visual retriver ColModernVBert, and was introduced in the following paper:
|
| 247 |
+
[*ModernVBERT: Towards Smaller Visual Document Retrievers*](https://arxiv.org/abs/2510.01149).
|
| 248 |
+
"""
|
| 249 |
+
)
|
| 250 |
+
class ModernVBertModel(SmolVLMModel):
|
| 251 |
+
def __init__(self, config: ModernVBertConfig):
|
| 252 |
+
super().__init__(config)
|
| 253 |
+
|
| 254 |
+
# init components
|
| 255 |
+
self.connector = ModernVBertConnector(config)
|
| 256 |
+
self.text_model = AutoModel.from_config(config.text_config)
|
| 257 |
+
self.vision_model = AutoModel.from_config(config.vision_config)
|
| 258 |
+
|
| 259 |
+
self.image_seq_len = int(
|
| 260 |
+
((config.vision_config.image_size // config.vision_config.patch_size) ** 2)
|
| 261 |
+
/ (config.pixel_shuffle_factor**2)
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
# initialize weights and apply final processing
|
| 265 |
+
self.post_init()
|
| 266 |
+
|
| 267 |
+
@can_return_tuple
|
| 268 |
+
@auto_docstring(
|
| 269 |
+
custom_intro="""
|
| 270 |
+
Inputs fed to the model can have an arbitrary number of images. To account for this, pixel_values fed to
|
| 271 |
+
the model have image padding -> (batch_size, max_num_images, 3, max_heights, max_widths) where
|
| 272 |
+
max_num_images is the maximum number of images among the batch_size samples in the batch.
|
| 273 |
+
Padding images are not needed beyond padding the pixel_values at the entrance of the model.
|
| 274 |
+
For efficiency, we only pass through the vision_model's forward the real images by
|
| 275 |
+
discarding the padding images i.e. pixel_values of size (image_batch_size, 3, height, width) where
|
| 276 |
+
image_batch_size would be 7 when num_images_per_sample=[1, 3, 1, 2] and max_num_images would be 3.
|
| 277 |
+
""",
|
| 278 |
+
checkpoint="ModernVBERT/modernvbert",
|
| 279 |
+
)
|
| 280 |
+
def forward(
|
| 281 |
+
self,
|
| 282 |
+
input_ids: torch.LongTensor = None,
|
| 283 |
+
attention_mask: torch.Tensor | None = None,
|
| 284 |
+
position_ids: torch.LongTensor | None = None,
|
| 285 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 286 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 287 |
+
pixel_attention_mask: torch.BoolTensor | None = None,
|
| 288 |
+
image_hidden_states: torch.FloatTensor | None = None,
|
| 289 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 290 |
+
) -> tuple | ModernVBertBaseModelOutput:
|
| 291 |
+
r"""
|
| 292 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 293 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 294 |
+
image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 295 |
+
The hidden states of the image encoder after modality projection.
|
| 296 |
+
"""
|
| 297 |
+
|
| 298 |
+
if inputs_embeds is None:
|
| 299 |
+
inputs_embeds = self.text_model.get_input_embeddings()(input_ids).to(input_ids.device)
|
| 300 |
+
|
| 301 |
+
# Images processing
|
| 302 |
+
if pixel_values is not None:
|
| 303 |
+
image_hidden_states = self.get_image_features(
|
| 304 |
+
pixel_values=pixel_values, pixel_attention_mask=pixel_attention_mask
|
| 305 |
+
).pooler_output
|
| 306 |
+
|
| 307 |
+
# Merge image and text embeddings
|
| 308 |
+
if image_hidden_states is not None:
|
| 309 |
+
image_hidden_states = image_hidden_states.to(dtype=inputs_embeds.dtype, device=inputs_embeds.device)
|
| 310 |
+
inputs_embeds = self.inputs_merger(
|
| 311 |
+
input_ids=input_ids, inputs_embeds=inputs_embeds, image_hidden_states=image_hidden_states
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
# Language model pass
|
| 315 |
+
outputs = self.text_model(
|
| 316 |
+
inputs_embeds=inputs_embeds,
|
| 317 |
+
attention_mask=attention_mask,
|
| 318 |
+
position_ids=position_ids,
|
| 319 |
+
**kwargs,
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
return ModernVBertBaseModelOutput(
|
| 323 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 324 |
+
hidden_states=outputs.hidden_states,
|
| 325 |
+
attentions=outputs.attentions,
|
| 326 |
+
image_hidden_states=image_hidden_states,
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class ModernVBertPredictionHead(ModernBertPredictionHead):
|
| 331 |
+
pass
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
@auto_docstring
|
| 335 |
+
class ModernVBertForMaskedLM(ModernVBertPreTrainedModel):
|
| 336 |
+
_tied_weights_keys = {"lm_head.weight": "model.text_model.embeddings.tok_embeddings.weight"}
|
| 337 |
+
|
| 338 |
+
def __init__(self, config: ModernVBertConfig):
|
| 339 |
+
super().__init__(config)
|
| 340 |
+
|
| 341 |
+
self.vocab_size = config.text_config.vocab_size
|
| 342 |
+
|
| 343 |
+
self.model = ModernVBertModel(config)
|
| 344 |
+
self.projection_head = ModernVBertPredictionHead(config.text_config)
|
| 345 |
+
self.lm_head = nn.Linear(config.text_config.hidden_size, self.vocab_size, bias=config.text_config.decoder_bias)
|
| 346 |
+
|
| 347 |
+
# Initialize weights and apply final processing
|
| 348 |
+
self.post_init()
|
| 349 |
+
|
| 350 |
+
def get_output_embeddings(self):
|
| 351 |
+
return self.lm_head
|
| 352 |
+
|
| 353 |
+
def set_output_embeddings(self, new_embeddings):
|
| 354 |
+
self.lm_head = new_embeddings
|
| 355 |
+
|
| 356 |
+
@can_return_tuple
|
| 357 |
+
@auto_docstring(
|
| 358 |
+
custom_intro="""
|
| 359 |
+
Inputs fed to the model can have an arbitrary number of images. To account for this, pixel_values fed to
|
| 360 |
+
the model have image padding -> (batch_size, max_num_images, 3, max_heights, max_widths) where
|
| 361 |
+
max_num_images is the maximum number of images among the batch_size samples in the batch.
|
| 362 |
+
Padding images are not needed beyond padding the pixel_values at the entrance of the model.
|
| 363 |
+
For efficiency, we only pass through the vision_model's forward the real images by
|
| 364 |
+
discarding the padding images i.e. pixel_values of size (image_batch_size, 3, height, width) where
|
| 365 |
+
image_batch_size would be 7 when num_images_per_sample=[1, 3, 1, 2] and max_num_images would be 3.
|
| 366 |
+
""",
|
| 367 |
+
checkpoint="ModernVBERT/modernvbert",
|
| 368 |
+
)
|
| 369 |
+
def forward(
|
| 370 |
+
self,
|
| 371 |
+
input_ids: torch.LongTensor = None,
|
| 372 |
+
attention_mask: torch.Tensor | None = None,
|
| 373 |
+
position_ids: torch.LongTensor | None = None,
|
| 374 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 375 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 376 |
+
pixel_attention_mask: torch.BoolTensor | None = None,
|
| 377 |
+
image_hidden_states: torch.FloatTensor | None = None,
|
| 378 |
+
labels: torch.LongTensor | None = None,
|
| 379 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 380 |
+
) -> tuple | ModernVBertMaskedLMOutput:
|
| 381 |
+
r"""
|
| 382 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 383 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 384 |
+
image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 385 |
+
The hidden states of the image encoder after modality projection.
|
| 386 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 387 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 388 |
+
text_config.]` or `model.image_token_id`. Tokens with indices set to `model.image_token_id` are
|
| 389 |
+
ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., text_config.]`.
|
| 390 |
+
"""
|
| 391 |
+
|
| 392 |
+
outputs = self.model(
|
| 393 |
+
input_ids=input_ids,
|
| 394 |
+
attention_mask=attention_mask,
|
| 395 |
+
position_ids=position_ids,
|
| 396 |
+
inputs_embeds=inputs_embeds,
|
| 397 |
+
pixel_values=pixel_values,
|
| 398 |
+
pixel_attention_mask=pixel_attention_mask,
|
| 399 |
+
image_hidden_states=image_hidden_states,
|
| 400 |
+
**kwargs,
|
| 401 |
+
)
|
| 402 |
+
hidden_states = outputs[0]
|
| 403 |
+
|
| 404 |
+
logits = self.lm_head(self.projection_head(hidden_states))
|
| 405 |
+
|
| 406 |
+
loss = None
|
| 407 |
+
if labels is not None:
|
| 408 |
+
criterion = CrossEntropyLoss()
|
| 409 |
+
loss = criterion(logits.view(-1, self.vocab_size), labels.view(-1))
|
| 410 |
+
|
| 411 |
+
return ModernVBertMaskedLMOutput(
|
| 412 |
+
loss=loss,
|
| 413 |
+
logits=logits,
|
| 414 |
+
hidden_states=outputs.hidden_states,
|
| 415 |
+
attentions=outputs.attentions,
|
| 416 |
+
image_hidden_states=outputs.image_hidden_states,
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
@auto_docstring(
|
| 421 |
+
custom_intro="""
|
| 422 |
+
The ModernVBert Model with a sequence classification head on top that performs pooling.
|
| 423 |
+
"""
|
| 424 |
+
)
|
| 425 |
+
class ModernVBertForSequenceClassification(ModernVBertPreTrainedModel):
|
| 426 |
+
def __init__(self, config: ModernVBertConfig):
|
| 427 |
+
super().__init__(config)
|
| 428 |
+
self.num_labels = config.num_labels
|
| 429 |
+
self.config = config
|
| 430 |
+
|
| 431 |
+
self.model = ModernVBertModel(config)
|
| 432 |
+
self.head = ModernVBertPredictionHead(config.text_config)
|
| 433 |
+
self.drop = nn.Dropout(config.classifier_dropout)
|
| 434 |
+
self.classifier = nn.Linear(config.text_config.hidden_size, config.num_labels)
|
| 435 |
+
|
| 436 |
+
# Initialize weights and apply final processing
|
| 437 |
+
self.post_init()
|
| 438 |
+
|
| 439 |
+
@can_return_tuple
|
| 440 |
+
@auto_docstring(
|
| 441 |
+
custom_intro="""
|
| 442 |
+
Inputs fed to the model can have an arbitrary number of images. To account for this, pixel_values fed to
|
| 443 |
+
the model have image padding -> (batch_size, max_num_images, 3, max_heights, max_widths) where
|
| 444 |
+
max_num_images is the maximum number of images among the batch_size samples in the batch.
|
| 445 |
+
Padding images are not needed beyond padding the pixel_values at the entrance of the model.
|
| 446 |
+
For efficiency, we only pass through the vision_model's forward the real images by
|
| 447 |
+
discarding the padding images i.e. pixel_values of size (image_batch_size, 3, height, width) where
|
| 448 |
+
image_batch_size would be 7 when num_images_per_sample=[1, 3, 1, 2] and max_num_images would be 3.
|
| 449 |
+
""",
|
| 450 |
+
checkpoint="ModernVBERT/modernvbert",
|
| 451 |
+
)
|
| 452 |
+
def forward(
|
| 453 |
+
self,
|
| 454 |
+
input_ids: torch.LongTensor = None,
|
| 455 |
+
attention_mask: torch.Tensor | None = None,
|
| 456 |
+
position_ids: torch.LongTensor | None = None,
|
| 457 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 458 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 459 |
+
pixel_attention_mask: torch.BoolTensor | None = None,
|
| 460 |
+
image_hidden_states: torch.FloatTensor | None = None,
|
| 461 |
+
labels: torch.LongTensor | None = None,
|
| 462 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 463 |
+
) -> tuple | SequenceClassifierOutput:
|
| 464 |
+
r"""
|
| 465 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 466 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 467 |
+
image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 468 |
+
The hidden states of the image encoder after modality projection.
|
| 469 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 470 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 471 |
+
text_config.]` or `model.image_token_id`. Tokens with indices set to `model.image_token_id` are
|
| 472 |
+
ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., text_config.]`.
|
| 473 |
+
"""
|
| 474 |
+
outputs = self.model(
|
| 475 |
+
input_ids=input_ids,
|
| 476 |
+
attention_mask=attention_mask,
|
| 477 |
+
position_ids=position_ids,
|
| 478 |
+
inputs_embeds=inputs_embeds,
|
| 479 |
+
pixel_values=pixel_values,
|
| 480 |
+
pixel_attention_mask=pixel_attention_mask,
|
| 481 |
+
image_hidden_states=image_hidden_states,
|
| 482 |
+
**kwargs,
|
| 483 |
+
)
|
| 484 |
+
last_hidden_state = outputs[0]
|
| 485 |
+
|
| 486 |
+
if self.config.classifier_pooling == "cls":
|
| 487 |
+
last_hidden_state = last_hidden_state[:, 0]
|
| 488 |
+
elif self.config.classifier_pooling == "mean":
|
| 489 |
+
if inputs_embeds is not None:
|
| 490 |
+
batch_size, seq_len = inputs_embeds.shape[:2]
|
| 491 |
+
else:
|
| 492 |
+
batch_size, seq_len = input_ids.shape[:2]
|
| 493 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 494 |
+
|
| 495 |
+
if attention_mask is None:
|
| 496 |
+
attention_mask = torch.ones((batch_size, seq_len), device=device, dtype=torch.bool)
|
| 497 |
+
last_hidden_state = (last_hidden_state * attention_mask.unsqueeze(-1)).sum(dim=1) / attention_mask.sum(
|
| 498 |
+
dim=1, keepdim=True
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
pooled_output = self.head(last_hidden_state)
|
| 502 |
+
pooled_output = self.drop(pooled_output)
|
| 503 |
+
logits = self.classifier(pooled_output)
|
| 504 |
+
|
| 505 |
+
loss = None
|
| 506 |
+
if labels is not None:
|
| 507 |
+
if self.config.problem_type is None:
|
| 508 |
+
if self.num_labels == 1:
|
| 509 |
+
self.config.problem_type = "regression"
|
| 510 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 511 |
+
self.config.problem_type = "single_label_classification"
|
| 512 |
+
else:
|
| 513 |
+
self.config.problem_type = "multi_label_classification"
|
| 514 |
+
|
| 515 |
+
if self.config.problem_type == "regression":
|
| 516 |
+
loss_fct = MSELoss()
|
| 517 |
+
if self.num_labels == 1:
|
| 518 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 519 |
+
else:
|
| 520 |
+
loss = loss_fct(logits, labels)
|
| 521 |
+
elif self.config.problem_type == "single_label_classification":
|
| 522 |
+
loss_fct = CrossEntropyLoss()
|
| 523 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 524 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 525 |
+
loss_fct = BCEWithLogitsLoss()
|
| 526 |
+
loss = loss_fct(logits, labels)
|
| 527 |
+
|
| 528 |
+
return SequenceClassifierOutput(
|
| 529 |
+
loss=loss,
|
| 530 |
+
logits=logits,
|
| 531 |
+
hidden_states=outputs.hidden_states,
|
| 532 |
+
attentions=outputs.attentions,
|
| 533 |
+
)
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
@auto_docstring(
|
| 537 |
+
custom_intro="""
|
| 538 |
+
The ModernVBert Model with a token classification head on top, e.g. for Named Entity Recognition (NER) tasks.
|
| 539 |
+
"""
|
| 540 |
+
)
|
| 541 |
+
class ModernVBertForTokenClassification(ModernVBertPreTrainedModel):
|
| 542 |
+
def __init__(self, config: ModernVBertConfig):
|
| 543 |
+
super().__init__(config)
|
| 544 |
+
self.num_labels = config.num_labels
|
| 545 |
+
|
| 546 |
+
self.model = ModernVBertModel(config)
|
| 547 |
+
self.head = ModernVBertPredictionHead(config.text_config)
|
| 548 |
+
self.drop = nn.Dropout(config.classifier_dropout)
|
| 549 |
+
self.classifier = nn.Linear(config.text_config.hidden_size, config.num_labels)
|
| 550 |
+
|
| 551 |
+
# Initialize weights and apply final processing
|
| 552 |
+
self.post_init()
|
| 553 |
+
|
| 554 |
+
@can_return_tuple
|
| 555 |
+
@auto_docstring(
|
| 556 |
+
custom_intro="""
|
| 557 |
+
Inputs fed to the model can have an arbitrary number of images. To account for this, pixel_values fed to
|
| 558 |
+
the model have image padding -> (batch_size, max_num_images, 3, max_heights, max_widths) where
|
| 559 |
+
max_num_images is the maximum number of images among the batch_size samples in the batch.
|
| 560 |
+
Padding images are not needed beyond padding the pixel_values at the entrance of the model.
|
| 561 |
+
For efficiency, we only pass through the vision_model's forward the real images by
|
| 562 |
+
discarding the padding images i.e. pixel_values of size (image_batch_size, 3, height, width) where
|
| 563 |
+
image_batch_size would be 7 when num_images_per_sample=[1, 3, 1, 2] and max_num_images would be 3.
|
| 564 |
+
""",
|
| 565 |
+
checkpoint="ModernVBERT/modernvbert",
|
| 566 |
+
)
|
| 567 |
+
def forward(
|
| 568 |
+
self,
|
| 569 |
+
input_ids: torch.LongTensor = None,
|
| 570 |
+
attention_mask: torch.Tensor | None = None,
|
| 571 |
+
position_ids: torch.LongTensor | None = None,
|
| 572 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 573 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 574 |
+
pixel_attention_mask: torch.BoolTensor | None = None,
|
| 575 |
+
image_hidden_states: torch.FloatTensor | None = None,
|
| 576 |
+
labels: torch.LongTensor | None = None,
|
| 577 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 578 |
+
) -> tuple | TokenClassifierOutput:
|
| 579 |
+
r"""
|
| 580 |
+
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
|
| 581 |
+
Mask to avoid performing attention on padding pixel indices.
|
| 582 |
+
image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 583 |
+
The hidden states of the image encoder after modality projection.
|
| 584 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 585 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 586 |
+
text_config.]` or `model.image_token_id`. Tokens with indices set to `model.image_token_id` are
|
| 587 |
+
ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., text_config.]`.
|
| 588 |
+
"""
|
| 589 |
+
|
| 590 |
+
outputs = self.model(
|
| 591 |
+
input_ids=input_ids,
|
| 592 |
+
attention_mask=attention_mask,
|
| 593 |
+
position_ids=position_ids,
|
| 594 |
+
inputs_embeds=inputs_embeds,
|
| 595 |
+
pixel_values=pixel_values,
|
| 596 |
+
pixel_attention_mask=pixel_attention_mask,
|
| 597 |
+
image_hidden_states=image_hidden_states,
|
| 598 |
+
**kwargs,
|
| 599 |
+
)
|
| 600 |
+
last_hidden_state = outputs[0]
|
| 601 |
+
|
| 602 |
+
last_hidden_state = self.head(last_hidden_state)
|
| 603 |
+
last_hidden_state = self.drop(last_hidden_state)
|
| 604 |
+
logits = self.classifier(last_hidden_state)
|
| 605 |
+
|
| 606 |
+
loss = None
|
| 607 |
+
if labels is not None:
|
| 608 |
+
loss_fct = CrossEntropyLoss()
|
| 609 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 610 |
+
|
| 611 |
+
return TokenClassifierOutput(
|
| 612 |
+
loss=loss,
|
| 613 |
+
logits=logits,
|
| 614 |
+
hidden_states=outputs.hidden_states,
|
| 615 |
+
attentions=outputs.attentions,
|
| 616 |
+
)
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
__all__ = [
|
| 620 |
+
"ModernVBertConfig",
|
| 621 |
+
"ModernVBertPreTrainedModel",
|
| 622 |
+
"ModernVBertModel",
|
| 623 |
+
"ModernVBertForMaskedLM",
|
| 624 |
+
"ModernVBertForSequenceClassification",
|
| 625 |
+
"ModernVBertForTokenClassification",
|
| 626 |
+
]
|
lib/python3.11/site-packages/transformers/models/moonshine/__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_moonshine import *
|
| 22 |
+
from .modeling_moonshine import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (787 Bytes). View file
|
|
|
lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/configuration_moonshine.cpython-311.pyc
ADDED
|
Binary file (5.79 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/modeling_moonshine.cpython-311.pyc
ADDED
|
Binary file (50.3 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/modular_moonshine.cpython-311.pyc
ADDED
|
Binary file (41.1 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/moonshine/configuration_moonshine.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/moonshine/modular_moonshine.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_moonshine.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from huggingface_hub.dataclasses import strict
|
| 22 |
+
|
| 23 |
+
from ...configuration_utils import PreTrainedConfig
|
| 24 |
+
from ...modeling_rope_utils import RopeParameters
|
| 25 |
+
from ...utils import auto_docstring
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@auto_docstring(checkpoint="UsefulSensors/moonshine-tiny")
|
| 29 |
+
@strict
|
| 30 |
+
class MoonshineConfig(PreTrainedConfig):
|
| 31 |
+
r"""
|
| 32 |
+
encoder_num_key_value_heads (`int`, *optional*):
|
| 33 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 34 |
+
`encoder_num_key_value_heads=encoder_num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 35 |
+
`encoder_num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 36 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 37 |
+
by meanpooling all the original heads within that group. For more details, check out [this
|
| 38 |
+
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
|
| 39 |
+
`num_attention_heads`.
|
| 40 |
+
decoder_num_key_value_heads (`int`, *optional*):
|
| 41 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 42 |
+
`decoder_num_key_value_heads=decoder_num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 43 |
+
`decoder_num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 44 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 45 |
+
by meanpooling all the original heads within that group. For more details, check out [this
|
| 46 |
+
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
|
| 47 |
+
`decoder_num_attention_heads`.
|
| 48 |
+
pad_head_dim_to_multiple_of (`int`, *optional*):
|
| 49 |
+
Pad head dimension in encoder and decoder to the next multiple of this value. Necessary for using certain
|
| 50 |
+
optimized attention implementations.
|
| 51 |
+
encoder_hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 52 |
+
The non-linear activation function (function or string) in the encoder.
|
| 53 |
+
decoder_hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 54 |
+
The non-linear activation function (function or string) in the decoder.
|
| 55 |
+
|
| 56 |
+
Example:
|
| 57 |
+
|
| 58 |
+
```python
|
| 59 |
+
>>> from transformers import MoonshineModel, MoonshineConfig
|
| 60 |
+
|
| 61 |
+
>>> # Initializing a Moonshine style configuration
|
| 62 |
+
>>> configuration = MoonshineConfig().from_pretrained("UsefulSensors/moonshine-tiny")
|
| 63 |
+
|
| 64 |
+
>>> # Initializing a model from the configuration
|
| 65 |
+
>>> model = MoonshineModel(configuration)
|
| 66 |
+
|
| 67 |
+
>>> # Accessing the model configuration
|
| 68 |
+
>>> configuration = model.config
|
| 69 |
+
```"""
|
| 70 |
+
|
| 71 |
+
model_type = "moonshine"
|
| 72 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 73 |
+
attribute_map = {
|
| 74 |
+
"num_key_value_heads": "decoder_num_key_value_heads",
|
| 75 |
+
"num_attention_heads": "decoder_num_attention_heads",
|
| 76 |
+
"num_hidden_layers": "decoder_num_hidden_layers",
|
| 77 |
+
"hidden_act": "decoder_hidden_act",
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
vocab_size: int = 32768
|
| 81 |
+
hidden_size: int = 288
|
| 82 |
+
intermediate_size: int = 1152
|
| 83 |
+
encoder_num_hidden_layers: int = 6
|
| 84 |
+
decoder_num_hidden_layers: int = 6
|
| 85 |
+
encoder_num_attention_heads: int = 8
|
| 86 |
+
decoder_num_attention_heads: int = 8
|
| 87 |
+
encoder_num_key_value_heads: int | None = None
|
| 88 |
+
decoder_num_key_value_heads: int | None = None
|
| 89 |
+
pad_head_dim_to_multiple_of: int | None = None
|
| 90 |
+
encoder_hidden_act: str = "gelu"
|
| 91 |
+
decoder_hidden_act: str = "silu"
|
| 92 |
+
max_position_embeddings: int = 512
|
| 93 |
+
initializer_range: float = 0.02
|
| 94 |
+
decoder_start_token_id: int = 1
|
| 95 |
+
use_cache: bool = True
|
| 96 |
+
rope_parameters: RopeParameters | dict | None = None
|
| 97 |
+
is_encoder_decoder: bool = True
|
| 98 |
+
attention_bias: bool = False
|
| 99 |
+
attention_dropout: float | int = 0.0
|
| 100 |
+
bos_token_id: int | None = 1
|
| 101 |
+
eos_token_id: int | list[int] | None = 2
|
| 102 |
+
pad_token_id: int | None = None
|
| 103 |
+
tie_word_embeddings: bool = True
|
| 104 |
+
|
| 105 |
+
def __post_init__(self, **kwargs):
|
| 106 |
+
if self.encoder_num_key_value_heads is None:
|
| 107 |
+
self.encoder_num_key_value_heads = self.encoder_num_attention_heads
|
| 108 |
+
|
| 109 |
+
if self.decoder_num_key_value_heads is None:
|
| 110 |
+
self.decoder_num_key_value_heads = self.decoder_num_attention_heads
|
| 111 |
+
|
| 112 |
+
kwargs.setdefault("partial_rotary_factor", 0.9) # assign default for BC
|
| 113 |
+
super().__post_init__(**kwargs)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
__all__ = ["MoonshineConfig"]
|
lib/python3.11/site-packages/transformers/models/moonshine/modeling_moonshine.py
ADDED
|
@@ -0,0 +1,953 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/moonshine/modular_moonshine.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_moonshine.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from collections.abc import Callable
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from typing import Optional
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
|
| 28 |
+
from ...activations import ACT2FN
|
| 29 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 30 |
+
from ...generation import GenerationMixin
|
| 31 |
+
from ...integrations import use_kernelized_func
|
| 32 |
+
from ...masking_utils import create_bidirectional_mask, create_causal_mask
|
| 33 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 34 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 35 |
+
from ...modeling_outputs import (
|
| 36 |
+
BaseModelOutput,
|
| 37 |
+
BaseModelOutputWithPast,
|
| 38 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 39 |
+
Seq2SeqLMOutput,
|
| 40 |
+
Seq2SeqModelOutput,
|
| 41 |
+
)
|
| 42 |
+
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 43 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 44 |
+
from ...processing_utils import Unpack
|
| 45 |
+
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
|
| 46 |
+
from ...utils.generic import maybe_autocast, merge_with_config_defaults
|
| 47 |
+
from ...utils.output_capturing import OutputRecorder, capture_outputs
|
| 48 |
+
from .configuration_moonshine import MoonshineConfig
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@auto_docstring(
|
| 52 |
+
custom_intro="""
|
| 53 |
+
Extends [~modeling_outputs.BaseModelOutput] to include the output attention mask since sequence length is not preserved in the model's forward.
|
| 54 |
+
"""
|
| 55 |
+
)
|
| 56 |
+
@dataclass
|
| 57 |
+
class MoonshineEncoderModelOutput(BaseModelOutput):
|
| 58 |
+
r"""
|
| 59 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 60 |
+
Mask to avoid performing attention on padding token indices after sequence compression. Returned because the
|
| 61 |
+
sequence length may differ from the input sequence length. Mask values selected in `[0, 1]`:
|
| 62 |
+
|
| 63 |
+
- 1 for tokens that are **not masked**,
|
| 64 |
+
- 0 for tokens that are **masked**.
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
attention_mask: torch.Tensor | None = None
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class MoonshineEncoderMLP(nn.Module):
|
| 71 |
+
def __init__(self, config, hidden_act):
|
| 72 |
+
super().__init__()
|
| 73 |
+
self.config = config
|
| 74 |
+
self.activation_fn = ACT2FN[hidden_act]
|
| 75 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 76 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 77 |
+
|
| 78 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 79 |
+
hidden_states = self.fc1(hidden_states)
|
| 80 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 81 |
+
hidden_states = self.fc2(hidden_states)
|
| 82 |
+
return hidden_states
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class MoonshineDecoderMLP(nn.Module):
|
| 86 |
+
def __init__(self, config, hidden_act):
|
| 87 |
+
super().__init__()
|
| 88 |
+
self.config = config
|
| 89 |
+
self.activation_fn = ACT2FN[hidden_act]
|
| 90 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size * 2)
|
| 91 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 92 |
+
|
| 93 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 94 |
+
hidden_states = self.fc1(hidden_states)
|
| 95 |
+
hidden_states, gate = hidden_states.chunk(2, dim=-1)
|
| 96 |
+
hidden_states = self.activation_fn(gate) * hidden_states
|
| 97 |
+
hidden_states = self.fc2(hidden_states)
|
| 98 |
+
return hidden_states
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class MoonshineRotaryEmbedding(nn.Module):
|
| 102 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
| 103 |
+
|
| 104 |
+
def __init__(self, config: MoonshineConfig, device=None):
|
| 105 |
+
super().__init__()
|
| 106 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 107 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 108 |
+
|
| 109 |
+
self.config = config
|
| 110 |
+
|
| 111 |
+
self.rope_type = self.config.rope_parameters["rope_type"]
|
| 112 |
+
rope_init_fn: Callable = self.compute_default_rope_parameters
|
| 113 |
+
if self.rope_type != "default":
|
| 114 |
+
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 115 |
+
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
|
| 116 |
+
|
| 117 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 118 |
+
self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
|
| 119 |
+
|
| 120 |
+
@staticmethod
|
| 121 |
+
def compute_default_rope_parameters(
|
| 122 |
+
config: MoonshineConfig | None = None,
|
| 123 |
+
device: Optional["torch.device"] = None,
|
| 124 |
+
seq_len: int | None = None,
|
| 125 |
+
) -> tuple["torch.Tensor", float]:
|
| 126 |
+
"""
|
| 127 |
+
Computes the inverse frequencies according to the original RoPE implementation
|
| 128 |
+
Args:
|
| 129 |
+
config ([`~transformers.PreTrainedConfig`]):
|
| 130 |
+
The model configuration.
|
| 131 |
+
device (`torch.device`):
|
| 132 |
+
The device to use for initialization of the inverse frequencies.
|
| 133 |
+
seq_len (`int`, *optional*):
|
| 134 |
+
The current sequence length. Unused for this type of RoPE.
|
| 135 |
+
Returns:
|
| 136 |
+
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
| 137 |
+
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
|
| 138 |
+
"""
|
| 139 |
+
base = config.rope_parameters["rope_theta"]
|
| 140 |
+
partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
|
| 141 |
+
head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
| 142 |
+
dim = int(head_dim * partial_rotary_factor)
|
| 143 |
+
|
| 144 |
+
attention_factor = 1.0 # Unused in this type of RoPE
|
| 145 |
+
|
| 146 |
+
# Compute the inverse frequencies
|
| 147 |
+
inv_freq = 1.0 / (
|
| 148 |
+
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
|
| 149 |
+
)
|
| 150 |
+
return inv_freq, attention_factor
|
| 151 |
+
|
| 152 |
+
@torch.no_grad()
|
| 153 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 154 |
+
def forward(self, x, position_ids):
|
| 155 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 156 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 157 |
+
|
| 158 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 159 |
+
with maybe_autocast(device_type=device_type, enabled=False): # Force float32
|
| 160 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 161 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 162 |
+
cos = emb.cos() * self.attention_scaling
|
| 163 |
+
sin = emb.sin() * self.attention_scaling
|
| 164 |
+
|
| 165 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 169 |
+
"""
|
| 170 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 171 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 172 |
+
"""
|
| 173 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 174 |
+
if n_rep == 1:
|
| 175 |
+
return hidden_states
|
| 176 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 177 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def eager_attention_forward(
|
| 181 |
+
module: nn.Module,
|
| 182 |
+
query: torch.Tensor,
|
| 183 |
+
key: torch.Tensor,
|
| 184 |
+
value: torch.Tensor,
|
| 185 |
+
attention_mask: torch.Tensor | None,
|
| 186 |
+
scaling: float,
|
| 187 |
+
dropout: float = 0.0,
|
| 188 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 189 |
+
):
|
| 190 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 191 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 192 |
+
|
| 193 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 194 |
+
if attention_mask is not None:
|
| 195 |
+
attn_weights = attn_weights + attention_mask
|
| 196 |
+
|
| 197 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 198 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 199 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 200 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 201 |
+
|
| 202 |
+
return attn_output, attn_weights
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def rotate_half(x):
|
| 206 |
+
"""Rotates half the hidden dims of the input."""
|
| 207 |
+
x1 = x[..., 0::2]
|
| 208 |
+
x2 = x[..., 1::2]
|
| 209 |
+
return torch.stack((-x2, x1), dim=-1).flatten(-2)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 213 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 214 |
+
|
| 215 |
+
Args:
|
| 216 |
+
q (`torch.Tensor`): The query tensor.
|
| 217 |
+
k (`torch.Tensor`): The key tensor.
|
| 218 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 219 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 220 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 221 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 222 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 223 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 224 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 225 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 226 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 227 |
+
Returns:
|
| 228 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 229 |
+
"""
|
| 230 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 231 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 232 |
+
|
| 233 |
+
# Interleave them instead of usual shape
|
| 234 |
+
cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
|
| 235 |
+
sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
|
| 236 |
+
|
| 237 |
+
# Keep half or full tensor for later concatenation
|
| 238 |
+
rotary_dim = cos.shape[-1]
|
| 239 |
+
q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
|
| 240 |
+
k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
|
| 241 |
+
|
| 242 |
+
# Apply rotary embeddings on the first half or full tensor
|
| 243 |
+
q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
|
| 244 |
+
k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
|
| 245 |
+
|
| 246 |
+
# Concatenate back to full shape
|
| 247 |
+
q_embed = torch.cat([q_embed, q_pass], dim=-1)
|
| 248 |
+
k_embed = torch.cat([k_embed, k_pass], dim=-1)
|
| 249 |
+
return q_embed, k_embed
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
@use_kernelized_func(apply_rotary_pos_emb)
|
| 253 |
+
class MoonshineAttention(nn.Module):
|
| 254 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 255 |
+
|
| 256 |
+
def __init__(
|
| 257 |
+
self,
|
| 258 |
+
config: MoonshineConfig,
|
| 259 |
+
layer_idx: int,
|
| 260 |
+
is_causal: bool,
|
| 261 |
+
num_attention_heads: int,
|
| 262 |
+
num_key_value_heads: int,
|
| 263 |
+
):
|
| 264 |
+
super().__init__()
|
| 265 |
+
config.update({"num_attention_heads": num_attention_heads, "num_key_value_heads": num_key_value_heads})
|
| 266 |
+
self.config = config
|
| 267 |
+
self.layer_idx = layer_idx
|
| 268 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 269 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 270 |
+
self.scaling = self.head_dim**-0.5
|
| 271 |
+
self.attention_dropout = config.attention_dropout
|
| 272 |
+
self.is_causal = is_causal
|
| 273 |
+
|
| 274 |
+
self.q_proj = nn.Linear(
|
| 275 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 276 |
+
)
|
| 277 |
+
self.k_proj = nn.Linear(
|
| 278 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 279 |
+
)
|
| 280 |
+
self.v_proj = nn.Linear(
|
| 281 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 282 |
+
)
|
| 283 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
| 284 |
+
|
| 285 |
+
# Pad head dimension to the next specified multiple.
|
| 286 |
+
if self.config.pad_head_dim_to_multiple_of is not None:
|
| 287 |
+
target_multiple = self.config.pad_head_dim_to_multiple_of
|
| 288 |
+
target_head_dim = target_multiple * ((self.head_dim + target_multiple - 1) // target_multiple)
|
| 289 |
+
self.head_dim_padding = target_head_dim - self.head_dim
|
| 290 |
+
else:
|
| 291 |
+
self.head_dim_padding = 0
|
| 292 |
+
|
| 293 |
+
def forward(
|
| 294 |
+
self,
|
| 295 |
+
hidden_states: torch.Tensor,
|
| 296 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 297 |
+
attention_mask: torch.Tensor | None = None,
|
| 298 |
+
past_key_values: Cache | None = None,
|
| 299 |
+
key_value_states: torch.Tensor | None = None,
|
| 300 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 301 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
|
| 302 |
+
bsz, q_len = hidden_states.shape[:-1]
|
| 303 |
+
|
| 304 |
+
query_states = (
|
| 305 |
+
self.q_proj(hidden_states).view(bsz, q_len, self.config.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
is_cross_attention = key_value_states is not None
|
| 309 |
+
if past_key_values is not None:
|
| 310 |
+
is_updated = past_key_values.is_updated.get(self.layer_idx)
|
| 311 |
+
if is_cross_attention:
|
| 312 |
+
# after the first generated id, we can subsequently re-use all key/value_states from cache
|
| 313 |
+
past_key_values.is_updated[self.layer_idx] = True
|
| 314 |
+
past_key_values = past_key_values.cross_attention_cache
|
| 315 |
+
else:
|
| 316 |
+
past_key_values = past_key_values.self_attention_cache
|
| 317 |
+
|
| 318 |
+
# use key_value_states if cross attention
|
| 319 |
+
current_states = key_value_states if key_value_states is not None else hidden_states
|
| 320 |
+
if is_cross_attention and past_key_values and is_updated:
|
| 321 |
+
key_states = past_key_values.layers[self.layer_idx].keys
|
| 322 |
+
value_states = past_key_values.layers[self.layer_idx].values
|
| 323 |
+
else:
|
| 324 |
+
key_states = (
|
| 325 |
+
self.k_proj(current_states)
|
| 326 |
+
.view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
|
| 327 |
+
.transpose(1, 2)
|
| 328 |
+
)
|
| 329 |
+
value_states = (
|
| 330 |
+
self.v_proj(current_states)
|
| 331 |
+
.view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
|
| 332 |
+
.transpose(1, 2)
|
| 333 |
+
)
|
| 334 |
+
if is_cross_attention and past_key_values is not None:
|
| 335 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 336 |
+
|
| 337 |
+
if not is_cross_attention:
|
| 338 |
+
cos, sin = position_embeddings
|
| 339 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 340 |
+
|
| 341 |
+
if past_key_values is not None:
|
| 342 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 343 |
+
|
| 344 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 345 |
+
self.config._attn_implementation, eager_attention_forward
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
is_causal = self.is_causal and attention_mask is None and q_len > 1
|
| 349 |
+
|
| 350 |
+
if self.head_dim_padding > 0:
|
| 351 |
+
query_states = torch.nn.functional.pad(query_states, (0, self.head_dim_padding))
|
| 352 |
+
key_states = torch.nn.functional.pad(key_states, (0, self.head_dim_padding))
|
| 353 |
+
value_states = torch.nn.functional.pad(value_states, (0, self.head_dim_padding))
|
| 354 |
+
|
| 355 |
+
attn_output, attn_weights = attention_interface(
|
| 356 |
+
self,
|
| 357 |
+
query_states,
|
| 358 |
+
key_states,
|
| 359 |
+
value_states,
|
| 360 |
+
attention_mask,
|
| 361 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 362 |
+
scaling=self.scaling,
|
| 363 |
+
is_causal=is_causal,
|
| 364 |
+
**kwargs,
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
if self.head_dim_padding > 0:
|
| 368 |
+
attn_output = attn_output[..., : -self.head_dim_padding]
|
| 369 |
+
|
| 370 |
+
attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
|
| 371 |
+
attn_output = self.o_proj(attn_output)
|
| 372 |
+
return attn_output, attn_weights
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
class MoonshineEncoderLayer(GradientCheckpointingLayer):
|
| 376 |
+
def __init__(self, config: MoonshineConfig, layer_idx: int):
|
| 377 |
+
super().__init__()
|
| 378 |
+
self.hidden_size = config.hidden_size
|
| 379 |
+
|
| 380 |
+
self.self_attn = MoonshineAttention(
|
| 381 |
+
config=config,
|
| 382 |
+
layer_idx=layer_idx,
|
| 383 |
+
is_causal=False,
|
| 384 |
+
num_attention_heads=config.encoder_num_attention_heads,
|
| 385 |
+
num_key_value_heads=config.encoder_num_key_value_heads,
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
self.mlp = MoonshineEncoderMLP(config, config.encoder_hidden_act)
|
| 389 |
+
self.input_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 390 |
+
self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 391 |
+
|
| 392 |
+
def forward(
|
| 393 |
+
self,
|
| 394 |
+
hidden_states: torch.Tensor,
|
| 395 |
+
attention_mask: torch.Tensor | None = None,
|
| 396 |
+
position_ids: torch.LongTensor | None = None,
|
| 397 |
+
past_key_values: Cache | None = None,
|
| 398 |
+
use_cache: bool | None = False,
|
| 399 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 400 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 401 |
+
) -> torch.Tensor:
|
| 402 |
+
residual = hidden_states
|
| 403 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 404 |
+
# Self Attention
|
| 405 |
+
hidden_states, _ = self.self_attn(
|
| 406 |
+
hidden_states=hidden_states,
|
| 407 |
+
attention_mask=attention_mask,
|
| 408 |
+
position_ids=position_ids,
|
| 409 |
+
past_key_values=past_key_values,
|
| 410 |
+
use_cache=use_cache,
|
| 411 |
+
position_embeddings=position_embeddings,
|
| 412 |
+
**kwargs,
|
| 413 |
+
)
|
| 414 |
+
hidden_states = residual + hidden_states
|
| 415 |
+
|
| 416 |
+
# Fully Connected
|
| 417 |
+
residual = hidden_states
|
| 418 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 419 |
+
hidden_states = self.mlp(hidden_states)
|
| 420 |
+
hidden_states = residual + hidden_states
|
| 421 |
+
return hidden_states
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
class MoonshineDecoderLayer(GradientCheckpointingLayer):
|
| 425 |
+
def __init__(self, config: MoonshineConfig, layer_idx: int | None = None):
|
| 426 |
+
super().__init__()
|
| 427 |
+
self.hidden_size = config.hidden_size
|
| 428 |
+
|
| 429 |
+
self.self_attn = MoonshineAttention(
|
| 430 |
+
config=config,
|
| 431 |
+
layer_idx=layer_idx,
|
| 432 |
+
is_causal=True,
|
| 433 |
+
num_attention_heads=config.num_attention_heads,
|
| 434 |
+
num_key_value_heads=config.num_key_value_heads,
|
| 435 |
+
)
|
| 436 |
+
self.encoder_attn = MoonshineAttention(
|
| 437 |
+
config=config,
|
| 438 |
+
layer_idx=layer_idx,
|
| 439 |
+
is_causal=False,
|
| 440 |
+
num_attention_heads=config.num_attention_heads,
|
| 441 |
+
num_key_value_heads=config.num_key_value_heads,
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
self.mlp = MoonshineDecoderMLP(config, config.hidden_act)
|
| 445 |
+
self.input_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 446 |
+
self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 447 |
+
self.final_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 448 |
+
|
| 449 |
+
def forward(
|
| 450 |
+
self,
|
| 451 |
+
hidden_states: torch.Tensor,
|
| 452 |
+
attention_mask: torch.Tensor | None = None,
|
| 453 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 454 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 455 |
+
position_ids: torch.LongTensor | None = None,
|
| 456 |
+
encoder_position_ids: torch.LongTensor | None = None,
|
| 457 |
+
past_key_values: Cache | None = None,
|
| 458 |
+
use_cache: bool | None = False,
|
| 459 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 460 |
+
encoder_position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 461 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 462 |
+
) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
|
| 463 |
+
residual = hidden_states
|
| 464 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 465 |
+
|
| 466 |
+
hidden_states, _ = self.self_attn(
|
| 467 |
+
hidden_states=hidden_states,
|
| 468 |
+
attention_mask=attention_mask,
|
| 469 |
+
position_ids=position_ids,
|
| 470 |
+
past_key_values=past_key_values,
|
| 471 |
+
use_cache=use_cache,
|
| 472 |
+
position_embeddings=position_embeddings,
|
| 473 |
+
**kwargs,
|
| 474 |
+
)
|
| 475 |
+
hidden_states = residual + hidden_states
|
| 476 |
+
|
| 477 |
+
if encoder_hidden_states is not None:
|
| 478 |
+
residual = hidden_states
|
| 479 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 480 |
+
hidden_states, _ = self.encoder_attn(
|
| 481 |
+
hidden_states=hidden_states,
|
| 482 |
+
key_value_states=encoder_hidden_states,
|
| 483 |
+
attention_mask=encoder_attention_mask,
|
| 484 |
+
past_key_values=past_key_values,
|
| 485 |
+
use_cache=use_cache,
|
| 486 |
+
)
|
| 487 |
+
hidden_states = residual + hidden_states
|
| 488 |
+
|
| 489 |
+
residual = hidden_states
|
| 490 |
+
hidden_states = self.final_layernorm(hidden_states)
|
| 491 |
+
hidden_states = self.mlp(hidden_states)
|
| 492 |
+
hidden_states = residual + hidden_states
|
| 493 |
+
return hidden_states
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
@auto_docstring
|
| 497 |
+
class MoonshinePreTrainedModel(PreTrainedModel):
|
| 498 |
+
config: MoonshineConfig
|
| 499 |
+
base_model_prefix = "model"
|
| 500 |
+
main_input_name = "input_values"
|
| 501 |
+
input_modalities = "audio"
|
| 502 |
+
supports_gradient_checkpointing = True
|
| 503 |
+
_no_split_modules = ["MoonshineEncoderLayer", "MoonshineDecoderLayer"]
|
| 504 |
+
_supports_flash_attn = True
|
| 505 |
+
_supports_sdpa = True
|
| 506 |
+
|
| 507 |
+
_can_compile_fullgraph = True
|
| 508 |
+
# TODO arthur, how do we separate when it cross / self coming from different layer?
|
| 509 |
+
|
| 510 |
+
def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
|
| 511 |
+
"""
|
| 512 |
+
Computes the output length of the convolutional layers
|
| 513 |
+
"""
|
| 514 |
+
output_conv1_length = int((input_lengths - 127) / 64 + 1)
|
| 515 |
+
output_conv2_length = int((output_conv1_length - 7) / 3 + 1)
|
| 516 |
+
output_conv3_length = int((output_conv2_length - 3) / 2 + 1)
|
| 517 |
+
|
| 518 |
+
return output_conv3_length
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
class MoonshineEncoder(MoonshinePreTrainedModel):
|
| 522 |
+
"""
|
| 523 |
+
Transformer encoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MoonshineEncoderLayer`]
|
| 524 |
+
|
| 525 |
+
Args:
|
| 526 |
+
config: MoonshineConfig
|
| 527 |
+
"""
|
| 528 |
+
|
| 529 |
+
main_input_name = "input_values"
|
| 530 |
+
_can_record_outputs = {
|
| 531 |
+
"attentions": MoonshineAttention,
|
| 532 |
+
"hidden_states": MoonshineEncoderLayer,
|
| 533 |
+
}
|
| 534 |
+
|
| 535 |
+
def __init__(self, config: MoonshineConfig):
|
| 536 |
+
super().__init__(config)
|
| 537 |
+
self.config = config
|
| 538 |
+
embed_dim = config.hidden_size
|
| 539 |
+
|
| 540 |
+
self.conv1 = nn.Conv1d(1, embed_dim, kernel_size=127, stride=64, bias=False)
|
| 541 |
+
self.conv2 = nn.Conv1d(embed_dim, 2 * embed_dim, kernel_size=7, stride=3)
|
| 542 |
+
self.conv3 = nn.Conv1d(2 * embed_dim, embed_dim, kernel_size=3, stride=2)
|
| 543 |
+
self.groupnorm = nn.GroupNorm(num_groups=1, num_channels=embed_dim, eps=1e-5)
|
| 544 |
+
|
| 545 |
+
self.layers = nn.ModuleList(
|
| 546 |
+
[MoonshineEncoderLayer(config, idx) for idx in range(config.encoder_num_hidden_layers)]
|
| 547 |
+
)
|
| 548 |
+
self.layer_norm = nn.LayerNorm(embed_dim, bias=False)
|
| 549 |
+
self.rotary_emb = MoonshineRotaryEmbedding(config=config)
|
| 550 |
+
self.gradient_checkpointing = False
|
| 551 |
+
self.post_init()
|
| 552 |
+
|
| 553 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 554 |
+
return self.conv1
|
| 555 |
+
|
| 556 |
+
def set_input_embeddings(self, value: nn.Module):
|
| 557 |
+
self.conv1 = value
|
| 558 |
+
|
| 559 |
+
@merge_with_config_defaults
|
| 560 |
+
@capture_outputs
|
| 561 |
+
def forward(
|
| 562 |
+
self,
|
| 563 |
+
input_values: torch.FloatTensor,
|
| 564 |
+
attention_mask: torch.Tensor | None = None,
|
| 565 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 566 |
+
) -> tuple | BaseModelOutputWithPast:
|
| 567 |
+
r"""
|
| 568 |
+
Args:
|
| 569 |
+
input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
|
| 570 |
+
Float values of the raw speech waveform. Raw speech waveform can be
|
| 571 |
+
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
|
| 572 |
+
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
|
| 573 |
+
the soundfile library (`pip install soundfile`). To prepare the array into
|
| 574 |
+
`input_values`, the [`AutoFeatureExtractor`] should be used for padding
|
| 575 |
+
and conversion into a tensor of type `torch.FloatTensor`.
|
| 576 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 577 |
+
Mask to avoid performing attention on padding indices in `input_values`. Mask values selected in `[0, 1]`:
|
| 578 |
+
- 1 for tokens that are **not masked**,
|
| 579 |
+
- 0 for tokens that are **masked**.
|
| 580 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 581 |
+
"""
|
| 582 |
+
input_values = input_values.unsqueeze(1)
|
| 583 |
+
hidden_states = nn.functional.tanh(self.conv1(input_values))
|
| 584 |
+
hidden_states = self.groupnorm(hidden_states)
|
| 585 |
+
hidden_states = nn.functional.gelu(self.conv2(hidden_states))
|
| 586 |
+
hidden_states = nn.functional.gelu(self.conv3(hidden_states))
|
| 587 |
+
hidden_states = hidden_states.permute(0, 2, 1)
|
| 588 |
+
|
| 589 |
+
# attention mask downsampling
|
| 590 |
+
output_attention_mask = None
|
| 591 |
+
if attention_mask is not None:
|
| 592 |
+
mask_len = self._get_feat_extract_output_lengths(attention_mask.shape[-1])
|
| 593 |
+
downsample_stride = 64 * 3 * 2 # conv strides
|
| 594 |
+
attention_mask = attention_mask[..., ::downsample_stride][..., :mask_len]
|
| 595 |
+
output_attention_mask = attention_mask
|
| 596 |
+
|
| 597 |
+
attention_mask = create_bidirectional_mask(
|
| 598 |
+
config=self.config,
|
| 599 |
+
inputs_embeds=hidden_states,
|
| 600 |
+
attention_mask=attention_mask,
|
| 601 |
+
encoder_hidden_states=hidden_states,
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
position_ids = torch.arange(0, hidden_states.shape[1], device=hidden_states.device).unsqueeze(0)
|
| 605 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
|
| 606 |
+
|
| 607 |
+
for encoder_layer in self.layers:
|
| 608 |
+
hidden_states = encoder_layer(
|
| 609 |
+
hidden_states,
|
| 610 |
+
attention_mask=attention_mask,
|
| 611 |
+
position_ids=position_ids,
|
| 612 |
+
position_embeddings=position_embeddings,
|
| 613 |
+
**kwargs,
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 617 |
+
|
| 618 |
+
return MoonshineEncoderModelOutput(
|
| 619 |
+
last_hidden_state=hidden_states,
|
| 620 |
+
attention_mask=output_attention_mask.int() if output_attention_mask is not None else None,
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
@auto_docstring
|
| 625 |
+
class MoonshineDecoder(MoonshinePreTrainedModel):
|
| 626 |
+
main_input_name = "input_ids"
|
| 627 |
+
_can_record_outputs = {
|
| 628 |
+
"attentions": OutputRecorder(MoonshineAttention, index=1, layer_name="self_attn"),
|
| 629 |
+
"hidden_states": MoonshineDecoderLayer,
|
| 630 |
+
"cross_attentions": OutputRecorder(MoonshineAttention, index=1, layer_name="encoder_attn"),
|
| 631 |
+
}
|
| 632 |
+
|
| 633 |
+
def __init__(self, config: MoonshineConfig):
|
| 634 |
+
super().__init__(config)
|
| 635 |
+
self.padding_idx = config.pad_token_id
|
| 636 |
+
self.vocab_size = config.vocab_size
|
| 637 |
+
|
| 638 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 639 |
+
self.layers = nn.ModuleList([MoonshineDecoderLayer(config, idx) for idx in range(config.num_hidden_layers)])
|
| 640 |
+
self.norm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 641 |
+
self.rotary_emb = MoonshineRotaryEmbedding(config=config)
|
| 642 |
+
self.gradient_checkpointing = False
|
| 643 |
+
|
| 644 |
+
# Initialize weights and apply final processing
|
| 645 |
+
self.post_init()
|
| 646 |
+
|
| 647 |
+
@merge_with_config_defaults
|
| 648 |
+
@capture_outputs
|
| 649 |
+
def forward(
|
| 650 |
+
self,
|
| 651 |
+
input_ids: torch.LongTensor | None = None,
|
| 652 |
+
attention_mask: torch.Tensor | None = None,
|
| 653 |
+
position_ids: torch.LongTensor | None = None,
|
| 654 |
+
past_key_values: Cache | None = None,
|
| 655 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 656 |
+
use_cache: bool | None = None,
|
| 657 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 658 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 659 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 660 |
+
) -> tuple | BaseModelOutputWithPast:
|
| 661 |
+
r"""
|
| 662 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 663 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 664 |
+
of the decoder.
|
| 665 |
+
encoder_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 666 |
+
Mask to avoid performing attention on padding indices in `encoder_hidden_states`. Mask values selected in `[0, 1]`:
|
| 667 |
+
- 1 for tokens that are **not masked**,
|
| 668 |
+
- 0 for tokens that are **masked**.
|
| 669 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 670 |
+
"""
|
| 671 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 672 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 673 |
+
|
| 674 |
+
if inputs_embeds is None:
|
| 675 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 676 |
+
|
| 677 |
+
if use_cache and past_key_values is None:
|
| 678 |
+
past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
|
| 679 |
+
|
| 680 |
+
if position_ids is None:
|
| 681 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 682 |
+
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
|
| 683 |
+
position_ids = position_ids.unsqueeze(0)
|
| 684 |
+
|
| 685 |
+
causal_mask = create_causal_mask(
|
| 686 |
+
config=self.config,
|
| 687 |
+
inputs_embeds=inputs_embeds,
|
| 688 |
+
attention_mask=attention_mask,
|
| 689 |
+
past_key_values=past_key_values,
|
| 690 |
+
position_ids=position_ids,
|
| 691 |
+
)
|
| 692 |
+
encoder_attention_mask = create_bidirectional_mask(
|
| 693 |
+
config=self.config,
|
| 694 |
+
inputs_embeds=inputs_embeds,
|
| 695 |
+
attention_mask=encoder_attention_mask,
|
| 696 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 697 |
+
)
|
| 698 |
+
|
| 699 |
+
hidden_states = inputs_embeds
|
| 700 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
|
| 701 |
+
|
| 702 |
+
for decoder_layer in self.layers:
|
| 703 |
+
hidden_states = decoder_layer(
|
| 704 |
+
hidden_states,
|
| 705 |
+
causal_mask,
|
| 706 |
+
encoder_hidden_states, # as a positional argument for gradient checkpointing
|
| 707 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 708 |
+
position_ids=position_ids,
|
| 709 |
+
past_key_values=past_key_values,
|
| 710 |
+
use_cache=use_cache,
|
| 711 |
+
position_embeddings=position_embeddings,
|
| 712 |
+
**kwargs,
|
| 713 |
+
)
|
| 714 |
+
|
| 715 |
+
hidden_states = self.norm(hidden_states)
|
| 716 |
+
|
| 717 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 718 |
+
last_hidden_state=hidden_states,
|
| 719 |
+
past_key_values=past_key_values if use_cache else None,
|
| 720 |
+
)
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
@auto_docstring
|
| 724 |
+
class MoonshineModel(MoonshinePreTrainedModel):
|
| 725 |
+
def __init__(self, config: MoonshineConfig):
|
| 726 |
+
super().__init__(config)
|
| 727 |
+
|
| 728 |
+
self.encoder = MoonshineEncoder(config)
|
| 729 |
+
self.decoder = MoonshineDecoder(config)
|
| 730 |
+
# Initialize weights and apply final processing
|
| 731 |
+
self.post_init()
|
| 732 |
+
|
| 733 |
+
def get_input_embeddings(self):
|
| 734 |
+
return self.decoder.embed_tokens
|
| 735 |
+
|
| 736 |
+
def set_input_embeddings(self, value):
|
| 737 |
+
self.decoder.embed_tokens = value
|
| 738 |
+
|
| 739 |
+
def freeze_encoder(self):
|
| 740 |
+
"""
|
| 741 |
+
Calling this function will disable the gradient computation for the Moonshine encoder so that its parameters will
|
| 742 |
+
not be updated during training.
|
| 743 |
+
"""
|
| 744 |
+
self.encoder._freeze_parameters()
|
| 745 |
+
|
| 746 |
+
def _mask_input_features(self):
|
| 747 |
+
"""
|
| 748 |
+
Masks extracted features along time axis and/or along feature axis according to
|
| 749 |
+
[SpecAugment](https://huggingface.co/papers/1904.08779).
|
| 750 |
+
"""
|
| 751 |
+
raise AttributeError("Not needed for Moonshine")
|
| 752 |
+
|
| 753 |
+
@can_return_tuple
|
| 754 |
+
@auto_docstring
|
| 755 |
+
def forward(
|
| 756 |
+
self,
|
| 757 |
+
input_values: torch.FloatTensor | None = None,
|
| 758 |
+
attention_mask: torch.LongTensor | None = None,
|
| 759 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 760 |
+
decoder_attention_mask: torch.LongTensor | None = None,
|
| 761 |
+
encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
|
| 762 |
+
past_key_values: EncoderDecoderCache | None = None,
|
| 763 |
+
decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
|
| 764 |
+
decoder_position_ids: tuple[torch.LongTensor] | None = None,
|
| 765 |
+
use_cache: bool | None = None,
|
| 766 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 767 |
+
) -> Seq2SeqModelOutput:
|
| 768 |
+
r"""
|
| 769 |
+
input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
|
| 770 |
+
Float values of the raw speech waveform. Raw speech waveform can be
|
| 771 |
+
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
|
| 772 |
+
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
|
| 773 |
+
the soundfile library (`pip install soundfile`). To prepare the array into
|
| 774 |
+
`input_values`, the [`AutoFeatureExtractor`] should be used for padding
|
| 775 |
+
and conversion into a tensor of type `torch.FloatTensor`.
|
| 776 |
+
decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
|
| 777 |
+
Indices of positions of each input sequence tokens in the position embeddings.
|
| 778 |
+
Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
|
| 779 |
+
|
| 780 |
+
Example:
|
| 781 |
+
|
| 782 |
+
```python
|
| 783 |
+
>>> import torch
|
| 784 |
+
>>> from transformers import AutoFeatureExtractor, MoonshineModel
|
| 785 |
+
>>> from datasets import load_dataset
|
| 786 |
+
|
| 787 |
+
>>> model = MoonshineModel.from_pretrained("UsefulSensors/moonshine-tiny")
|
| 788 |
+
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("UsefulSensors/moonshine-tiny")
|
| 789 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 790 |
+
>>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
|
| 791 |
+
>>> input_values = inputs.input_values
|
| 792 |
+
>>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
|
| 793 |
+
>>> last_hidden_state = model(input_values, decoder_input_ids=decoder_input_ids).last_hidden_state
|
| 794 |
+
>>> list(last_hidden_state.shape)
|
| 795 |
+
[1, 2, 288]
|
| 796 |
+
```
|
| 797 |
+
"""
|
| 798 |
+
if encoder_outputs is None:
|
| 799 |
+
encoder_outputs: BaseModelOutput = self.encoder(input_values, attention_mask=attention_mask, **kwargs)
|
| 800 |
+
|
| 801 |
+
decoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.decoder(
|
| 802 |
+
input_ids=decoder_input_ids,
|
| 803 |
+
attention_mask=decoder_attention_mask,
|
| 804 |
+
encoder_hidden_states=encoder_outputs.last_hidden_state,
|
| 805 |
+
encoder_attention_mask=encoder_outputs.attention_mask,
|
| 806 |
+
past_key_values=past_key_values,
|
| 807 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 808 |
+
position_ids=decoder_position_ids,
|
| 809 |
+
use_cache=use_cache,
|
| 810 |
+
**kwargs,
|
| 811 |
+
)
|
| 812 |
+
|
| 813 |
+
return Seq2SeqModelOutput(
|
| 814 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 815 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 816 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 817 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 818 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 819 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 820 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 821 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
|
| 826 |
+
"""
|
| 827 |
+
Shift input ids one token to the right.
|
| 828 |
+
"""
|
| 829 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 830 |
+
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
|
| 831 |
+
shifted_input_ids[:, 0] = decoder_start_token_id
|
| 832 |
+
|
| 833 |
+
if pad_token_id is None:
|
| 834 |
+
raise ValueError("self.model.config.pad_token_id has to be defined.")
|
| 835 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 836 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
|
| 837 |
+
|
| 838 |
+
return shifted_input_ids
|
| 839 |
+
|
| 840 |
+
|
| 841 |
+
@auto_docstring(
|
| 842 |
+
custom_intro="""
|
| 843 |
+
The Moonshine Model with a language modeling head. Can be used for automatic speech recognition.
|
| 844 |
+
"""
|
| 845 |
+
)
|
| 846 |
+
class MoonshineForConditionalGeneration(MoonshinePreTrainedModel, GenerationMixin):
|
| 847 |
+
_tied_weights_keys = {"proj_out.weight": "model.decoder.embed_tokens.weight"}
|
| 848 |
+
|
| 849 |
+
def __init__(self, config: MoonshineConfig):
|
| 850 |
+
super().__init__(config)
|
| 851 |
+
self.model = MoonshineModel(config)
|
| 852 |
+
self.proj_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 853 |
+
|
| 854 |
+
# Initialize weights and apply final processing
|
| 855 |
+
self.post_init()
|
| 856 |
+
|
| 857 |
+
def get_output_embeddings(self):
|
| 858 |
+
return self.proj_out
|
| 859 |
+
|
| 860 |
+
def set_output_embeddings(self, new_embeddings):
|
| 861 |
+
self.proj_out = new_embeddings
|
| 862 |
+
|
| 863 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 864 |
+
return self.model.get_input_embeddings()
|
| 865 |
+
|
| 866 |
+
@can_return_tuple
|
| 867 |
+
@auto_docstring
|
| 868 |
+
def forward(
|
| 869 |
+
self,
|
| 870 |
+
input_values: torch.FloatTensor | None = None,
|
| 871 |
+
attention_mask: torch.LongTensor | None = None,
|
| 872 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 873 |
+
decoder_attention_mask: torch.LongTensor | None = None,
|
| 874 |
+
encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
|
| 875 |
+
past_key_values: EncoderDecoderCache | None = None,
|
| 876 |
+
decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
|
| 877 |
+
decoder_position_ids: tuple[torch.LongTensor] | None = None,
|
| 878 |
+
use_cache: bool | None = None,
|
| 879 |
+
labels: torch.LongTensor | None = None,
|
| 880 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 881 |
+
) -> Seq2SeqLMOutput:
|
| 882 |
+
r"""
|
| 883 |
+
input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
|
| 884 |
+
Float values of the raw speech waveform. Raw speech waveform can be
|
| 885 |
+
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
|
| 886 |
+
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
|
| 887 |
+
the soundfile library (`pip install soundfile`). To prepare the array into
|
| 888 |
+
`input_values`, the [`AutoFeatureExtractor`] should be used for padding
|
| 889 |
+
and conversion into a tensor of type `torch.FloatTensor`.
|
| 890 |
+
decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
|
| 891 |
+
Indices of positions of each input sequence tokens in the position embeddings.
|
| 892 |
+
Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
|
| 893 |
+
|
| 894 |
+
Example:
|
| 895 |
+
|
| 896 |
+
```python
|
| 897 |
+
>>> import torch
|
| 898 |
+
>>> from transformers import AutoProcessor, MoonshineForConditionalGeneration
|
| 899 |
+
>>> from datasets import load_dataset
|
| 900 |
+
|
| 901 |
+
>>> processor = AutoProcessor.from_pretrained("UsefulSensors/moonshine-tiny")
|
| 902 |
+
>>> model = MoonshineForConditionalGeneration.from_pretrained("UsefulSensors/moonshine-tiny")
|
| 903 |
+
|
| 904 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 905 |
+
|
| 906 |
+
>>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
|
| 907 |
+
>>> input_values = inputs.input_values
|
| 908 |
+
|
| 909 |
+
>>> generated_ids = model.generate(input_values, max_new_tokens=100)
|
| 910 |
+
|
| 911 |
+
>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 912 |
+
>>> transcription
|
| 913 |
+
'Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
|
| 914 |
+
```"""
|
| 915 |
+
|
| 916 |
+
if labels is not None:
|
| 917 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 918 |
+
decoder_input_ids = shift_tokens_right(
|
| 919 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 920 |
+
)
|
| 921 |
+
|
| 922 |
+
outputs: Seq2SeqModelOutput = self.model(
|
| 923 |
+
input_values,
|
| 924 |
+
attention_mask=attention_mask,
|
| 925 |
+
decoder_input_ids=decoder_input_ids,
|
| 926 |
+
encoder_outputs=encoder_outputs,
|
| 927 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 928 |
+
past_key_values=past_key_values,
|
| 929 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 930 |
+
decoder_position_ids=decoder_position_ids,
|
| 931 |
+
use_cache=use_cache,
|
| 932 |
+
**kwargs,
|
| 933 |
+
)
|
| 934 |
+
logits = self.proj_out(outputs.last_hidden_state)
|
| 935 |
+
|
| 936 |
+
loss = None
|
| 937 |
+
if labels is not None:
|
| 938 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size)
|
| 939 |
+
|
| 940 |
+
return Seq2SeqLMOutput(
|
| 941 |
+
loss=loss,
|
| 942 |
+
logits=logits,
|
| 943 |
+
past_key_values=outputs.past_key_values,
|
| 944 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 945 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 946 |
+
cross_attentions=outputs.cross_attentions,
|
| 947 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 948 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 949 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 950 |
+
)
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
__all__ = ["MoonshineModel", "MoonshinePreTrainedModel", "MoonshineForConditionalGeneration"]
|
lib/python3.11/site-packages/transformers/models/moonshine/modular_moonshine.py
ADDED
|
@@ -0,0 +1,795 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from collections.abc import Callable
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
from huggingface_hub.dataclasses import strict
|
| 21 |
+
|
| 22 |
+
from ...activations import ACT2FN
|
| 23 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 24 |
+
from ...configuration_utils import PreTrainedConfig
|
| 25 |
+
from ...generation import GenerationMixin
|
| 26 |
+
from ...masking_utils import create_bidirectional_mask, create_causal_mask
|
| 27 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 28 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 29 |
+
from ...modeling_outputs import (
|
| 30 |
+
BaseModelOutput,
|
| 31 |
+
BaseModelOutputWithPast,
|
| 32 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 33 |
+
Seq2SeqLMOutput,
|
| 34 |
+
Seq2SeqModelOutput,
|
| 35 |
+
)
|
| 36 |
+
from ...modeling_rope_utils import RopeParameters
|
| 37 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 38 |
+
from ...processing_utils import Unpack
|
| 39 |
+
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
|
| 40 |
+
from ...utils.generic import merge_with_config_defaults
|
| 41 |
+
from ...utils.output_capturing import OutputRecorder, capture_outputs
|
| 42 |
+
from ..glm.modeling_glm import GlmAttention, GlmRotaryEmbedding, apply_rotary_pos_emb
|
| 43 |
+
from ..llama.modeling_llama import LlamaDecoderLayer, LlamaModel, eager_attention_forward
|
| 44 |
+
from ..whisper.modeling_whisper import WhisperModel, shift_tokens_right
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
logger = logging.get_logger(__name__)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@auto_docstring(checkpoint="UsefulSensors/moonshine-tiny")
|
| 51 |
+
@strict
|
| 52 |
+
class MoonshineConfig(PreTrainedConfig):
|
| 53 |
+
r"""
|
| 54 |
+
encoder_num_key_value_heads (`int`, *optional*):
|
| 55 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 56 |
+
`encoder_num_key_value_heads=encoder_num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 57 |
+
`encoder_num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 58 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 59 |
+
by meanpooling all the original heads within that group. For more details, check out [this
|
| 60 |
+
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
|
| 61 |
+
`num_attention_heads`.
|
| 62 |
+
decoder_num_key_value_heads (`int`, *optional*):
|
| 63 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 64 |
+
`decoder_num_key_value_heads=decoder_num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 65 |
+
`decoder_num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 66 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 67 |
+
by meanpooling all the original heads within that group. For more details, check out [this
|
| 68 |
+
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
|
| 69 |
+
`decoder_num_attention_heads`.
|
| 70 |
+
pad_head_dim_to_multiple_of (`int`, *optional*):
|
| 71 |
+
Pad head dimension in encoder and decoder to the next multiple of this value. Necessary for using certain
|
| 72 |
+
optimized attention implementations.
|
| 73 |
+
encoder_hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 74 |
+
The non-linear activation function (function or string) in the encoder.
|
| 75 |
+
decoder_hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 76 |
+
The non-linear activation function (function or string) in the decoder.
|
| 77 |
+
|
| 78 |
+
Example:
|
| 79 |
+
|
| 80 |
+
```python
|
| 81 |
+
>>> from transformers import MoonshineModel, MoonshineConfig
|
| 82 |
+
|
| 83 |
+
>>> # Initializing a Moonshine style configuration
|
| 84 |
+
>>> configuration = MoonshineConfig().from_pretrained("UsefulSensors/moonshine-tiny")
|
| 85 |
+
|
| 86 |
+
>>> # Initializing a model from the configuration
|
| 87 |
+
>>> model = MoonshineModel(configuration)
|
| 88 |
+
|
| 89 |
+
>>> # Accessing the model configuration
|
| 90 |
+
>>> configuration = model.config
|
| 91 |
+
```"""
|
| 92 |
+
|
| 93 |
+
model_type = "moonshine"
|
| 94 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 95 |
+
attribute_map = {
|
| 96 |
+
"num_key_value_heads": "decoder_num_key_value_heads",
|
| 97 |
+
"num_attention_heads": "decoder_num_attention_heads",
|
| 98 |
+
"num_hidden_layers": "decoder_num_hidden_layers",
|
| 99 |
+
"hidden_act": "decoder_hidden_act",
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
vocab_size: int = 32768
|
| 103 |
+
hidden_size: int = 288
|
| 104 |
+
intermediate_size: int = 1152
|
| 105 |
+
encoder_num_hidden_layers: int = 6
|
| 106 |
+
decoder_num_hidden_layers: int = 6
|
| 107 |
+
encoder_num_attention_heads: int = 8
|
| 108 |
+
decoder_num_attention_heads: int = 8
|
| 109 |
+
encoder_num_key_value_heads: int | None = None
|
| 110 |
+
decoder_num_key_value_heads: int | None = None
|
| 111 |
+
pad_head_dim_to_multiple_of: int | None = None
|
| 112 |
+
encoder_hidden_act: str = "gelu"
|
| 113 |
+
decoder_hidden_act: str = "silu"
|
| 114 |
+
max_position_embeddings: int = 512
|
| 115 |
+
initializer_range: float = 0.02
|
| 116 |
+
decoder_start_token_id: int = 1
|
| 117 |
+
use_cache: bool = True
|
| 118 |
+
rope_parameters: RopeParameters | dict | None = None
|
| 119 |
+
is_encoder_decoder: bool = True
|
| 120 |
+
attention_bias: bool = False
|
| 121 |
+
attention_dropout: float | int = 0.0
|
| 122 |
+
bos_token_id: int | None = 1
|
| 123 |
+
eos_token_id: int | list[int] | None = 2
|
| 124 |
+
pad_token_id: int | None = None
|
| 125 |
+
tie_word_embeddings: bool = True
|
| 126 |
+
|
| 127 |
+
def __post_init__(self, **kwargs):
|
| 128 |
+
if self.encoder_num_key_value_heads is None:
|
| 129 |
+
self.encoder_num_key_value_heads = self.encoder_num_attention_heads
|
| 130 |
+
|
| 131 |
+
if self.decoder_num_key_value_heads is None:
|
| 132 |
+
self.decoder_num_key_value_heads = self.decoder_num_attention_heads
|
| 133 |
+
|
| 134 |
+
kwargs.setdefault("partial_rotary_factor", 0.9) # assign default for BC
|
| 135 |
+
super().__post_init__(**kwargs)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
@auto_docstring(
|
| 139 |
+
custom_intro="""
|
| 140 |
+
Extends [~modeling_outputs.BaseModelOutput] to include the output attention mask since sequence length is not preserved in the model's forward.
|
| 141 |
+
"""
|
| 142 |
+
)
|
| 143 |
+
@dataclass
|
| 144 |
+
class MoonshineEncoderModelOutput(BaseModelOutput):
|
| 145 |
+
r"""
|
| 146 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 147 |
+
Mask to avoid performing attention on padding token indices after sequence compression. Returned because the
|
| 148 |
+
sequence length may differ from the input sequence length. Mask values selected in `[0, 1]`:
|
| 149 |
+
|
| 150 |
+
- 1 for tokens that are **not masked**,
|
| 151 |
+
- 0 for tokens that are **masked**.
|
| 152 |
+
"""
|
| 153 |
+
|
| 154 |
+
attention_mask: torch.Tensor | None = None
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class MoonshineEncoderMLP(nn.Module):
|
| 158 |
+
def __init__(self, config, hidden_act):
|
| 159 |
+
super().__init__()
|
| 160 |
+
self.config = config
|
| 161 |
+
self.activation_fn = ACT2FN[hidden_act]
|
| 162 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 163 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 164 |
+
|
| 165 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 166 |
+
hidden_states = self.fc1(hidden_states)
|
| 167 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 168 |
+
hidden_states = self.fc2(hidden_states)
|
| 169 |
+
return hidden_states
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class MoonshineDecoderMLP(nn.Module):
|
| 173 |
+
def __init__(self, config, hidden_act):
|
| 174 |
+
super().__init__()
|
| 175 |
+
self.config = config
|
| 176 |
+
self.activation_fn = ACT2FN[hidden_act]
|
| 177 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size * 2)
|
| 178 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 179 |
+
|
| 180 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 181 |
+
hidden_states = self.fc1(hidden_states)
|
| 182 |
+
hidden_states, gate = hidden_states.chunk(2, dim=-1)
|
| 183 |
+
hidden_states = self.activation_fn(gate) * hidden_states
|
| 184 |
+
hidden_states = self.fc2(hidden_states)
|
| 185 |
+
return hidden_states
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class MoonshineRotaryEmbedding(GlmRotaryEmbedding):
|
| 189 |
+
pass
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class MoonshineAttention(GlmAttention):
|
| 193 |
+
def __init__(
|
| 194 |
+
self,
|
| 195 |
+
config: MoonshineConfig,
|
| 196 |
+
layer_idx: int,
|
| 197 |
+
is_causal: bool,
|
| 198 |
+
num_attention_heads: int,
|
| 199 |
+
num_key_value_heads: int,
|
| 200 |
+
):
|
| 201 |
+
config.update({"num_attention_heads": num_attention_heads, "num_key_value_heads": num_key_value_heads})
|
| 202 |
+
super().__init__(config, layer_idx)
|
| 203 |
+
self.is_causal = is_causal
|
| 204 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 205 |
+
|
| 206 |
+
# Pad head dimension to the next specified multiple.
|
| 207 |
+
if self.config.pad_head_dim_to_multiple_of is not None:
|
| 208 |
+
target_multiple = self.config.pad_head_dim_to_multiple_of
|
| 209 |
+
target_head_dim = target_multiple * ((self.head_dim + target_multiple - 1) // target_multiple)
|
| 210 |
+
self.head_dim_padding = target_head_dim - self.head_dim
|
| 211 |
+
else:
|
| 212 |
+
self.head_dim_padding = 0
|
| 213 |
+
|
| 214 |
+
def forward(
|
| 215 |
+
self,
|
| 216 |
+
hidden_states: torch.Tensor,
|
| 217 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 218 |
+
attention_mask: torch.Tensor | None = None,
|
| 219 |
+
past_key_values: Cache | None = None,
|
| 220 |
+
key_value_states: torch.Tensor | None = None,
|
| 221 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 222 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
|
| 223 |
+
bsz, q_len = hidden_states.shape[:-1]
|
| 224 |
+
|
| 225 |
+
query_states = (
|
| 226 |
+
self.q_proj(hidden_states).view(bsz, q_len, self.config.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
is_cross_attention = key_value_states is not None
|
| 230 |
+
if past_key_values is not None:
|
| 231 |
+
is_updated = past_key_values.is_updated.get(self.layer_idx)
|
| 232 |
+
if is_cross_attention:
|
| 233 |
+
# after the first generated id, we can subsequently re-use all key/value_states from cache
|
| 234 |
+
past_key_values.is_updated[self.layer_idx] = True
|
| 235 |
+
past_key_values = past_key_values.cross_attention_cache
|
| 236 |
+
else:
|
| 237 |
+
past_key_values = past_key_values.self_attention_cache
|
| 238 |
+
|
| 239 |
+
# use key_value_states if cross attention
|
| 240 |
+
current_states = key_value_states if key_value_states is not None else hidden_states
|
| 241 |
+
if is_cross_attention and past_key_values and is_updated:
|
| 242 |
+
key_states = past_key_values.layers[self.layer_idx].keys
|
| 243 |
+
value_states = past_key_values.layers[self.layer_idx].values
|
| 244 |
+
else:
|
| 245 |
+
key_states = (
|
| 246 |
+
self.k_proj(current_states)
|
| 247 |
+
.view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
|
| 248 |
+
.transpose(1, 2)
|
| 249 |
+
)
|
| 250 |
+
value_states = (
|
| 251 |
+
self.v_proj(current_states)
|
| 252 |
+
.view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
|
| 253 |
+
.transpose(1, 2)
|
| 254 |
+
)
|
| 255 |
+
if is_cross_attention and past_key_values is not None:
|
| 256 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 257 |
+
|
| 258 |
+
if not is_cross_attention:
|
| 259 |
+
cos, sin = position_embeddings
|
| 260 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 261 |
+
|
| 262 |
+
if past_key_values is not None:
|
| 263 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 264 |
+
|
| 265 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 266 |
+
self.config._attn_implementation, eager_attention_forward
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
is_causal = self.is_causal and attention_mask is None and q_len > 1
|
| 270 |
+
|
| 271 |
+
if self.head_dim_padding > 0:
|
| 272 |
+
query_states = torch.nn.functional.pad(query_states, (0, self.head_dim_padding))
|
| 273 |
+
key_states = torch.nn.functional.pad(key_states, (0, self.head_dim_padding))
|
| 274 |
+
value_states = torch.nn.functional.pad(value_states, (0, self.head_dim_padding))
|
| 275 |
+
|
| 276 |
+
attn_output, attn_weights = attention_interface(
|
| 277 |
+
self,
|
| 278 |
+
query_states,
|
| 279 |
+
key_states,
|
| 280 |
+
value_states,
|
| 281 |
+
attention_mask,
|
| 282 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 283 |
+
scaling=self.scaling,
|
| 284 |
+
is_causal=is_causal,
|
| 285 |
+
**kwargs,
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
if self.head_dim_padding > 0:
|
| 289 |
+
attn_output = attn_output[..., : -self.head_dim_padding]
|
| 290 |
+
|
| 291 |
+
attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
|
| 292 |
+
attn_output = self.o_proj(attn_output)
|
| 293 |
+
return attn_output, attn_weights
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
class MoonshineEncoderLayer(LlamaDecoderLayer):
|
| 297 |
+
def __init__(self, config: MoonshineConfig, layer_idx: int):
|
| 298 |
+
super().__init__(config, layer_idx)
|
| 299 |
+
|
| 300 |
+
self.self_attn = MoonshineAttention(
|
| 301 |
+
config=config,
|
| 302 |
+
layer_idx=layer_idx,
|
| 303 |
+
is_causal=False,
|
| 304 |
+
num_attention_heads=config.encoder_num_attention_heads,
|
| 305 |
+
num_key_value_heads=config.encoder_num_key_value_heads,
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
self.mlp = MoonshineEncoderMLP(config, config.encoder_hidden_act)
|
| 309 |
+
self.input_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 310 |
+
self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
class MoonshineDecoderLayer(GradientCheckpointingLayer):
|
| 314 |
+
def __init__(self, config: MoonshineConfig, layer_idx: int | None = None):
|
| 315 |
+
super().__init__()
|
| 316 |
+
self.hidden_size = config.hidden_size
|
| 317 |
+
|
| 318 |
+
self.self_attn = MoonshineAttention(
|
| 319 |
+
config=config,
|
| 320 |
+
layer_idx=layer_idx,
|
| 321 |
+
is_causal=True,
|
| 322 |
+
num_attention_heads=config.num_attention_heads,
|
| 323 |
+
num_key_value_heads=config.num_key_value_heads,
|
| 324 |
+
)
|
| 325 |
+
self.encoder_attn = MoonshineAttention(
|
| 326 |
+
config=config,
|
| 327 |
+
layer_idx=layer_idx,
|
| 328 |
+
is_causal=False,
|
| 329 |
+
num_attention_heads=config.num_attention_heads,
|
| 330 |
+
num_key_value_heads=config.num_key_value_heads,
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
self.mlp = MoonshineDecoderMLP(config, config.hidden_act)
|
| 334 |
+
self.input_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 335 |
+
self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 336 |
+
self.final_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 337 |
+
|
| 338 |
+
def forward(
|
| 339 |
+
self,
|
| 340 |
+
hidden_states: torch.Tensor,
|
| 341 |
+
attention_mask: torch.Tensor | None = None,
|
| 342 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 343 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 344 |
+
position_ids: torch.LongTensor | None = None,
|
| 345 |
+
encoder_position_ids: torch.LongTensor | None = None,
|
| 346 |
+
past_key_values: Cache | None = None,
|
| 347 |
+
use_cache: bool | None = False,
|
| 348 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 349 |
+
encoder_position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 350 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 351 |
+
) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
|
| 352 |
+
residual = hidden_states
|
| 353 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 354 |
+
|
| 355 |
+
hidden_states, _ = self.self_attn(
|
| 356 |
+
hidden_states=hidden_states,
|
| 357 |
+
attention_mask=attention_mask,
|
| 358 |
+
position_ids=position_ids,
|
| 359 |
+
past_key_values=past_key_values,
|
| 360 |
+
use_cache=use_cache,
|
| 361 |
+
position_embeddings=position_embeddings,
|
| 362 |
+
**kwargs,
|
| 363 |
+
)
|
| 364 |
+
hidden_states = residual + hidden_states
|
| 365 |
+
|
| 366 |
+
if encoder_hidden_states is not None:
|
| 367 |
+
residual = hidden_states
|
| 368 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 369 |
+
hidden_states, _ = self.encoder_attn(
|
| 370 |
+
hidden_states=hidden_states,
|
| 371 |
+
key_value_states=encoder_hidden_states,
|
| 372 |
+
attention_mask=encoder_attention_mask,
|
| 373 |
+
past_key_values=past_key_values,
|
| 374 |
+
use_cache=use_cache,
|
| 375 |
+
)
|
| 376 |
+
hidden_states = residual + hidden_states
|
| 377 |
+
|
| 378 |
+
residual = hidden_states
|
| 379 |
+
hidden_states = self.final_layernorm(hidden_states)
|
| 380 |
+
hidden_states = self.mlp(hidden_states)
|
| 381 |
+
hidden_states = residual + hidden_states
|
| 382 |
+
return hidden_states
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
@auto_docstring
|
| 386 |
+
class MoonshinePreTrainedModel(PreTrainedModel):
|
| 387 |
+
config: MoonshineConfig
|
| 388 |
+
base_model_prefix = "model"
|
| 389 |
+
main_input_name = "input_values"
|
| 390 |
+
input_modalities = "audio"
|
| 391 |
+
supports_gradient_checkpointing = True
|
| 392 |
+
_no_split_modules = ["MoonshineEncoderLayer", "MoonshineDecoderLayer"]
|
| 393 |
+
_supports_flash_attn = True
|
| 394 |
+
_supports_sdpa = True
|
| 395 |
+
|
| 396 |
+
_can_compile_fullgraph = True
|
| 397 |
+
# TODO arthur, how do we separate when it cross / self coming from different layer?
|
| 398 |
+
|
| 399 |
+
def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
|
| 400 |
+
"""
|
| 401 |
+
Computes the output length of the convolutional layers
|
| 402 |
+
"""
|
| 403 |
+
output_conv1_length = int((input_lengths - 127) / 64 + 1)
|
| 404 |
+
output_conv2_length = int((output_conv1_length - 7) / 3 + 1)
|
| 405 |
+
output_conv3_length = int((output_conv2_length - 3) / 2 + 1)
|
| 406 |
+
|
| 407 |
+
return output_conv3_length
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
class MoonshineEncoder(MoonshinePreTrainedModel):
|
| 411 |
+
"""
|
| 412 |
+
Transformer encoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MoonshineEncoderLayer`]
|
| 413 |
+
|
| 414 |
+
Args:
|
| 415 |
+
config: MoonshineConfig
|
| 416 |
+
"""
|
| 417 |
+
|
| 418 |
+
main_input_name = "input_values"
|
| 419 |
+
_can_record_outputs = {
|
| 420 |
+
"attentions": MoonshineAttention,
|
| 421 |
+
"hidden_states": MoonshineEncoderLayer,
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
def __init__(self, config: MoonshineConfig):
|
| 425 |
+
super().__init__(config)
|
| 426 |
+
self.config = config
|
| 427 |
+
embed_dim = config.hidden_size
|
| 428 |
+
|
| 429 |
+
self.conv1 = nn.Conv1d(1, embed_dim, kernel_size=127, stride=64, bias=False)
|
| 430 |
+
self.conv2 = nn.Conv1d(embed_dim, 2 * embed_dim, kernel_size=7, stride=3)
|
| 431 |
+
self.conv3 = nn.Conv1d(2 * embed_dim, embed_dim, kernel_size=3, stride=2)
|
| 432 |
+
self.groupnorm = nn.GroupNorm(num_groups=1, num_channels=embed_dim, eps=1e-5)
|
| 433 |
+
|
| 434 |
+
self.layers = nn.ModuleList(
|
| 435 |
+
[MoonshineEncoderLayer(config, idx) for idx in range(config.encoder_num_hidden_layers)]
|
| 436 |
+
)
|
| 437 |
+
self.layer_norm = nn.LayerNorm(embed_dim, bias=False)
|
| 438 |
+
self.rotary_emb = MoonshineRotaryEmbedding(config=config)
|
| 439 |
+
self.gradient_checkpointing = False
|
| 440 |
+
self.post_init()
|
| 441 |
+
|
| 442 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 443 |
+
return self.conv1
|
| 444 |
+
|
| 445 |
+
def set_input_embeddings(self, value: nn.Module):
|
| 446 |
+
self.conv1 = value
|
| 447 |
+
|
| 448 |
+
@merge_with_config_defaults
|
| 449 |
+
@capture_outputs
|
| 450 |
+
def forward(
|
| 451 |
+
self,
|
| 452 |
+
input_values: torch.FloatTensor,
|
| 453 |
+
attention_mask: torch.Tensor | None = None,
|
| 454 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 455 |
+
) -> tuple | BaseModelOutputWithPast:
|
| 456 |
+
r"""
|
| 457 |
+
Args:
|
| 458 |
+
input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
|
| 459 |
+
Float values of the raw speech waveform. Raw speech waveform can be
|
| 460 |
+
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
|
| 461 |
+
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
|
| 462 |
+
the soundfile library (`pip install soundfile`). To prepare the array into
|
| 463 |
+
`input_values`, the [`AutoFeatureExtractor`] should be used for padding
|
| 464 |
+
and conversion into a tensor of type `torch.FloatTensor`.
|
| 465 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 466 |
+
Mask to avoid performing attention on padding indices in `input_values`. Mask values selected in `[0, 1]`:
|
| 467 |
+
- 1 for tokens that are **not masked**,
|
| 468 |
+
- 0 for tokens that are **masked**.
|
| 469 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 470 |
+
"""
|
| 471 |
+
input_values = input_values.unsqueeze(1)
|
| 472 |
+
hidden_states = nn.functional.tanh(self.conv1(input_values))
|
| 473 |
+
hidden_states = self.groupnorm(hidden_states)
|
| 474 |
+
hidden_states = nn.functional.gelu(self.conv2(hidden_states))
|
| 475 |
+
hidden_states = nn.functional.gelu(self.conv3(hidden_states))
|
| 476 |
+
hidden_states = hidden_states.permute(0, 2, 1)
|
| 477 |
+
|
| 478 |
+
# attention mask downsampling
|
| 479 |
+
output_attention_mask = None
|
| 480 |
+
if attention_mask is not None:
|
| 481 |
+
mask_len = self._get_feat_extract_output_lengths(attention_mask.shape[-1])
|
| 482 |
+
downsample_stride = 64 * 3 * 2 # conv strides
|
| 483 |
+
attention_mask = attention_mask[..., ::downsample_stride][..., :mask_len]
|
| 484 |
+
output_attention_mask = attention_mask
|
| 485 |
+
|
| 486 |
+
attention_mask = create_bidirectional_mask(
|
| 487 |
+
config=self.config,
|
| 488 |
+
inputs_embeds=hidden_states,
|
| 489 |
+
attention_mask=attention_mask,
|
| 490 |
+
encoder_hidden_states=hidden_states,
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
position_ids = torch.arange(0, hidden_states.shape[1], device=hidden_states.device).unsqueeze(0)
|
| 494 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
|
| 495 |
+
|
| 496 |
+
for encoder_layer in self.layers:
|
| 497 |
+
hidden_states = encoder_layer(
|
| 498 |
+
hidden_states,
|
| 499 |
+
attention_mask=attention_mask,
|
| 500 |
+
position_ids=position_ids,
|
| 501 |
+
position_embeddings=position_embeddings,
|
| 502 |
+
**kwargs,
|
| 503 |
+
)
|
| 504 |
+
|
| 505 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 506 |
+
|
| 507 |
+
return MoonshineEncoderModelOutput(
|
| 508 |
+
last_hidden_state=hidden_states,
|
| 509 |
+
attention_mask=output_attention_mask.int() if output_attention_mask is not None else None,
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
class MoonshineDecoder(LlamaModel):
|
| 514 |
+
main_input_name = "input_ids"
|
| 515 |
+
_can_record_outputs = {
|
| 516 |
+
"attentions": OutputRecorder(MoonshineAttention, index=1, layer_name="self_attn"),
|
| 517 |
+
"hidden_states": MoonshineDecoderLayer,
|
| 518 |
+
"cross_attentions": OutputRecorder(MoonshineAttention, index=1, layer_name="encoder_attn"),
|
| 519 |
+
}
|
| 520 |
+
|
| 521 |
+
def __init__(self, config: MoonshineConfig):
|
| 522 |
+
super().__init__(config)
|
| 523 |
+
self.norm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 524 |
+
self.layers = nn.ModuleList([MoonshineDecoderLayer(config, idx) for idx in range(config.num_hidden_layers)])
|
| 525 |
+
|
| 526 |
+
@merge_with_config_defaults
|
| 527 |
+
@capture_outputs
|
| 528 |
+
def forward(
|
| 529 |
+
self,
|
| 530 |
+
input_ids: torch.LongTensor | None = None,
|
| 531 |
+
attention_mask: torch.Tensor | None = None,
|
| 532 |
+
position_ids: torch.LongTensor | None = None,
|
| 533 |
+
past_key_values: Cache | None = None,
|
| 534 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 535 |
+
use_cache: bool | None = None,
|
| 536 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 537 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 538 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 539 |
+
) -> tuple | BaseModelOutputWithPast:
|
| 540 |
+
r"""
|
| 541 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 542 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 543 |
+
of the decoder.
|
| 544 |
+
encoder_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 545 |
+
Mask to avoid performing attention on padding indices in `encoder_hidden_states`. Mask values selected in `[0, 1]`:
|
| 546 |
+
- 1 for tokens that are **not masked**,
|
| 547 |
+
- 0 for tokens that are **masked**.
|
| 548 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 549 |
+
"""
|
| 550 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 551 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 552 |
+
|
| 553 |
+
if inputs_embeds is None:
|
| 554 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 555 |
+
|
| 556 |
+
if use_cache and past_key_values is None:
|
| 557 |
+
past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
|
| 558 |
+
|
| 559 |
+
if position_ids is None:
|
| 560 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 561 |
+
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
|
| 562 |
+
position_ids = position_ids.unsqueeze(0)
|
| 563 |
+
|
| 564 |
+
causal_mask = create_causal_mask(
|
| 565 |
+
config=self.config,
|
| 566 |
+
inputs_embeds=inputs_embeds,
|
| 567 |
+
attention_mask=attention_mask,
|
| 568 |
+
past_key_values=past_key_values,
|
| 569 |
+
position_ids=position_ids,
|
| 570 |
+
)
|
| 571 |
+
encoder_attention_mask = create_bidirectional_mask(
|
| 572 |
+
config=self.config,
|
| 573 |
+
inputs_embeds=inputs_embeds,
|
| 574 |
+
attention_mask=encoder_attention_mask,
|
| 575 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
hidden_states = inputs_embeds
|
| 579 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
|
| 580 |
+
|
| 581 |
+
for decoder_layer in self.layers:
|
| 582 |
+
hidden_states = decoder_layer(
|
| 583 |
+
hidden_states,
|
| 584 |
+
causal_mask,
|
| 585 |
+
encoder_hidden_states, # as a positional argument for gradient checkpointing
|
| 586 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 587 |
+
position_ids=position_ids,
|
| 588 |
+
past_key_values=past_key_values,
|
| 589 |
+
use_cache=use_cache,
|
| 590 |
+
position_embeddings=position_embeddings,
|
| 591 |
+
**kwargs,
|
| 592 |
+
)
|
| 593 |
+
|
| 594 |
+
hidden_states = self.norm(hidden_states)
|
| 595 |
+
|
| 596 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 597 |
+
last_hidden_state=hidden_states,
|
| 598 |
+
past_key_values=past_key_values if use_cache else None,
|
| 599 |
+
)
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
class MoonshineModel(WhisperModel):
|
| 603 |
+
def _mask_input_features(self):
|
| 604 |
+
raise AttributeError("Not needed for Moonshine")
|
| 605 |
+
|
| 606 |
+
@can_return_tuple
|
| 607 |
+
@auto_docstring
|
| 608 |
+
def forward(
|
| 609 |
+
self,
|
| 610 |
+
input_values: torch.FloatTensor | None = None,
|
| 611 |
+
attention_mask: torch.LongTensor | None = None,
|
| 612 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 613 |
+
decoder_attention_mask: torch.LongTensor | None = None,
|
| 614 |
+
encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
|
| 615 |
+
past_key_values: EncoderDecoderCache | None = None,
|
| 616 |
+
decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
|
| 617 |
+
decoder_position_ids: tuple[torch.LongTensor] | None = None,
|
| 618 |
+
use_cache: bool | None = None,
|
| 619 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 620 |
+
) -> Seq2SeqModelOutput:
|
| 621 |
+
r"""
|
| 622 |
+
input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
|
| 623 |
+
Float values of the raw speech waveform. Raw speech waveform can be
|
| 624 |
+
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
|
| 625 |
+
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
|
| 626 |
+
the soundfile library (`pip install soundfile`). To prepare the array into
|
| 627 |
+
`input_values`, the [`AutoFeatureExtractor`] should be used for padding
|
| 628 |
+
and conversion into a tensor of type `torch.FloatTensor`.
|
| 629 |
+
decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
|
| 630 |
+
Indices of positions of each input sequence tokens in the position embeddings.
|
| 631 |
+
Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
|
| 632 |
+
|
| 633 |
+
Example:
|
| 634 |
+
|
| 635 |
+
```python
|
| 636 |
+
>>> import torch
|
| 637 |
+
>>> from transformers import AutoFeatureExtractor, MoonshineModel
|
| 638 |
+
>>> from datasets import load_dataset
|
| 639 |
+
|
| 640 |
+
>>> model = MoonshineModel.from_pretrained("UsefulSensors/moonshine-tiny")
|
| 641 |
+
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("UsefulSensors/moonshine-tiny")
|
| 642 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 643 |
+
>>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
|
| 644 |
+
>>> input_values = inputs.input_values
|
| 645 |
+
>>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
|
| 646 |
+
>>> last_hidden_state = model(input_values, decoder_input_ids=decoder_input_ids).last_hidden_state
|
| 647 |
+
>>> list(last_hidden_state.shape)
|
| 648 |
+
[1, 2, 288]
|
| 649 |
+
```
|
| 650 |
+
"""
|
| 651 |
+
if encoder_outputs is None:
|
| 652 |
+
encoder_outputs: BaseModelOutput = self.encoder(input_values, attention_mask=attention_mask, **kwargs)
|
| 653 |
+
|
| 654 |
+
decoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.decoder(
|
| 655 |
+
input_ids=decoder_input_ids,
|
| 656 |
+
attention_mask=decoder_attention_mask,
|
| 657 |
+
encoder_hidden_states=encoder_outputs.last_hidden_state,
|
| 658 |
+
encoder_attention_mask=encoder_outputs.attention_mask,
|
| 659 |
+
past_key_values=past_key_values,
|
| 660 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 661 |
+
position_ids=decoder_position_ids,
|
| 662 |
+
use_cache=use_cache,
|
| 663 |
+
**kwargs,
|
| 664 |
+
)
|
| 665 |
+
|
| 666 |
+
return Seq2SeqModelOutput(
|
| 667 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 668 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 669 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 670 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 671 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 672 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 673 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 674 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 675 |
+
)
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
@auto_docstring(
|
| 679 |
+
custom_intro="""
|
| 680 |
+
The Moonshine Model with a language modeling head. Can be used for automatic speech recognition.
|
| 681 |
+
"""
|
| 682 |
+
)
|
| 683 |
+
class MoonshineForConditionalGeneration(MoonshinePreTrainedModel, GenerationMixin):
|
| 684 |
+
_tied_weights_keys = {"proj_out.weight": "model.decoder.embed_tokens.weight"}
|
| 685 |
+
|
| 686 |
+
def __init__(self, config: MoonshineConfig):
|
| 687 |
+
super().__init__(config)
|
| 688 |
+
self.model = MoonshineModel(config)
|
| 689 |
+
self.proj_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 690 |
+
|
| 691 |
+
# Initialize weights and apply final processing
|
| 692 |
+
self.post_init()
|
| 693 |
+
|
| 694 |
+
def get_output_embeddings(self):
|
| 695 |
+
return self.proj_out
|
| 696 |
+
|
| 697 |
+
def set_output_embeddings(self, new_embeddings):
|
| 698 |
+
self.proj_out = new_embeddings
|
| 699 |
+
|
| 700 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 701 |
+
return self.model.get_input_embeddings()
|
| 702 |
+
|
| 703 |
+
@can_return_tuple
|
| 704 |
+
@auto_docstring
|
| 705 |
+
def forward(
|
| 706 |
+
self,
|
| 707 |
+
input_values: torch.FloatTensor | None = None,
|
| 708 |
+
attention_mask: torch.LongTensor | None = None,
|
| 709 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 710 |
+
decoder_attention_mask: torch.LongTensor | None = None,
|
| 711 |
+
encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
|
| 712 |
+
past_key_values: EncoderDecoderCache | None = None,
|
| 713 |
+
decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
|
| 714 |
+
decoder_position_ids: tuple[torch.LongTensor] | None = None,
|
| 715 |
+
use_cache: bool | None = None,
|
| 716 |
+
labels: torch.LongTensor | None = None,
|
| 717 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 718 |
+
) -> Seq2SeqLMOutput:
|
| 719 |
+
r"""
|
| 720 |
+
input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
|
| 721 |
+
Float values of the raw speech waveform. Raw speech waveform can be
|
| 722 |
+
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
|
| 723 |
+
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
|
| 724 |
+
the soundfile library (`pip install soundfile`). To prepare the array into
|
| 725 |
+
`input_values`, the [`AutoFeatureExtractor`] should be used for padding
|
| 726 |
+
and conversion into a tensor of type `torch.FloatTensor`.
|
| 727 |
+
decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
|
| 728 |
+
Indices of positions of each input sequence tokens in the position embeddings.
|
| 729 |
+
Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
|
| 730 |
+
|
| 731 |
+
Example:
|
| 732 |
+
|
| 733 |
+
```python
|
| 734 |
+
>>> import torch
|
| 735 |
+
>>> from transformers import AutoProcessor, MoonshineForConditionalGeneration
|
| 736 |
+
>>> from datasets import load_dataset
|
| 737 |
+
|
| 738 |
+
>>> processor = AutoProcessor.from_pretrained("UsefulSensors/moonshine-tiny")
|
| 739 |
+
>>> model = MoonshineForConditionalGeneration.from_pretrained("UsefulSensors/moonshine-tiny")
|
| 740 |
+
|
| 741 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 742 |
+
|
| 743 |
+
>>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
|
| 744 |
+
>>> input_values = inputs.input_values
|
| 745 |
+
|
| 746 |
+
>>> generated_ids = model.generate(input_values, max_new_tokens=100)
|
| 747 |
+
|
| 748 |
+
>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 749 |
+
>>> transcription
|
| 750 |
+
'Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
|
| 751 |
+
```"""
|
| 752 |
+
|
| 753 |
+
if labels is not None:
|
| 754 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 755 |
+
decoder_input_ids = shift_tokens_right(
|
| 756 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 757 |
+
)
|
| 758 |
+
|
| 759 |
+
outputs: Seq2SeqModelOutput = self.model(
|
| 760 |
+
input_values,
|
| 761 |
+
attention_mask=attention_mask,
|
| 762 |
+
decoder_input_ids=decoder_input_ids,
|
| 763 |
+
encoder_outputs=encoder_outputs,
|
| 764 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 765 |
+
past_key_values=past_key_values,
|
| 766 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 767 |
+
decoder_position_ids=decoder_position_ids,
|
| 768 |
+
use_cache=use_cache,
|
| 769 |
+
**kwargs,
|
| 770 |
+
)
|
| 771 |
+
logits = self.proj_out(outputs.last_hidden_state)
|
| 772 |
+
|
| 773 |
+
loss = None
|
| 774 |
+
if labels is not None:
|
| 775 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size)
|
| 776 |
+
|
| 777 |
+
return Seq2SeqLMOutput(
|
| 778 |
+
loss=loss,
|
| 779 |
+
logits=logits,
|
| 780 |
+
past_key_values=outputs.past_key_values,
|
| 781 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 782 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 783 |
+
cross_attentions=outputs.cross_attentions,
|
| 784 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 785 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 786 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 787 |
+
)
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
__all__ = [
|
| 791 |
+
"MoonshineConfig",
|
| 792 |
+
"MoonshineModel",
|
| 793 |
+
"MoonshinePreTrainedModel",
|
| 794 |
+
"MoonshineForConditionalGeneration",
|
| 795 |
+
]
|
lib/python3.11/site-packages/transformers/models/moonshine_streaming/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 the HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import TYPE_CHECKING
|
| 16 |
+
|
| 17 |
+
from ...utils import _LazyModule
|
| 18 |
+
from ...utils.import_utils import define_import_structure
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING:
|
| 22 |
+
from .configuration_moonshine_streaming import *
|
| 23 |
+
from .modeling_moonshine_streaming import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.11/site-packages/transformers/models/moonshine_streaming/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (817 Bytes). View file
|
|
|
lib/python3.11/site-packages/transformers/models/moonshine_streaming/__pycache__/configuration_moonshine_streaming.cpython-311.pyc
ADDED
|
Binary file (6.93 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/moonshine_streaming/__pycache__/modeling_moonshine_streaming.cpython-311.pyc
ADDED
|
Binary file (64.4 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/moonshine_streaming/__pycache__/modular_moonshine_streaming.cpython-311.pyc
ADDED
|
Binary file (27.5 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/moonshine_streaming/__pycache__/processing_moonshine_streaming.cpython-311.pyc
ADDED
|
Binary file (4.79 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/moonshine_streaming/configuration_moonshine_streaming.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 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 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...modeling_rope_utils import RopeParameters
|
| 20 |
+
from ...utils import auto_docstring
|
| 21 |
+
from ..auto import CONFIG_MAPPING
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@auto_docstring(checkpoint="UsefulSensors/moonshine-streaming-tiny")
|
| 25 |
+
@strict
|
| 26 |
+
class MoonshineStreamingEncoderConfig(PreTrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
sample_rate (`int`, *optional*, defaults to 16000):
|
| 29 |
+
The sample rate of the audio input in Hz.
|
| 30 |
+
frame_ms (`float`, *optional*, defaults to 5.0):
|
| 31 |
+
The frame duration in milliseconds for audio processing.
|
| 32 |
+
sliding_windows (`list[tuple[int, int]]`, *optional*, defaults to `[(16, 4), (16, 4), (16, 0), (16, 0), (16, 4), (16, 4)]`):
|
| 33 |
+
List of sliding window configurations for each encoder layer. Each tuple contains (window_size, shift).
|
| 34 |
+
|
| 35 |
+
```python
|
| 36 |
+
>>> from transformers import MoonshineStreamingEncoder, MoonshineStreamingEncoderConfig
|
| 37 |
+
|
| 38 |
+
>>> # Initializing a Moonshine Streaming encoder configuration
|
| 39 |
+
>>> configuration = MoonshineStreamingEncoderConfig()
|
| 40 |
+
|
| 41 |
+
>>> # Initializing a model from the configuration
|
| 42 |
+
>>> model = MoonshineStreamingEncoder(configuration)
|
| 43 |
+
|
| 44 |
+
>>> # Accessing the model configuration
|
| 45 |
+
>>> configuration = model.config
|
| 46 |
+
```
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
model_type = "moonshine_streaming_encoder"
|
| 50 |
+
|
| 51 |
+
hidden_size: int = 320
|
| 52 |
+
intermediate_size: int = 1280
|
| 53 |
+
hidden_act: str = "gelu"
|
| 54 |
+
num_hidden_layers: int = 6
|
| 55 |
+
num_attention_heads: int = 8
|
| 56 |
+
num_key_value_heads: int = 8
|
| 57 |
+
max_position_embeddings: int = 4096
|
| 58 |
+
attention_dropout: float | int = 0.0
|
| 59 |
+
attention_bias: bool = False
|
| 60 |
+
sample_rate: int = 16000
|
| 61 |
+
frame_ms: float = 5.0
|
| 62 |
+
sliding_windows: tuple[tuple[int, int], ...] | list[list[int, int]] = (
|
| 63 |
+
(16, 4),
|
| 64 |
+
(16, 4),
|
| 65 |
+
(16, 0),
|
| 66 |
+
(16, 0),
|
| 67 |
+
(16, 4),
|
| 68 |
+
(16, 4),
|
| 69 |
+
)
|
| 70 |
+
head_dim: int | None = None
|
| 71 |
+
|
| 72 |
+
def __post_init__(self, **kwargs):
|
| 73 |
+
self.head_dim = self.head_dim if self.head_dim is not None else self.hidden_size // self.num_attention_heads
|
| 74 |
+
self.sliding_windows = [list(window) for window in self.sliding_windows]
|
| 75 |
+
|
| 76 |
+
super().__post_init__(**kwargs)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@auto_docstring(checkpoint="UsefulSensors/moonshine-streaming-tiny")
|
| 80 |
+
@strict
|
| 81 |
+
class MoonshineStreamingConfig(PreTrainedConfig):
|
| 82 |
+
r"""
|
| 83 |
+
pad_head_dim_to_multiple_of (`int`, *optional*):
|
| 84 |
+
If set, the head dimension will be padded to a multiple of this value.
|
| 85 |
+
|
| 86 |
+
```python
|
| 87 |
+
>>> from transformers import MoonshineStreamingModel, MoonshineStreamingConfig
|
| 88 |
+
|
| 89 |
+
>>> # Initializing a Moonshine Streaming configuration
|
| 90 |
+
>>> configuration = MoonshineStreamingConfig()
|
| 91 |
+
|
| 92 |
+
>>> # Initializing a model from the configuration
|
| 93 |
+
>>> model = MoonshineStreamingModel(configuration)
|
| 94 |
+
|
| 95 |
+
>>> # Accessing the model configuration
|
| 96 |
+
>>> configuration = model.config
|
| 97 |
+
```
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
model_type = "moonshine_streaming"
|
| 101 |
+
sub_configs = {"encoder_config": MoonshineStreamingEncoderConfig}
|
| 102 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 103 |
+
|
| 104 |
+
encoder_config: dict | MoonshineStreamingEncoderConfig | None = None
|
| 105 |
+
vocab_size: int = 32768
|
| 106 |
+
hidden_size: int = 320
|
| 107 |
+
intermediate_size: int = 1280
|
| 108 |
+
num_hidden_layers: int = 6
|
| 109 |
+
num_attention_heads: int = 8
|
| 110 |
+
hidden_act: str = "silu"
|
| 111 |
+
max_position_embeddings: int = 4096
|
| 112 |
+
use_cache: bool = True
|
| 113 |
+
pad_token_id: int | None = 0
|
| 114 |
+
bos_token_id: int | None = 1
|
| 115 |
+
eos_token_id: int | list[int] | None = 2
|
| 116 |
+
rope_parameters: RopeParameters | dict | None = None
|
| 117 |
+
attention_bias: bool = False
|
| 118 |
+
attention_dropout: float | int = 0.0
|
| 119 |
+
decoder_start_token_id: int | None = None
|
| 120 |
+
head_dim: int | None = None
|
| 121 |
+
pad_head_dim_to_multiple_of: int | None = None
|
| 122 |
+
tie_word_embeddings: bool = False
|
| 123 |
+
is_encoder_decoder: bool = True
|
| 124 |
+
|
| 125 |
+
def __post_init__(self, **kwargs):
|
| 126 |
+
if isinstance(self.encoder_config, dict):
|
| 127 |
+
self.encoder_config["model_type"] = self.encoder_config.get("model_type", "moonshine_streaming_encoder")
|
| 128 |
+
self.encoder_config = CONFIG_MAPPING[self.encoder_config["model_type"]](**self.encoder_config)
|
| 129 |
+
elif self.encoder_config is None:
|
| 130 |
+
self.encoder_config = CONFIG_MAPPING["moonshine_streaming_encoder"]()
|
| 131 |
+
|
| 132 |
+
if self.rope_parameters is None:
|
| 133 |
+
self.rope_parameters = {
|
| 134 |
+
"rope_type": "default",
|
| 135 |
+
"rope_theta": 10000.0,
|
| 136 |
+
"partial_rotary_factor": 0.8,
|
| 137 |
+
}
|
| 138 |
+
self.head_dim = self.head_dim if self.head_dim is not None else self.hidden_size // self.num_attention_heads
|
| 139 |
+
super().__post_init__(**kwargs)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
__all__ = ["MoonshineStreamingConfig", "MoonshineStreamingEncoderConfig"]
|
lib/python3.11/site-packages/transformers/models/moonshine_streaming/modeling_moonshine_streaming.py
ADDED
|
@@ -0,0 +1,1121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/moonshine_streaming/modular_moonshine_streaming.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_moonshine_streaming.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2026 the HuggingFace Team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from collections.abc import Callable
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from typing import Optional
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
from torch import Tensor
|
| 28 |
+
|
| 29 |
+
from ...activations import ACT2FN
|
| 30 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 31 |
+
from ...generation import GenerationMixin
|
| 32 |
+
from ...integrations import use_kernelized_func
|
| 33 |
+
from ...masking_utils import create_bidirectional_mask, create_causal_mask
|
| 34 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 35 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 36 |
+
from ...modeling_outputs import (
|
| 37 |
+
BaseModelOutput,
|
| 38 |
+
BaseModelOutputWithPast,
|
| 39 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 40 |
+
Seq2SeqLMOutput,
|
| 41 |
+
Seq2SeqModelOutput,
|
| 42 |
+
)
|
| 43 |
+
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 44 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 45 |
+
from ...processing_utils import Unpack
|
| 46 |
+
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
|
| 47 |
+
from ...utils.generic import maybe_autocast, merge_with_config_defaults
|
| 48 |
+
from ...utils.output_capturing import OutputRecorder, capture_outputs
|
| 49 |
+
from .configuration_moonshine_streaming import MoonshineStreamingConfig, MoonshineStreamingEncoderConfig
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@auto_docstring(
|
| 53 |
+
custom_intro="""
|
| 54 |
+
Extends [~modeling_outputs.BaseModelOutput] to include the output attention mask since sequence length is not preserved in the model's forward.
|
| 55 |
+
"""
|
| 56 |
+
)
|
| 57 |
+
@dataclass
|
| 58 |
+
class MoonshineStreamingEncoderModelOutput(BaseModelOutput):
|
| 59 |
+
r"""
|
| 60 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 61 |
+
Mask to avoid performing attention on padding token indices after sequence compression. Returned because the
|
| 62 |
+
sequence length may differ from the input sequence length. Mask values selected in `[0, 1]`:
|
| 63 |
+
|
| 64 |
+
- 1 for tokens that are **not masked**,
|
| 65 |
+
- 0 for tokens that are **masked**.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
attention_mask: torch.Tensor | None = None
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class MoonshineStreamingFrameCMVN(nn.Module):
|
| 72 |
+
def __init__(self, eps: float = 1e-6):
|
| 73 |
+
super().__init__()
|
| 74 |
+
self.eps = eps
|
| 75 |
+
|
| 76 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 77 |
+
mean = x.mean(dim=-1, keepdim=True)
|
| 78 |
+
centered = x - mean
|
| 79 |
+
rms = (centered.pow(2).mean(dim=-1, keepdim=True) + self.eps).sqrt()
|
| 80 |
+
return centered / rms
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class MoonshineStreamingAsinhCompression(nn.Module):
|
| 84 |
+
def __init__(self, k_init: float = 0.75):
|
| 85 |
+
super().__init__()
|
| 86 |
+
self.log_k = nn.Parameter(torch.log(torch.tensor(k_init)))
|
| 87 |
+
|
| 88 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 89 |
+
return torch.asinh(torch.exp(self.log_k) * x)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class MoonshineStreamingCausalConv1d(nn.Conv1d):
|
| 93 |
+
def __init__(
|
| 94 |
+
self,
|
| 95 |
+
in_channels: int,
|
| 96 |
+
out_channels: int,
|
| 97 |
+
kernel_size: int,
|
| 98 |
+
stride: int = 1,
|
| 99 |
+
dilation: int = 1,
|
| 100 |
+
bias: bool = True,
|
| 101 |
+
):
|
| 102 |
+
super().__init__(in_channels, out_channels, kernel_size, stride=stride, dilation=dilation, bias=bias)
|
| 103 |
+
self.left_pad = (kernel_size - 1) * dilation
|
| 104 |
+
|
| 105 |
+
def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor:
|
| 106 |
+
x = nn.functional.pad(x, (self.left_pad, 0))
|
| 107 |
+
x = super().forward(x)
|
| 108 |
+
|
| 109 |
+
if mask is not None:
|
| 110 |
+
mask = nn.functional.pad(mask, (self.left_pad, 0))[:, None, :]
|
| 111 |
+
weight = torch.ones(1, 1, self.kernel_size[0], device=mask.device)
|
| 112 |
+
mask = nn.functional.conv1d(mask.float(), weight, stride=self.stride)
|
| 113 |
+
mask = mask > 0
|
| 114 |
+
x *= mask
|
| 115 |
+
|
| 116 |
+
if mask is not None:
|
| 117 |
+
mask = mask.squeeze(1)
|
| 118 |
+
return x, mask
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class MoonshineStreamingLayerNorm(nn.Module):
|
| 122 |
+
def __init__(self, dim: int, unit_offset: bool = True, device=None, dtype=None):
|
| 123 |
+
super().__init__()
|
| 124 |
+
self.unit_offset = float(unit_offset)
|
| 125 |
+
self.ln = nn.LayerNorm(dim, elementwise_affine=False, device=device, dtype=dtype)
|
| 126 |
+
self.gamma = nn.Parameter(torch.ones(dim, device=device, dtype=dtype))
|
| 127 |
+
|
| 128 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 129 |
+
normed = self.ln(x)
|
| 130 |
+
gamma = self.gamma + self.unit_offset
|
| 131 |
+
return normed * gamma
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class MoonshineStreamingEncoderMLP(nn.Module):
|
| 135 |
+
def __init__(self, config, hidden_act):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.config = config
|
| 138 |
+
self.activation_fn = ACT2FN[hidden_act]
|
| 139 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 140 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 141 |
+
|
| 142 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 143 |
+
hidden_states = self.fc1(hidden_states)
|
| 144 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 145 |
+
hidden_states = self.fc2(hidden_states)
|
| 146 |
+
return hidden_states
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 150 |
+
"""
|
| 151 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 152 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 153 |
+
"""
|
| 154 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 155 |
+
if n_rep == 1:
|
| 156 |
+
return hidden_states
|
| 157 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 158 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def eager_attention_forward(
|
| 162 |
+
module: nn.Module,
|
| 163 |
+
query: torch.Tensor,
|
| 164 |
+
key: torch.Tensor,
|
| 165 |
+
value: torch.Tensor,
|
| 166 |
+
attention_mask: torch.Tensor | None,
|
| 167 |
+
scaling: float,
|
| 168 |
+
dropout: float = 0.0,
|
| 169 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 170 |
+
):
|
| 171 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 172 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 173 |
+
|
| 174 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 175 |
+
if attention_mask is not None:
|
| 176 |
+
attn_weights = attn_weights + attention_mask
|
| 177 |
+
|
| 178 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 179 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 180 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 181 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 182 |
+
|
| 183 |
+
return attn_output, attn_weights
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class MoonshineStreamingEncoderAttention(nn.Module):
|
| 187 |
+
def __init__(self, config: MoonshineStreamingConfig, layer_idx: int):
|
| 188 |
+
super().__init__()
|
| 189 |
+
self.config = config
|
| 190 |
+
self.layer_idx = layer_idx
|
| 191 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 192 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 193 |
+
self.scaling = self.head_dim**-0.5
|
| 194 |
+
self.attention_dropout = config.attention_dropout
|
| 195 |
+
self.is_causal = False
|
| 196 |
+
|
| 197 |
+
self.q_proj = nn.Linear(
|
| 198 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 199 |
+
)
|
| 200 |
+
self.k_proj = nn.Linear(
|
| 201 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 202 |
+
)
|
| 203 |
+
self.v_proj = nn.Linear(
|
| 204 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 205 |
+
)
|
| 206 |
+
self.o_proj = nn.Linear(
|
| 207 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
def forward(
|
| 211 |
+
self,
|
| 212 |
+
hidden_states: torch.Tensor,
|
| 213 |
+
attention_mask: torch.Tensor | None = None,
|
| 214 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 215 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 216 |
+
input_shape = hidden_states.shape[:-1]
|
| 217 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 218 |
+
|
| 219 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 220 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 221 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 222 |
+
|
| 223 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 224 |
+
self.config._attn_implementation, eager_attention_forward
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
attn_output, attn_weights = attention_interface(
|
| 228 |
+
self,
|
| 229 |
+
query_states,
|
| 230 |
+
key_states,
|
| 231 |
+
value_states,
|
| 232 |
+
attention_mask,
|
| 233 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 234 |
+
scaling=self.scaling,
|
| 235 |
+
**kwargs,
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 239 |
+
attn_output = self.o_proj(attn_output)
|
| 240 |
+
return attn_output, attn_weights
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class MoonshineStreamingEncoderLayer(GradientCheckpointingLayer):
|
| 244 |
+
def __init__(self, config: MoonshineStreamingConfig, layer_idx: int):
|
| 245 |
+
super().__init__()
|
| 246 |
+
self.hidden_size = config.hidden_size
|
| 247 |
+
self.self_attn = MoonshineStreamingEncoderAttention(config, layer_idx)
|
| 248 |
+
self.mlp = MoonshineStreamingEncoderMLP(config, config.hidden_act)
|
| 249 |
+
self.input_layernorm = MoonshineStreamingLayerNorm(config.hidden_size)
|
| 250 |
+
self.post_attention_layernorm = MoonshineStreamingLayerNorm(config.hidden_size)
|
| 251 |
+
|
| 252 |
+
def forward(
|
| 253 |
+
self,
|
| 254 |
+
hidden_states: torch.Tensor,
|
| 255 |
+
attention_mask: torch.Tensor | None = None,
|
| 256 |
+
position_ids: torch.LongTensor | None = None,
|
| 257 |
+
past_key_values: Cache | None = None,
|
| 258 |
+
use_cache: bool | None = False,
|
| 259 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 260 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 261 |
+
) -> torch.Tensor:
|
| 262 |
+
residual = hidden_states
|
| 263 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 264 |
+
# Self Attention
|
| 265 |
+
hidden_states, _ = self.self_attn(
|
| 266 |
+
hidden_states=hidden_states,
|
| 267 |
+
attention_mask=attention_mask,
|
| 268 |
+
position_ids=position_ids,
|
| 269 |
+
past_key_values=past_key_values,
|
| 270 |
+
use_cache=use_cache,
|
| 271 |
+
position_embeddings=position_embeddings,
|
| 272 |
+
**kwargs,
|
| 273 |
+
)
|
| 274 |
+
hidden_states = residual + hidden_states
|
| 275 |
+
|
| 276 |
+
# Fully Connected
|
| 277 |
+
residual = hidden_states
|
| 278 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 279 |
+
hidden_states = self.mlp(hidden_states)
|
| 280 |
+
hidden_states = residual + hidden_states
|
| 281 |
+
return hidden_states
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
class MoonshineStreamingEncoderEmbedder(nn.Module):
|
| 285 |
+
def __init__(self, config):
|
| 286 |
+
super().__init__()
|
| 287 |
+
self.cmvn = MoonshineStreamingFrameCMVN()
|
| 288 |
+
self.comp = MoonshineStreamingAsinhCompression()
|
| 289 |
+
self.conv1 = MoonshineStreamingCausalConv1d(
|
| 290 |
+
config.hidden_size, config.hidden_size * 2, kernel_size=5, stride=2
|
| 291 |
+
)
|
| 292 |
+
self.conv2 = MoonshineStreamingCausalConv1d(
|
| 293 |
+
config.hidden_size * 2, config.hidden_size, kernel_size=5, stride=2
|
| 294 |
+
)
|
| 295 |
+
self.frame_len = int(round(config.sample_rate * config.frame_ms / 1000.0))
|
| 296 |
+
self.linear = nn.Linear(self.frame_len, config.hidden_size, bias=False)
|
| 297 |
+
|
| 298 |
+
def forward(self, input_values, padding_mask=None):
|
| 299 |
+
hidden_states = self.cmvn(input_values.reshape(input_values.shape[0], -1, self.frame_len))
|
| 300 |
+
hidden_states = self.comp(hidden_states)
|
| 301 |
+
hidden_states = nn.functional.silu(self.linear(hidden_states))
|
| 302 |
+
|
| 303 |
+
if padding_mask is not None:
|
| 304 |
+
num_frames = padding_mask.sum(-1) // self.frame_len
|
| 305 |
+
padding_mask = (
|
| 306 |
+
torch.arange(hidden_states.shape[1], device=padding_mask.device)[None, :] < num_frames[:, None]
|
| 307 |
+
)
|
| 308 |
+
hidden_states *= padding_mask[..., None]
|
| 309 |
+
|
| 310 |
+
hidden_states = hidden_states.transpose(1, 2)
|
| 311 |
+
hidden_states, padding_mask = self.conv1(hidden_states, padding_mask)
|
| 312 |
+
hidden_states = nn.functional.silu(hidden_states)
|
| 313 |
+
hidden_states, padding_mask = self.conv2(hidden_states, padding_mask)
|
| 314 |
+
hidden_states = hidden_states.transpose(1, 2)
|
| 315 |
+
return hidden_states, padding_mask
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
@auto_docstring
|
| 319 |
+
class MoonshineStreamingPreTrainedModel(PreTrainedModel):
|
| 320 |
+
config: MoonshineStreamingConfig
|
| 321 |
+
base_model_prefix = "model"
|
| 322 |
+
main_input_name = "input_values"
|
| 323 |
+
input_modalities = "audio"
|
| 324 |
+
supports_gradient_checkpointing = True
|
| 325 |
+
_no_split_modules = ["MoonshineStreamingEncoderLayer", "MoonshineStreamingDecoderLayer"]
|
| 326 |
+
_supports_flash_attn = True
|
| 327 |
+
_supports_sdpa = True
|
| 328 |
+
|
| 329 |
+
_can_compile_fullgraph = True
|
| 330 |
+
# TODO arthur, how do we separate when it cross / self coming from different layer?
|
| 331 |
+
|
| 332 |
+
def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor) -> torch.LongTensor:
|
| 333 |
+
"""
|
| 334 |
+
Computes the output length of the convolutional layers
|
| 335 |
+
"""
|
| 336 |
+
frame_len = int(round(self.config.encoder_config.sample_rate * self.config.encoder_config.frame_ms / 1000.0))
|
| 337 |
+
output_lengths = input_lengths // frame_len
|
| 338 |
+
output_lengths = (output_lengths - 1) // 2 + 1
|
| 339 |
+
output_lengths = (output_lengths - 1) // 2 + 1
|
| 340 |
+
return output_lengths
|
| 341 |
+
|
| 342 |
+
def _init_weights(self, module: nn.Module):
|
| 343 |
+
if isinstance(module, MoonshineStreamingLayerNorm):
|
| 344 |
+
nn.init.constant_(module.gamma, 1.0 - module.unit_offset)
|
| 345 |
+
else:
|
| 346 |
+
super()._init_weights(module)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def sliding_window_mask_function(sliding_window: tuple[int, int]) -> Callable:
|
| 350 |
+
"""
|
| 351 |
+
This creates uni/bidirectional attention mask with sliding window.
|
| 352 |
+
"""
|
| 353 |
+
|
| 354 |
+
def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool:
|
| 355 |
+
left_window_size, right_window_size = sliding_window
|
| 356 |
+
|
| 357 |
+
dist = q_idx - kv_idx
|
| 358 |
+
left_mask = (dist >= 0) & (dist < left_window_size)
|
| 359 |
+
right_mask = (dist < 0) & (-dist < right_window_size)
|
| 360 |
+
return left_mask | right_mask
|
| 361 |
+
|
| 362 |
+
return inner_mask
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
class MoonshineStreamingEncoder(MoonshineStreamingPreTrainedModel):
|
| 366 |
+
config: MoonshineStreamingEncoderConfig
|
| 367 |
+
_can_record_outputs = {
|
| 368 |
+
"attentions": OutputRecorder(MoonshineStreamingEncoderAttention, index=1, layer_name="self_attn"),
|
| 369 |
+
"hidden_states": MoonshineStreamingEncoderLayer,
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
def __init__(self, config: MoonshineStreamingEncoderConfig):
|
| 373 |
+
super().__init__(config)
|
| 374 |
+
self.embedder = MoonshineStreamingEncoderEmbedder(config)
|
| 375 |
+
self.layers = nn.ModuleList(
|
| 376 |
+
[MoonshineStreamingEncoderLayer(config, idx) for idx in range(config.num_hidden_layers)]
|
| 377 |
+
)
|
| 378 |
+
self.final_norm = MoonshineStreamingLayerNorm(config.hidden_size)
|
| 379 |
+
self.gradient_checkpointing = False
|
| 380 |
+
|
| 381 |
+
self.post_init()
|
| 382 |
+
|
| 383 |
+
@merge_with_config_defaults
|
| 384 |
+
@capture_outputs
|
| 385 |
+
def forward(
|
| 386 |
+
self,
|
| 387 |
+
input_values: torch.FloatTensor,
|
| 388 |
+
attention_mask: torch.Tensor | None = None,
|
| 389 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 390 |
+
) -> BaseModelOutputWithPast:
|
| 391 |
+
r"""
|
| 392 |
+
Args:
|
| 393 |
+
input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
|
| 394 |
+
Float values of the raw speech waveform. Raw speech waveform can be
|
| 395 |
+
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
|
| 396 |
+
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
|
| 397 |
+
the soundfile library (`pip install soundfile`). To prepare the array into
|
| 398 |
+
`input_values`, the [`AutoFeatureExtractor`] should be used for padding
|
| 399 |
+
and conversion into a tensor of type `torch.FloatTensor`.
|
| 400 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 401 |
+
Mask to avoid performing attention on padding indices in `input_values`. Mask values selected in `[0, 1]`:
|
| 402 |
+
- 1 for tokens that are **not masked**,
|
| 403 |
+
- 0 for tokens that are **masked**.
|
| 404 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 405 |
+
"""
|
| 406 |
+
inputs_embeds, attention_mask = self.embedder(input_values, padding_mask=attention_mask)
|
| 407 |
+
|
| 408 |
+
if attention_mask is not None:
|
| 409 |
+
mask_kwargs = {
|
| 410 |
+
"config": self.config,
|
| 411 |
+
"inputs_embeds": inputs_embeds,
|
| 412 |
+
"attention_mask": attention_mask,
|
| 413 |
+
}
|
| 414 |
+
per_layer_attention_mask = [
|
| 415 |
+
create_bidirectional_mask(
|
| 416 |
+
and_mask_function=sliding_window_mask_function(self.config.sliding_windows[layer_idx]),
|
| 417 |
+
**mask_kwargs,
|
| 418 |
+
)
|
| 419 |
+
for layer_idx in range(self.config.num_hidden_layers)
|
| 420 |
+
]
|
| 421 |
+
|
| 422 |
+
hidden_states = inputs_embeds
|
| 423 |
+
for layer_idx, encoder_layer in enumerate(self.layers):
|
| 424 |
+
hidden_states = encoder_layer(
|
| 425 |
+
hidden_states,
|
| 426 |
+
attention_mask=per_layer_attention_mask[layer_idx] if attention_mask is not None else None,
|
| 427 |
+
**kwargs,
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
hidden_states = self.final_norm(hidden_states)
|
| 431 |
+
|
| 432 |
+
return MoonshineStreamingEncoderModelOutput(last_hidden_state=hidden_states, attention_mask=attention_mask)
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
class MoonshinMoonshineStreamingDecoderMLP(nn.Module):
|
| 436 |
+
def __init__(self, config):
|
| 437 |
+
super().__init__()
|
| 438 |
+
self.config = config
|
| 439 |
+
self.hidden_size = config.hidden_size
|
| 440 |
+
self.intermediate_size = config.intermediate_size
|
| 441 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 442 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 443 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
| 444 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 445 |
+
|
| 446 |
+
def forward(self, x):
|
| 447 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 448 |
+
return down_proj
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
class MoonshineStreamingDecoderMLP(nn.Module):
|
| 452 |
+
def __init__(self, config, hidden_act):
|
| 453 |
+
super().__init__()
|
| 454 |
+
self.config = config
|
| 455 |
+
self.activation_fn = ACT2FN[hidden_act]
|
| 456 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size * 2)
|
| 457 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 458 |
+
|
| 459 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 460 |
+
hidden_states = self.fc1(hidden_states)
|
| 461 |
+
hidden_states, gate = hidden_states.chunk(2, dim=-1)
|
| 462 |
+
hidden_states = self.activation_fn(gate) * hidden_states
|
| 463 |
+
hidden_states = self.fc2(hidden_states)
|
| 464 |
+
return hidden_states
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class MoonshineStreamingRotaryEmbedding(nn.Module):
|
| 468 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
| 469 |
+
|
| 470 |
+
def __init__(self, config: MoonshineStreamingConfig, device=None):
|
| 471 |
+
super().__init__()
|
| 472 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 473 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 474 |
+
|
| 475 |
+
self.config = config
|
| 476 |
+
|
| 477 |
+
self.rope_type = self.config.rope_parameters["rope_type"]
|
| 478 |
+
rope_init_fn: Callable = self.compute_default_rope_parameters
|
| 479 |
+
if self.rope_type != "default":
|
| 480 |
+
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 481 |
+
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
|
| 482 |
+
|
| 483 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 484 |
+
self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
|
| 485 |
+
|
| 486 |
+
@staticmethod
|
| 487 |
+
def compute_default_rope_parameters(
|
| 488 |
+
config: MoonshineStreamingConfig | None = None,
|
| 489 |
+
device: Optional["torch.device"] = None,
|
| 490 |
+
seq_len: int | None = None,
|
| 491 |
+
) -> tuple["torch.Tensor", float]:
|
| 492 |
+
"""
|
| 493 |
+
Computes the inverse frequencies according to the original RoPE implementation
|
| 494 |
+
Args:
|
| 495 |
+
config ([`~transformers.PreTrainedConfig`]):
|
| 496 |
+
The model configuration.
|
| 497 |
+
device (`torch.device`):
|
| 498 |
+
The device to use for initialization of the inverse frequencies.
|
| 499 |
+
seq_len (`int`, *optional*):
|
| 500 |
+
The current sequence length. Unused for this type of RoPE.
|
| 501 |
+
Returns:
|
| 502 |
+
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
| 503 |
+
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
|
| 504 |
+
"""
|
| 505 |
+
base = config.rope_parameters["rope_theta"]
|
| 506 |
+
partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
|
| 507 |
+
head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
| 508 |
+
dim = int(head_dim * partial_rotary_factor)
|
| 509 |
+
|
| 510 |
+
attention_factor = 1.0 # Unused in this type of RoPE
|
| 511 |
+
|
| 512 |
+
# Compute the inverse frequencies
|
| 513 |
+
inv_freq = 1.0 / (
|
| 514 |
+
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
|
| 515 |
+
)
|
| 516 |
+
return inv_freq, attention_factor
|
| 517 |
+
|
| 518 |
+
@torch.no_grad()
|
| 519 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 520 |
+
def forward(self, x, position_ids):
|
| 521 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 522 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 523 |
+
|
| 524 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 525 |
+
with maybe_autocast(device_type=device_type, enabled=False): # Force float32
|
| 526 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 527 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 528 |
+
cos = emb.cos() * self.attention_scaling
|
| 529 |
+
sin = emb.sin() * self.attention_scaling
|
| 530 |
+
|
| 531 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def rotate_half(x):
|
| 535 |
+
"""Rotates half the hidden dims of the input."""
|
| 536 |
+
x1 = x[..., 0::2]
|
| 537 |
+
x2 = x[..., 1::2]
|
| 538 |
+
return torch.stack((-x2, x1), dim=-1).flatten(-2)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 542 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 543 |
+
|
| 544 |
+
Args:
|
| 545 |
+
q (`torch.Tensor`): The query tensor.
|
| 546 |
+
k (`torch.Tensor`): The key tensor.
|
| 547 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 548 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 549 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 550 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 551 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 552 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 553 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 554 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 555 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 556 |
+
Returns:
|
| 557 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 558 |
+
"""
|
| 559 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 560 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 561 |
+
|
| 562 |
+
# Interleave them instead of usual shape
|
| 563 |
+
cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
|
| 564 |
+
sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
|
| 565 |
+
|
| 566 |
+
# Keep half or full tensor for later concatenation
|
| 567 |
+
rotary_dim = cos.shape[-1]
|
| 568 |
+
q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
|
| 569 |
+
k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
|
| 570 |
+
|
| 571 |
+
# Apply rotary embeddings on the first half or full tensor
|
| 572 |
+
q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
|
| 573 |
+
k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
|
| 574 |
+
|
| 575 |
+
# Concatenate back to full shape
|
| 576 |
+
q_embed = torch.cat([q_embed, q_pass], dim=-1)
|
| 577 |
+
k_embed = torch.cat([k_embed, k_pass], dim=-1)
|
| 578 |
+
return q_embed, k_embed
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
@use_kernelized_func(apply_rotary_pos_emb)
|
| 582 |
+
class MoonshineStreamingAttention(nn.Module):
|
| 583 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 584 |
+
|
| 585 |
+
def __init__(
|
| 586 |
+
self,
|
| 587 |
+
config: MoonshineStreamingConfig,
|
| 588 |
+
layer_idx: int,
|
| 589 |
+
is_causal: bool,
|
| 590 |
+
num_attention_heads: int,
|
| 591 |
+
num_key_value_heads: int,
|
| 592 |
+
):
|
| 593 |
+
super().__init__()
|
| 594 |
+
config.update({"num_attention_heads": num_attention_heads, "num_key_value_heads": num_key_value_heads})
|
| 595 |
+
self.config = config
|
| 596 |
+
self.layer_idx = layer_idx
|
| 597 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 598 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 599 |
+
self.scaling = self.head_dim**-0.5
|
| 600 |
+
self.attention_dropout = config.attention_dropout
|
| 601 |
+
self.is_causal = is_causal
|
| 602 |
+
|
| 603 |
+
self.q_proj = nn.Linear(
|
| 604 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 605 |
+
)
|
| 606 |
+
self.k_proj = nn.Linear(
|
| 607 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 608 |
+
)
|
| 609 |
+
self.v_proj = nn.Linear(
|
| 610 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 611 |
+
)
|
| 612 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
| 613 |
+
|
| 614 |
+
# Pad head dimension to the next specified multiple.
|
| 615 |
+
if self.config.pad_head_dim_to_multiple_of is not None:
|
| 616 |
+
target_multiple = self.config.pad_head_dim_to_multiple_of
|
| 617 |
+
target_head_dim = target_multiple * ((self.head_dim + target_multiple - 1) // target_multiple)
|
| 618 |
+
self.head_dim_padding = target_head_dim - self.head_dim
|
| 619 |
+
else:
|
| 620 |
+
self.head_dim_padding = 0
|
| 621 |
+
|
| 622 |
+
def forward(
|
| 623 |
+
self,
|
| 624 |
+
hidden_states: torch.Tensor,
|
| 625 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 626 |
+
attention_mask: torch.Tensor | None = None,
|
| 627 |
+
past_key_values: Cache | None = None,
|
| 628 |
+
key_value_states: torch.Tensor | None = None,
|
| 629 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 630 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
|
| 631 |
+
bsz, q_len = hidden_states.shape[:-1]
|
| 632 |
+
|
| 633 |
+
query_states = (
|
| 634 |
+
self.q_proj(hidden_states).view(bsz, q_len, self.config.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
is_cross_attention = key_value_states is not None
|
| 638 |
+
if past_key_values is not None:
|
| 639 |
+
is_updated = past_key_values.is_updated.get(self.layer_idx)
|
| 640 |
+
if is_cross_attention:
|
| 641 |
+
# after the first generated id, we can subsequently re-use all key/value_states from cache
|
| 642 |
+
past_key_values.is_updated[self.layer_idx] = True
|
| 643 |
+
past_key_values = past_key_values.cross_attention_cache
|
| 644 |
+
else:
|
| 645 |
+
past_key_values = past_key_values.self_attention_cache
|
| 646 |
+
|
| 647 |
+
# use key_value_states if cross attention
|
| 648 |
+
current_states = key_value_states if key_value_states is not None else hidden_states
|
| 649 |
+
if is_cross_attention and past_key_values and is_updated:
|
| 650 |
+
key_states = past_key_values.layers[self.layer_idx].keys
|
| 651 |
+
value_states = past_key_values.layers[self.layer_idx].values
|
| 652 |
+
else:
|
| 653 |
+
key_states = (
|
| 654 |
+
self.k_proj(current_states)
|
| 655 |
+
.view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
|
| 656 |
+
.transpose(1, 2)
|
| 657 |
+
)
|
| 658 |
+
value_states = (
|
| 659 |
+
self.v_proj(current_states)
|
| 660 |
+
.view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
|
| 661 |
+
.transpose(1, 2)
|
| 662 |
+
)
|
| 663 |
+
if is_cross_attention and past_key_values is not None:
|
| 664 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 665 |
+
|
| 666 |
+
if not is_cross_attention:
|
| 667 |
+
cos, sin = position_embeddings
|
| 668 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 669 |
+
|
| 670 |
+
if past_key_values is not None:
|
| 671 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 672 |
+
|
| 673 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 674 |
+
self.config._attn_implementation, eager_attention_forward
|
| 675 |
+
)
|
| 676 |
+
|
| 677 |
+
is_causal = self.is_causal and attention_mask is None and q_len > 1
|
| 678 |
+
|
| 679 |
+
if self.head_dim_padding > 0:
|
| 680 |
+
query_states = torch.nn.functional.pad(query_states, (0, self.head_dim_padding))
|
| 681 |
+
key_states = torch.nn.functional.pad(key_states, (0, self.head_dim_padding))
|
| 682 |
+
value_states = torch.nn.functional.pad(value_states, (0, self.head_dim_padding))
|
| 683 |
+
|
| 684 |
+
attn_output, attn_weights = attention_interface(
|
| 685 |
+
self,
|
| 686 |
+
query_states,
|
| 687 |
+
key_states,
|
| 688 |
+
value_states,
|
| 689 |
+
attention_mask,
|
| 690 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 691 |
+
scaling=self.scaling,
|
| 692 |
+
is_causal=is_causal,
|
| 693 |
+
**kwargs,
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
if self.head_dim_padding > 0:
|
| 697 |
+
attn_output = attn_output[..., : -self.head_dim_padding]
|
| 698 |
+
|
| 699 |
+
attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
|
| 700 |
+
attn_output = self.o_proj(attn_output)
|
| 701 |
+
return attn_output, attn_weights
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
class MoonshineStreamingDecoderLayer(GradientCheckpointingLayer):
|
| 705 |
+
def __init__(self, config: MoonshineStreamingConfig, layer_idx: int | None = None):
|
| 706 |
+
super().__init__()
|
| 707 |
+
self.hidden_size = config.hidden_size
|
| 708 |
+
|
| 709 |
+
self.self_attn = MoonshineStreamingAttention(
|
| 710 |
+
config=config,
|
| 711 |
+
layer_idx=layer_idx,
|
| 712 |
+
is_causal=True,
|
| 713 |
+
num_attention_heads=config.num_attention_heads,
|
| 714 |
+
num_key_value_heads=config.num_key_value_heads,
|
| 715 |
+
)
|
| 716 |
+
self.encoder_attn = MoonshineStreamingAttention(
|
| 717 |
+
config=config,
|
| 718 |
+
layer_idx=layer_idx,
|
| 719 |
+
is_causal=False,
|
| 720 |
+
num_attention_heads=config.num_attention_heads,
|
| 721 |
+
num_key_value_heads=config.num_key_value_heads,
|
| 722 |
+
)
|
| 723 |
+
|
| 724 |
+
self.mlp = MoonshineStreamingDecoderMLP(config, config.hidden_act)
|
| 725 |
+
self.input_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 726 |
+
self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 727 |
+
self.final_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 728 |
+
|
| 729 |
+
def forward(
|
| 730 |
+
self,
|
| 731 |
+
hidden_states: torch.Tensor,
|
| 732 |
+
attention_mask: torch.Tensor | None = None,
|
| 733 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 734 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 735 |
+
position_ids: torch.LongTensor | None = None,
|
| 736 |
+
encoder_position_ids: torch.LongTensor | None = None,
|
| 737 |
+
past_key_values: Cache | None = None,
|
| 738 |
+
use_cache: bool | None = False,
|
| 739 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 740 |
+
encoder_position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 741 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 742 |
+
) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
|
| 743 |
+
residual = hidden_states
|
| 744 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 745 |
+
|
| 746 |
+
hidden_states, _ = self.self_attn(
|
| 747 |
+
hidden_states=hidden_states,
|
| 748 |
+
attention_mask=attention_mask,
|
| 749 |
+
position_ids=position_ids,
|
| 750 |
+
past_key_values=past_key_values,
|
| 751 |
+
use_cache=use_cache,
|
| 752 |
+
position_embeddings=position_embeddings,
|
| 753 |
+
**kwargs,
|
| 754 |
+
)
|
| 755 |
+
hidden_states = residual + hidden_states
|
| 756 |
+
|
| 757 |
+
if encoder_hidden_states is not None:
|
| 758 |
+
residual = hidden_states
|
| 759 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 760 |
+
hidden_states, _ = self.encoder_attn(
|
| 761 |
+
hidden_states=hidden_states,
|
| 762 |
+
key_value_states=encoder_hidden_states,
|
| 763 |
+
attention_mask=encoder_attention_mask,
|
| 764 |
+
past_key_values=past_key_values,
|
| 765 |
+
use_cache=use_cache,
|
| 766 |
+
)
|
| 767 |
+
hidden_states = residual + hidden_states
|
| 768 |
+
|
| 769 |
+
residual = hidden_states
|
| 770 |
+
hidden_states = self.final_layernorm(hidden_states)
|
| 771 |
+
hidden_states = self.mlp(hidden_states)
|
| 772 |
+
hidden_states = residual + hidden_states
|
| 773 |
+
return hidden_states
|
| 774 |
+
|
| 775 |
+
|
| 776 |
+
@auto_docstring
|
| 777 |
+
class MoonshineStreamingDecoder(MoonshineStreamingPreTrainedModel):
|
| 778 |
+
main_input_name = "input_ids"
|
| 779 |
+
_can_record_outputs = {
|
| 780 |
+
"attentions": OutputRecorder(MoonshineStreamingAttention, index=1, layer_name="self_attn"),
|
| 781 |
+
"hidden_states": MoonshineStreamingDecoderLayer,
|
| 782 |
+
"cross_attentions": OutputRecorder(MoonshineStreamingAttention, index=1, layer_name="encoder_attn"),
|
| 783 |
+
}
|
| 784 |
+
|
| 785 |
+
def __init__(self, config):
|
| 786 |
+
super().__init__(config)
|
| 787 |
+
self.padding_idx = config.pad_token_id
|
| 788 |
+
self.vocab_size = config.vocab_size
|
| 789 |
+
|
| 790 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 791 |
+
self.layers = nn.ModuleList(
|
| 792 |
+
[MoonshineStreamingDecoderLayer(config, idx) for idx in range(config.num_hidden_layers)]
|
| 793 |
+
)
|
| 794 |
+
self.norm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 795 |
+
self.rotary_emb = MoonshineStreamingRotaryEmbedding(config=config)
|
| 796 |
+
self.gradient_checkpointing = False
|
| 797 |
+
self.pos_emb = nn.Embedding(self.config.max_position_embeddings, config.encoder_config.hidden_size)
|
| 798 |
+
|
| 799 |
+
if config.encoder_config.hidden_size != self.config.hidden_size:
|
| 800 |
+
self.proj = nn.Linear(config.encoder_config.hidden_size, self.config.hidden_size, bias=False)
|
| 801 |
+
else:
|
| 802 |
+
self.proj = nn.Identity()
|
| 803 |
+
|
| 804 |
+
# Initialize weights and apply final processing
|
| 805 |
+
self.post_init()
|
| 806 |
+
|
| 807 |
+
@merge_with_config_defaults
|
| 808 |
+
@capture_outputs
|
| 809 |
+
def forward(
|
| 810 |
+
self,
|
| 811 |
+
input_ids: torch.LongTensor | None = None,
|
| 812 |
+
attention_mask: torch.Tensor | None = None,
|
| 813 |
+
position_ids: torch.LongTensor | None = None,
|
| 814 |
+
past_key_values: Cache | None = None,
|
| 815 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 816 |
+
use_cache: bool | None = None,
|
| 817 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 818 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 819 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 820 |
+
) -> tuple | BaseModelOutputWithPast:
|
| 821 |
+
r"""
|
| 822 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 823 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 824 |
+
of the decoder.
|
| 825 |
+
encoder_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 826 |
+
Mask to avoid performing attention on padding indices in `encoder_hidden_states`. Mask values selected in `[0, 1]`:
|
| 827 |
+
- 1 for tokens that are **not masked**,
|
| 828 |
+
- 0 for tokens that are **masked**.
|
| 829 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 830 |
+
"""
|
| 831 |
+
position_embeddings = self.pos_emb(
|
| 832 |
+
torch.arange(encoder_hidden_states.shape[1], device=encoder_hidden_states.device)
|
| 833 |
+
)
|
| 834 |
+
encoder_hidden_states += position_embeddings.to(encoder_hidden_states.device)
|
| 835 |
+
encoder_hidden_states = self.proj(encoder_hidden_states)
|
| 836 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 837 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 838 |
+
|
| 839 |
+
if inputs_embeds is None:
|
| 840 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 841 |
+
|
| 842 |
+
if use_cache and past_key_values is None:
|
| 843 |
+
past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
|
| 844 |
+
|
| 845 |
+
if position_ids is None:
|
| 846 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 847 |
+
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
|
| 848 |
+
position_ids = position_ids.unsqueeze(0)
|
| 849 |
+
|
| 850 |
+
causal_mask = create_causal_mask(
|
| 851 |
+
config=self.config,
|
| 852 |
+
inputs_embeds=inputs_embeds,
|
| 853 |
+
attention_mask=attention_mask,
|
| 854 |
+
past_key_values=past_key_values,
|
| 855 |
+
position_ids=position_ids,
|
| 856 |
+
)
|
| 857 |
+
encoder_attention_mask = create_bidirectional_mask(
|
| 858 |
+
config=self.config,
|
| 859 |
+
inputs_embeds=inputs_embeds,
|
| 860 |
+
attention_mask=encoder_attention_mask,
|
| 861 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 862 |
+
)
|
| 863 |
+
|
| 864 |
+
hidden_states = inputs_embeds
|
| 865 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
|
| 866 |
+
|
| 867 |
+
for decoder_layer in self.layers:
|
| 868 |
+
hidden_states = decoder_layer(
|
| 869 |
+
hidden_states,
|
| 870 |
+
causal_mask,
|
| 871 |
+
encoder_hidden_states, # as a positional argument for gradient checkpointing
|
| 872 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 873 |
+
position_ids=position_ids,
|
| 874 |
+
past_key_values=past_key_values,
|
| 875 |
+
use_cache=use_cache,
|
| 876 |
+
position_embeddings=position_embeddings,
|
| 877 |
+
**kwargs,
|
| 878 |
+
)
|
| 879 |
+
|
| 880 |
+
hidden_states = self.norm(hidden_states)
|
| 881 |
+
|
| 882 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 883 |
+
last_hidden_state=hidden_states,
|
| 884 |
+
past_key_values=past_key_values if use_cache else None,
|
| 885 |
+
)
|
| 886 |
+
|
| 887 |
+
|
| 888 |
+
@auto_docstring
|
| 889 |
+
class MoonshineStreamingModel(MoonshineStreamingPreTrainedModel):
|
| 890 |
+
def __init__(self, config):
|
| 891 |
+
super().__init__(config)
|
| 892 |
+
self.encoder = MoonshineStreamingEncoder(config.encoder_config)
|
| 893 |
+
self.decoder = MoonshineStreamingDecoder(config)
|
| 894 |
+
# Initialize weights and apply final processing
|
| 895 |
+
self.post_init()
|
| 896 |
+
|
| 897 |
+
def get_input_embeddings(self):
|
| 898 |
+
return self.decoder.embed_tokens
|
| 899 |
+
|
| 900 |
+
def set_input_embeddings(self, value):
|
| 901 |
+
self.decoder.embed_tokens = value
|
| 902 |
+
|
| 903 |
+
def freeze_encoder(self):
|
| 904 |
+
"""
|
| 905 |
+
Calling this function will disable the gradient computation for the MoonshineStreaming encoder so that its parameters will
|
| 906 |
+
not be updated during training.
|
| 907 |
+
"""
|
| 908 |
+
self.encoder._freeze_parameters()
|
| 909 |
+
|
| 910 |
+
def _mask_input_features(self):
|
| 911 |
+
"""
|
| 912 |
+
Masks extracted features along time axis and/or along feature axis according to
|
| 913 |
+
[SpecAugment](https://huggingface.co/papers/1904.08779).
|
| 914 |
+
"""
|
| 915 |
+
raise AttributeError("Not needed for MoonshineStreaming")
|
| 916 |
+
|
| 917 |
+
@can_return_tuple
|
| 918 |
+
@auto_docstring
|
| 919 |
+
def forward(
|
| 920 |
+
self,
|
| 921 |
+
input_values: torch.FloatTensor | None = None,
|
| 922 |
+
attention_mask: torch.LongTensor | None = None,
|
| 923 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 924 |
+
decoder_attention_mask: torch.LongTensor | None = None,
|
| 925 |
+
encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
|
| 926 |
+
past_key_values: EncoderDecoderCache | None = None,
|
| 927 |
+
decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
|
| 928 |
+
decoder_position_ids: tuple[torch.LongTensor] | None = None,
|
| 929 |
+
use_cache: bool | None = None,
|
| 930 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 931 |
+
) -> Seq2SeqModelOutput:
|
| 932 |
+
r"""
|
| 933 |
+
input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
|
| 934 |
+
Float values of the raw speech waveform. Raw speech waveform can be
|
| 935 |
+
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
|
| 936 |
+
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
|
| 937 |
+
the soundfile library (`pip install soundfile`). To prepare the array into
|
| 938 |
+
`input_values`, the [`AutoFeatureExtractor`] should be used for padding
|
| 939 |
+
and conversion into a tensor of type `torch.FloatTensor`.
|
| 940 |
+
decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
|
| 941 |
+
Indices of positions of each input sequence tokens in the position embeddings.
|
| 942 |
+
Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
|
| 943 |
+
|
| 944 |
+
Example:
|
| 945 |
+
|
| 946 |
+
```python
|
| 947 |
+
>>> import torch
|
| 948 |
+
>>> from transformers import AutoFeatureExtractor, MoonshineStreamingModel
|
| 949 |
+
>>> from datasets import load_dataset
|
| 950 |
+
|
| 951 |
+
>>> model = MoonshineStreamingModel.from_pretrained("UsefulSensors/moonshine_streaming-tiny")
|
| 952 |
+
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("UsefulSensors/moonshine_streaming-tiny")
|
| 953 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 954 |
+
>>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
|
| 955 |
+
>>> input_values = inputs.input_values
|
| 956 |
+
>>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
|
| 957 |
+
>>> last_hidden_state = model(input_values, decoder_input_ids=decoder_input_ids).last_hidden_state
|
| 958 |
+
>>> list(last_hidden_state.shape)
|
| 959 |
+
[1, 2, 288]
|
| 960 |
+
```
|
| 961 |
+
"""
|
| 962 |
+
if encoder_outputs is None:
|
| 963 |
+
encoder_outputs: BaseModelOutput = self.encoder(input_values, attention_mask=attention_mask, **kwargs)
|
| 964 |
+
|
| 965 |
+
decoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.decoder(
|
| 966 |
+
input_ids=decoder_input_ids,
|
| 967 |
+
attention_mask=decoder_attention_mask,
|
| 968 |
+
encoder_hidden_states=encoder_outputs.last_hidden_state,
|
| 969 |
+
encoder_attention_mask=encoder_outputs.attention_mask,
|
| 970 |
+
past_key_values=past_key_values,
|
| 971 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 972 |
+
position_ids=decoder_position_ids,
|
| 973 |
+
use_cache=use_cache,
|
| 974 |
+
**kwargs,
|
| 975 |
+
)
|
| 976 |
+
|
| 977 |
+
return Seq2SeqModelOutput(
|
| 978 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 979 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 980 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 981 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 982 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 983 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 984 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 985 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 986 |
+
)
|
| 987 |
+
|
| 988 |
+
|
| 989 |
+
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
|
| 990 |
+
"""
|
| 991 |
+
Shift input ids one token to the right.
|
| 992 |
+
"""
|
| 993 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 994 |
+
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
|
| 995 |
+
shifted_input_ids[:, 0] = decoder_start_token_id
|
| 996 |
+
|
| 997 |
+
if pad_token_id is None:
|
| 998 |
+
raise ValueError("self.model.config.pad_token_id has to be defined.")
|
| 999 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 1000 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
|
| 1001 |
+
|
| 1002 |
+
return shifted_input_ids
|
| 1003 |
+
|
| 1004 |
+
|
| 1005 |
+
@auto_docstring(
|
| 1006 |
+
custom_intro="""
|
| 1007 |
+
The MoonshineStreaming Model with a language modeling head. Can be used for automatic speech recognition.
|
| 1008 |
+
"""
|
| 1009 |
+
)
|
| 1010 |
+
class MoonshineStreamingForConditionalGeneration(MoonshineStreamingPreTrainedModel, GenerationMixin):
|
| 1011 |
+
_tied_weights_keys = {"proj_out.weight": "model.decoder.embed_tokens.weight"}
|
| 1012 |
+
|
| 1013 |
+
def __init__(self, config: MoonshineStreamingConfig):
|
| 1014 |
+
super().__init__(config)
|
| 1015 |
+
self.model = MoonshineStreamingModel(config)
|
| 1016 |
+
self.proj_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1017 |
+
|
| 1018 |
+
# Initialize weights and apply final processing
|
| 1019 |
+
self.post_init()
|
| 1020 |
+
|
| 1021 |
+
def get_output_embeddings(self):
|
| 1022 |
+
return self.proj_out
|
| 1023 |
+
|
| 1024 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1025 |
+
self.proj_out = new_embeddings
|
| 1026 |
+
|
| 1027 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1028 |
+
return self.model.get_input_embeddings()
|
| 1029 |
+
|
| 1030 |
+
@can_return_tuple
|
| 1031 |
+
@auto_docstring
|
| 1032 |
+
def forward(
|
| 1033 |
+
self,
|
| 1034 |
+
input_values: torch.FloatTensor | None = None,
|
| 1035 |
+
attention_mask: torch.LongTensor | None = None,
|
| 1036 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 1037 |
+
decoder_attention_mask: torch.LongTensor | None = None,
|
| 1038 |
+
encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
|
| 1039 |
+
past_key_values: EncoderDecoderCache | None = None,
|
| 1040 |
+
decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
|
| 1041 |
+
decoder_position_ids: tuple[torch.LongTensor] | None = None,
|
| 1042 |
+
use_cache: bool | None = None,
|
| 1043 |
+
labels: torch.LongTensor | None = None,
|
| 1044 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1045 |
+
) -> Seq2SeqLMOutput:
|
| 1046 |
+
r"""
|
| 1047 |
+
input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
|
| 1048 |
+
Float values of the raw speech waveform. Raw speech waveform can be
|
| 1049 |
+
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
|
| 1050 |
+
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
|
| 1051 |
+
the soundfile library (`pip install soundfile`). To prepare the array into
|
| 1052 |
+
`input_values`, the [`AutoFeatureExtractor`] should be used for padding
|
| 1053 |
+
and conversion into a tensor of type `torch.FloatTensor`.
|
| 1054 |
+
decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
|
| 1055 |
+
Indices of positions of each input sequence tokens in the position embeddings.
|
| 1056 |
+
Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
|
| 1057 |
+
|
| 1058 |
+
Example:
|
| 1059 |
+
|
| 1060 |
+
```python
|
| 1061 |
+
>>> import torch
|
| 1062 |
+
>>> from transformers import AutoProcessor, MoonshineStreamingForConditionalGeneration
|
| 1063 |
+
>>> from datasets import load_dataset
|
| 1064 |
+
|
| 1065 |
+
>>> processor = AutoProcessor.from_pretrained("UsefulSensors/moonshine_streaming-tiny")
|
| 1066 |
+
>>> model = MoonshineStreamingForConditionalGeneration.from_pretrained("UsefulSensors/moonshine_streaming-tiny")
|
| 1067 |
+
|
| 1068 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 1069 |
+
|
| 1070 |
+
>>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
|
| 1071 |
+
>>> input_values = inputs.input_values
|
| 1072 |
+
|
| 1073 |
+
>>> generated_ids = model.generate(input_values, max_new_tokens=100)
|
| 1074 |
+
|
| 1075 |
+
>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 1076 |
+
>>> transcription
|
| 1077 |
+
'Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
|
| 1078 |
+
```"""
|
| 1079 |
+
|
| 1080 |
+
if labels is not None:
|
| 1081 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 1082 |
+
decoder_input_ids = shift_tokens_right(
|
| 1083 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 1084 |
+
)
|
| 1085 |
+
|
| 1086 |
+
outputs: Seq2SeqModelOutput = self.model(
|
| 1087 |
+
input_values,
|
| 1088 |
+
attention_mask=attention_mask,
|
| 1089 |
+
decoder_input_ids=decoder_input_ids,
|
| 1090 |
+
encoder_outputs=encoder_outputs,
|
| 1091 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1092 |
+
past_key_values=past_key_values,
|
| 1093 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1094 |
+
decoder_position_ids=decoder_position_ids,
|
| 1095 |
+
use_cache=use_cache,
|
| 1096 |
+
**kwargs,
|
| 1097 |
+
)
|
| 1098 |
+
logits = self.proj_out(outputs.last_hidden_state)
|
| 1099 |
+
|
| 1100 |
+
loss = None
|
| 1101 |
+
if labels is not None:
|
| 1102 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size)
|
| 1103 |
+
|
| 1104 |
+
return Seq2SeqLMOutput(
|
| 1105 |
+
loss=loss,
|
| 1106 |
+
logits=logits,
|
| 1107 |
+
past_key_values=outputs.past_key_values,
|
| 1108 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1109 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1110 |
+
cross_attentions=outputs.cross_attentions,
|
| 1111 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1112 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 1113 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 1114 |
+
)
|
| 1115 |
+
|
| 1116 |
+
|
| 1117 |
+
__all__ = [
|
| 1118 |
+
"MoonshineStreamingPreTrainedModel",
|
| 1119 |
+
"MoonshineStreamingModel",
|
| 1120 |
+
"MoonshineStreamingForConditionalGeneration",
|
| 1121 |
+
]
|
lib/python3.11/site-packages/transformers/models/moonshine_streaming/modular_moonshine_streaming.py
ADDED
|
@@ -0,0 +1,419 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 the HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from collections.abc import Callable
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
from torch import Tensor
|
| 21 |
+
|
| 22 |
+
from ...cache_utils import Cache
|
| 23 |
+
from ...masking_utils import create_bidirectional_mask
|
| 24 |
+
from ...modeling_outputs import (
|
| 25 |
+
BaseModelOutput,
|
| 26 |
+
BaseModelOutputWithPast,
|
| 27 |
+
)
|
| 28 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
|
| 29 |
+
from ...processing_utils import ProcessingKwargs, Unpack
|
| 30 |
+
from ...utils import TransformersKwargs, auto_docstring, logging
|
| 31 |
+
from ...utils.generic import merge_with_config_defaults
|
| 32 |
+
from ...utils.output_capturing import OutputRecorder, capture_outputs
|
| 33 |
+
from ..llama.modeling_llama import LlamaMLP, eager_attention_forward
|
| 34 |
+
from ..moonshine.modeling_moonshine import (
|
| 35 |
+
MoonshineDecoder,
|
| 36 |
+
MoonshineEncoderLayer,
|
| 37 |
+
MoonshineEncoderMLP,
|
| 38 |
+
MoonshineForConditionalGeneration,
|
| 39 |
+
MoonshineModel,
|
| 40 |
+
MoonshinePreTrainedModel,
|
| 41 |
+
)
|
| 42 |
+
from ..wav2vec2.processing_wav2vec2 import Wav2Vec2Processor
|
| 43 |
+
from .configuration_moonshine_streaming import MoonshineStreamingConfig, MoonshineStreamingEncoderConfig
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class MoonshineStreamingProcessorKwargs(ProcessingKwargs, total=False):
|
| 50 |
+
_defaults = {
|
| 51 |
+
"audio_kwargs": {
|
| 52 |
+
"pad_to_multiple_of": 80,
|
| 53 |
+
"padding": True,
|
| 54 |
+
},
|
| 55 |
+
"common_kwargs": {"return_tensors": "pt"},
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class MoonshineStreamingProcessor(Wav2Vec2Processor): ...
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@auto_docstring(
|
| 63 |
+
custom_intro="""
|
| 64 |
+
Extends [~modeling_outputs.BaseModelOutput] to include the output attention mask since sequence length is not preserved in the model's forward.
|
| 65 |
+
"""
|
| 66 |
+
)
|
| 67 |
+
@dataclass
|
| 68 |
+
class MoonshineStreamingEncoderModelOutput(BaseModelOutput):
|
| 69 |
+
r"""
|
| 70 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 71 |
+
Mask to avoid performing attention on padding token indices after sequence compression. Returned because the
|
| 72 |
+
sequence length may differ from the input sequence length. Mask values selected in `[0, 1]`:
|
| 73 |
+
|
| 74 |
+
- 1 for tokens that are **not masked**,
|
| 75 |
+
- 0 for tokens that are **masked**.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
attention_mask: torch.Tensor | None = None
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class MoonshineStreamingFrameCMVN(nn.Module):
|
| 82 |
+
def __init__(self, eps: float = 1e-6):
|
| 83 |
+
super().__init__()
|
| 84 |
+
self.eps = eps
|
| 85 |
+
|
| 86 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 87 |
+
mean = x.mean(dim=-1, keepdim=True)
|
| 88 |
+
centered = x - mean
|
| 89 |
+
rms = (centered.pow(2).mean(dim=-1, keepdim=True) + self.eps).sqrt()
|
| 90 |
+
return centered / rms
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class MoonshineStreamingAsinhCompression(nn.Module):
|
| 94 |
+
def __init__(self, k_init: float = 0.75):
|
| 95 |
+
super().__init__()
|
| 96 |
+
self.log_k = nn.Parameter(torch.log(torch.tensor(k_init)))
|
| 97 |
+
|
| 98 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 99 |
+
return torch.asinh(torch.exp(self.log_k) * x)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class MoonshineStreamingCausalConv1d(nn.Conv1d):
|
| 103 |
+
def __init__(
|
| 104 |
+
self,
|
| 105 |
+
in_channels: int,
|
| 106 |
+
out_channels: int,
|
| 107 |
+
kernel_size: int,
|
| 108 |
+
stride: int = 1,
|
| 109 |
+
dilation: int = 1,
|
| 110 |
+
bias: bool = True,
|
| 111 |
+
):
|
| 112 |
+
super().__init__(in_channels, out_channels, kernel_size, stride=stride, dilation=dilation, bias=bias)
|
| 113 |
+
self.left_pad = (kernel_size - 1) * dilation
|
| 114 |
+
|
| 115 |
+
def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor:
|
| 116 |
+
x = nn.functional.pad(x, (self.left_pad, 0))
|
| 117 |
+
x = super().forward(x)
|
| 118 |
+
|
| 119 |
+
if mask is not None:
|
| 120 |
+
mask = nn.functional.pad(mask, (self.left_pad, 0))[:, None, :]
|
| 121 |
+
weight = torch.ones(1, 1, self.kernel_size[0], device=mask.device)
|
| 122 |
+
mask = nn.functional.conv1d(mask.float(), weight, stride=self.stride)
|
| 123 |
+
mask = mask > 0
|
| 124 |
+
x *= mask
|
| 125 |
+
|
| 126 |
+
if mask is not None:
|
| 127 |
+
mask = mask.squeeze(1)
|
| 128 |
+
return x, mask
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class MoonshineStreamingLayerNorm(nn.Module):
|
| 132 |
+
def __init__(self, dim: int, unit_offset: bool = True, device=None, dtype=None):
|
| 133 |
+
super().__init__()
|
| 134 |
+
self.unit_offset = float(unit_offset)
|
| 135 |
+
self.ln = nn.LayerNorm(dim, elementwise_affine=False, device=device, dtype=dtype)
|
| 136 |
+
self.gamma = nn.Parameter(torch.ones(dim, device=device, dtype=dtype))
|
| 137 |
+
|
| 138 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 139 |
+
normed = self.ln(x)
|
| 140 |
+
gamma = self.gamma + self.unit_offset
|
| 141 |
+
return normed * gamma
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class MoonshineStreamingEncoderMLP(MoonshineEncoderMLP): ...
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class MoonshineStreamingEncoderAttention(nn.Module):
|
| 148 |
+
def __init__(self, config: MoonshineStreamingConfig, layer_idx: int):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.config = config
|
| 151 |
+
self.layer_idx = layer_idx
|
| 152 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 153 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 154 |
+
self.scaling = self.head_dim**-0.5
|
| 155 |
+
self.attention_dropout = config.attention_dropout
|
| 156 |
+
self.is_causal = False
|
| 157 |
+
|
| 158 |
+
self.q_proj = nn.Linear(
|
| 159 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 160 |
+
)
|
| 161 |
+
self.k_proj = nn.Linear(
|
| 162 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 163 |
+
)
|
| 164 |
+
self.v_proj = nn.Linear(
|
| 165 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 166 |
+
)
|
| 167 |
+
self.o_proj = nn.Linear(
|
| 168 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
def forward(
|
| 172 |
+
self,
|
| 173 |
+
hidden_states: torch.Tensor,
|
| 174 |
+
attention_mask: torch.Tensor | None = None,
|
| 175 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 176 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 177 |
+
input_shape = hidden_states.shape[:-1]
|
| 178 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 179 |
+
|
| 180 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 181 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 182 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 183 |
+
|
| 184 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 185 |
+
self.config._attn_implementation, eager_attention_forward
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
attn_output, attn_weights = attention_interface(
|
| 189 |
+
self,
|
| 190 |
+
query_states,
|
| 191 |
+
key_states,
|
| 192 |
+
value_states,
|
| 193 |
+
attention_mask,
|
| 194 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 195 |
+
scaling=self.scaling,
|
| 196 |
+
**kwargs,
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 200 |
+
attn_output = self.o_proj(attn_output)
|
| 201 |
+
return attn_output, attn_weights
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class MoonshineStreamingEncoderLayer(MoonshineEncoderLayer):
|
| 205 |
+
def __init__(self, config: MoonshineStreamingConfig, layer_idx: int):
|
| 206 |
+
super().__init__(config, layer_idx)
|
| 207 |
+
self.self_attn = MoonshineStreamingEncoderAttention(config, layer_idx)
|
| 208 |
+
self.mlp = MoonshineStreamingEncoderMLP(config, config.hidden_act)
|
| 209 |
+
self.input_layernorm = MoonshineStreamingLayerNorm(config.hidden_size)
|
| 210 |
+
self.post_attention_layernorm = MoonshineStreamingLayerNorm(config.hidden_size)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class MoonshineStreamingEncoderEmbedder(nn.Module):
|
| 214 |
+
def __init__(self, config):
|
| 215 |
+
super().__init__()
|
| 216 |
+
self.cmvn = MoonshineStreamingFrameCMVN()
|
| 217 |
+
self.comp = MoonshineStreamingAsinhCompression()
|
| 218 |
+
self.conv1 = MoonshineStreamingCausalConv1d(
|
| 219 |
+
config.hidden_size, config.hidden_size * 2, kernel_size=5, stride=2
|
| 220 |
+
)
|
| 221 |
+
self.conv2 = MoonshineStreamingCausalConv1d(
|
| 222 |
+
config.hidden_size * 2, config.hidden_size, kernel_size=5, stride=2
|
| 223 |
+
)
|
| 224 |
+
self.frame_len = int(round(config.sample_rate * config.frame_ms / 1000.0))
|
| 225 |
+
self.linear = nn.Linear(self.frame_len, config.hidden_size, bias=False)
|
| 226 |
+
|
| 227 |
+
def forward(self, input_values, padding_mask=None):
|
| 228 |
+
hidden_states = self.cmvn(input_values.reshape(input_values.shape[0], -1, self.frame_len))
|
| 229 |
+
hidden_states = self.comp(hidden_states)
|
| 230 |
+
hidden_states = nn.functional.silu(self.linear(hidden_states))
|
| 231 |
+
|
| 232 |
+
if padding_mask is not None:
|
| 233 |
+
num_frames = padding_mask.sum(-1) // self.frame_len
|
| 234 |
+
padding_mask = (
|
| 235 |
+
torch.arange(hidden_states.shape[1], device=padding_mask.device)[None, :] < num_frames[:, None]
|
| 236 |
+
)
|
| 237 |
+
hidden_states *= padding_mask[..., None]
|
| 238 |
+
|
| 239 |
+
hidden_states = hidden_states.transpose(1, 2)
|
| 240 |
+
hidden_states, padding_mask = self.conv1(hidden_states, padding_mask)
|
| 241 |
+
hidden_states = nn.functional.silu(hidden_states)
|
| 242 |
+
hidden_states, padding_mask = self.conv2(hidden_states, padding_mask)
|
| 243 |
+
hidden_states = hidden_states.transpose(1, 2)
|
| 244 |
+
return hidden_states, padding_mask
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
class MoonshineStreamingPreTrainedModel(MoonshinePreTrainedModel):
|
| 248 |
+
def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor) -> torch.LongTensor:
|
| 249 |
+
frame_len = int(round(self.config.encoder_config.sample_rate * self.config.encoder_config.frame_ms / 1000.0))
|
| 250 |
+
output_lengths = input_lengths // frame_len
|
| 251 |
+
output_lengths = (output_lengths - 1) // 2 + 1
|
| 252 |
+
output_lengths = (output_lengths - 1) // 2 + 1
|
| 253 |
+
return output_lengths
|
| 254 |
+
|
| 255 |
+
def _init_weights(self, module: nn.Module):
|
| 256 |
+
if isinstance(module, MoonshineStreamingLayerNorm):
|
| 257 |
+
nn.init.constant_(module.gamma, 1.0 - module.unit_offset)
|
| 258 |
+
else:
|
| 259 |
+
super()._init_weights(module)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def sliding_window_mask_function(sliding_window: tuple[int, int]) -> Callable:
|
| 263 |
+
"""
|
| 264 |
+
This creates uni/bidirectional attention mask with sliding window.
|
| 265 |
+
"""
|
| 266 |
+
|
| 267 |
+
def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool:
|
| 268 |
+
left_window_size, right_window_size = sliding_window
|
| 269 |
+
|
| 270 |
+
dist = q_idx - kv_idx
|
| 271 |
+
left_mask = (dist >= 0) & (dist < left_window_size)
|
| 272 |
+
right_mask = (dist < 0) & (-dist < right_window_size)
|
| 273 |
+
return left_mask | right_mask
|
| 274 |
+
|
| 275 |
+
return inner_mask
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
class MoonshineStreamingEncoder(MoonshineStreamingPreTrainedModel):
|
| 279 |
+
config: MoonshineStreamingEncoderConfig
|
| 280 |
+
_can_record_outputs = {
|
| 281 |
+
"attentions": OutputRecorder(MoonshineStreamingEncoderAttention, index=1, layer_name="self_attn"),
|
| 282 |
+
"hidden_states": MoonshineStreamingEncoderLayer,
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
def __init__(self, config: MoonshineStreamingEncoderConfig):
|
| 286 |
+
super().__init__(config)
|
| 287 |
+
self.embedder = MoonshineStreamingEncoderEmbedder(config)
|
| 288 |
+
self.layers = nn.ModuleList(
|
| 289 |
+
[MoonshineStreamingEncoderLayer(config, idx) for idx in range(config.num_hidden_layers)]
|
| 290 |
+
)
|
| 291 |
+
self.final_norm = MoonshineStreamingLayerNorm(config.hidden_size)
|
| 292 |
+
self.gradient_checkpointing = False
|
| 293 |
+
|
| 294 |
+
self.post_init()
|
| 295 |
+
|
| 296 |
+
@merge_with_config_defaults
|
| 297 |
+
@capture_outputs
|
| 298 |
+
def forward(
|
| 299 |
+
self,
|
| 300 |
+
input_values: torch.FloatTensor,
|
| 301 |
+
attention_mask: torch.Tensor | None = None,
|
| 302 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 303 |
+
) -> BaseModelOutputWithPast:
|
| 304 |
+
r"""
|
| 305 |
+
Args:
|
| 306 |
+
input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
|
| 307 |
+
Float values of the raw speech waveform. Raw speech waveform can be
|
| 308 |
+
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
|
| 309 |
+
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
|
| 310 |
+
the soundfile library (`pip install soundfile`). To prepare the array into
|
| 311 |
+
`input_values`, the [`AutoFeatureExtractor`] should be used for padding
|
| 312 |
+
and conversion into a tensor of type `torch.FloatTensor`.
|
| 313 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 314 |
+
Mask to avoid performing attention on padding indices in `input_values`. Mask values selected in `[0, 1]`:
|
| 315 |
+
- 1 for tokens that are **not masked**,
|
| 316 |
+
- 0 for tokens that are **masked**.
|
| 317 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 318 |
+
"""
|
| 319 |
+
inputs_embeds, attention_mask = self.embedder(input_values, padding_mask=attention_mask)
|
| 320 |
+
|
| 321 |
+
if attention_mask is not None:
|
| 322 |
+
mask_kwargs = {
|
| 323 |
+
"config": self.config,
|
| 324 |
+
"inputs_embeds": inputs_embeds,
|
| 325 |
+
"attention_mask": attention_mask,
|
| 326 |
+
}
|
| 327 |
+
per_layer_attention_mask = [
|
| 328 |
+
create_bidirectional_mask(
|
| 329 |
+
and_mask_function=sliding_window_mask_function(self.config.sliding_windows[layer_idx]),
|
| 330 |
+
**mask_kwargs,
|
| 331 |
+
)
|
| 332 |
+
for layer_idx in range(self.config.num_hidden_layers)
|
| 333 |
+
]
|
| 334 |
+
|
| 335 |
+
hidden_states = inputs_embeds
|
| 336 |
+
for layer_idx, encoder_layer in enumerate(self.layers):
|
| 337 |
+
hidden_states = encoder_layer(
|
| 338 |
+
hidden_states,
|
| 339 |
+
attention_mask=per_layer_attention_mask[layer_idx] if attention_mask is not None else None,
|
| 340 |
+
**kwargs,
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
hidden_states = self.final_norm(hidden_states)
|
| 344 |
+
|
| 345 |
+
return MoonshineStreamingEncoderModelOutput(last_hidden_state=hidden_states, attention_mask=attention_mask)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
class MoonshinMoonshineStreamingDecoderMLP(LlamaMLP): ...
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
class MoonshineStreamingDecoder(MoonshineDecoder):
|
| 352 |
+
def __init__(self, config):
|
| 353 |
+
super().__init__(config)
|
| 354 |
+
self.pos_emb = nn.Embedding(self.config.max_position_embeddings, config.encoder_config.hidden_size)
|
| 355 |
+
|
| 356 |
+
if config.encoder_config.hidden_size != self.config.hidden_size:
|
| 357 |
+
self.proj = nn.Linear(config.encoder_config.hidden_size, self.config.hidden_size, bias=False)
|
| 358 |
+
else:
|
| 359 |
+
self.proj = nn.Identity()
|
| 360 |
+
|
| 361 |
+
@merge_with_config_defaults
|
| 362 |
+
@capture_outputs
|
| 363 |
+
def forward(
|
| 364 |
+
self,
|
| 365 |
+
input_ids: torch.LongTensor | None = None,
|
| 366 |
+
attention_mask: torch.Tensor | None = None,
|
| 367 |
+
position_ids: torch.LongTensor | None = None,
|
| 368 |
+
past_key_values: Cache | None = None,
|
| 369 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 370 |
+
use_cache: bool | None = None,
|
| 371 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 372 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 373 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 374 |
+
) -> tuple | BaseModelOutputWithPast:
|
| 375 |
+
r"""
|
| 376 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 377 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 378 |
+
of the decoder.
|
| 379 |
+
encoder_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 380 |
+
Mask to avoid performing attention on padding indices in `encoder_hidden_states`. Mask values selected in `[0, 1]`:
|
| 381 |
+
- 1 for tokens that are **not masked**,
|
| 382 |
+
- 0 for tokens that are **masked**.
|
| 383 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 384 |
+
"""
|
| 385 |
+
position_embeddings = self.pos_emb(
|
| 386 |
+
torch.arange(encoder_hidden_states.shape[1], device=encoder_hidden_states.device)
|
| 387 |
+
)
|
| 388 |
+
encoder_hidden_states += position_embeddings.to(encoder_hidden_states.device)
|
| 389 |
+
encoder_hidden_states = self.proj(encoder_hidden_states)
|
| 390 |
+
|
| 391 |
+
return super().forward(
|
| 392 |
+
input_ids=input_ids,
|
| 393 |
+
attention_mask=attention_mask,
|
| 394 |
+
position_ids=position_ids,
|
| 395 |
+
past_key_values=past_key_values,
|
| 396 |
+
inputs_embeds=inputs_embeds,
|
| 397 |
+
use_cache=use_cache,
|
| 398 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 399 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 400 |
+
**kwargs,
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
class MoonshineStreamingModel(MoonshineModel):
|
| 405 |
+
def __init__(self, config):
|
| 406 |
+
super().__init__(config)
|
| 407 |
+
self.encoder = MoonshineStreamingEncoder(config.encoder_config)
|
| 408 |
+
self.decoder = MoonshineStreamingDecoder(config)
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
class MoonshineStreamingForConditionalGeneration(MoonshineForConditionalGeneration): ...
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
__all__ = [
|
| 415 |
+
"MoonshineStreamingPreTrainedModel",
|
| 416 |
+
"MoonshineStreamingModel",
|
| 417 |
+
"MoonshineStreamingForConditionalGeneration",
|
| 418 |
+
"MoonshineStreamingProcessor",
|
| 419 |
+
]
|
lib/python3.11/site-packages/transformers/models/moonshine_streaming/processing_moonshine_streaming.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/moonshine_streaming/modular_moonshine_streaming.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_moonshine_streaming.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2026 the HuggingFace Team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
|
| 22 |
+
from ...tokenization_utils_base import AudioInput, PreTokenizedInput, TextInput
|
| 23 |
+
from ...utils import auto_docstring
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class MoonshineStreamingProcessorKwargs(ProcessingKwargs, total=False):
|
| 27 |
+
_defaults = {
|
| 28 |
+
"audio_kwargs": {
|
| 29 |
+
"pad_to_multiple_of": 80,
|
| 30 |
+
"padding": True,
|
| 31 |
+
},
|
| 32 |
+
"common_kwargs": {"return_tensors": "pt"},
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@auto_docstring
|
| 37 |
+
class MoonshineStreamingProcessor(ProcessorMixin):
|
| 38 |
+
def __init__(self, feature_extractor, tokenizer):
|
| 39 |
+
super().__init__(feature_extractor, tokenizer)
|
| 40 |
+
|
| 41 |
+
@auto_docstring
|
| 42 |
+
def __call__(
|
| 43 |
+
self,
|
| 44 |
+
audio: AudioInput | None = None,
|
| 45 |
+
text: str | list[str] | TextInput | PreTokenizedInput | None = None,
|
| 46 |
+
**kwargs: Unpack[MoonshineStreamingProcessorKwargs],
|
| 47 |
+
):
|
| 48 |
+
r"""
|
| 49 |
+
Returns:
|
| 50 |
+
This method returns the results of each `call` method. If both are used, the output is a dictionary containing the results of both.
|
| 51 |
+
"""
|
| 52 |
+
if audio is None and text is None:
|
| 53 |
+
raise ValueError("You need to specify either an `audio` or `text` input to process.")
|
| 54 |
+
|
| 55 |
+
output_kwargs = self._merge_kwargs(
|
| 56 |
+
MoonshineStreamingProcessorKwargs,
|
| 57 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 58 |
+
**kwargs,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
if audio is not None:
|
| 62 |
+
inputs = self.feature_extractor(audio, **output_kwargs["audio_kwargs"])
|
| 63 |
+
if text is not None:
|
| 64 |
+
encodings = self.tokenizer(text, **output_kwargs["text_kwargs"])
|
| 65 |
+
|
| 66 |
+
if text is None:
|
| 67 |
+
return inputs
|
| 68 |
+
elif audio is None:
|
| 69 |
+
return encodings
|
| 70 |
+
else:
|
| 71 |
+
inputs["labels"] = encodings["input_ids"]
|
| 72 |
+
return inputs
|
| 73 |
+
|
| 74 |
+
def pad(self, *args, **kwargs):
|
| 75 |
+
"""
|
| 76 |
+
This method operates on batches of extracted features and/or tokenized text. It forwards all arguments to
|
| 77 |
+
[`MoonshineStreamingFeatureExtractor.pad`] and/or [`PreTrainedTokenizer.pad`] depending on the input modality and returns their outputs. If both modalities are passed, [`MoonshineStreamingFeatureExtractor.pad`] and [`PreTrainedTokenizer.pad`] are called.
|
| 78 |
+
|
| 79 |
+
Args:
|
| 80 |
+
input_features:
|
| 81 |
+
When the first argument is a dictionary containing a batch of tensors, or the `input_features` argument is present, it is passed to [`MoonshineStreamingFeatureExtractor.pad`].
|
| 82 |
+
labels:
|
| 83 |
+
When the `label` argument is present, it is passed to [`PreTrainedTokenizer.pad`].
|
| 84 |
+
|
| 85 |
+
Returns:
|
| 86 |
+
This method returns the results of each `pad` method. If both are used, the output is a dictionary containing the results of both.
|
| 87 |
+
"""
|
| 88 |
+
input_features = kwargs.pop("input_features", None)
|
| 89 |
+
labels = kwargs.pop("labels", None)
|
| 90 |
+
if len(args) > 0:
|
| 91 |
+
input_features = args[0]
|
| 92 |
+
args = args[1:]
|
| 93 |
+
|
| 94 |
+
if input_features is not None:
|
| 95 |
+
input_features = self.feature_extractor.pad(input_features, *args, **kwargs)
|
| 96 |
+
if labels is not None:
|
| 97 |
+
labels = self.tokenizer.pad(labels, **kwargs)
|
| 98 |
+
|
| 99 |
+
if labels is None:
|
| 100 |
+
return input_features
|
| 101 |
+
elif input_features is None:
|
| 102 |
+
return labels
|
| 103 |
+
else:
|
| 104 |
+
input_features["labels"] = labels["input_ids"]
|
| 105 |
+
return input_features
|
| 106 |
+
|
| 107 |
+
@property
|
| 108 |
+
def model_input_names(self):
|
| 109 |
+
# The processor doesn't return text ids and the model seems to not need them
|
| 110 |
+
feature_extractor_input_names = self.feature_extractor.model_input_names
|
| 111 |
+
return feature_extractor_input_names + ["labels"]
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
__all__ = ["MoonshineStreamingProcessor"]
|
lib/python3.11/site-packages/transformers/models/moshi/__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_moshi import *
|
| 22 |
+
from .modeling_moshi import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.11/site-packages/transformers/models/moshi/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (775 Bytes). View file
|
|
|
lib/python3.11/site-packages/transformers/models/moshi/__pycache__/configuration_moshi.cpython-311.pyc
ADDED
|
Binary file (10.3 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/moshi/configuration_moshi.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Meta AI and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Moshi model configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...modeling_rope_utils import RopeParameters
|
| 20 |
+
from ...utils import auto_docstring
|
| 21 |
+
from ..auto.configuration_auto import AutoConfig
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@auto_docstring(checkpoint="kmhf/hf-moshiko")
|
| 25 |
+
@strict
|
| 26 |
+
class MoshiDepthConfig(PreTrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
input_size (`int`, *optional*, defaults to 4096):
|
| 29 |
+
Dimensionality of the input hidden states. Used to connect the main decoder to the depth decoder.
|
| 30 |
+
audio_vocab_size (`int`, *optional*, defaults to 2048):
|
| 31 |
+
Vocabulary size of the audio part of model. Defines the number of different tokens that can be
|
| 32 |
+
represented by the `audio_codes` passed when calling the Moshi models.
|
| 33 |
+
ffn_dim (`int`, *optional*, defaults to 5632):
|
| 34 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the depth decoder block. Must be even.
|
| 35 |
+
|
| 36 |
+
Example:
|
| 37 |
+
|
| 38 |
+
```python
|
| 39 |
+
>>> from transformers import (
|
| 40 |
+
... MoshiDepthConfig,
|
| 41 |
+
... MoshiDepthDecoder,
|
| 42 |
+
... )
|
| 43 |
+
|
| 44 |
+
>>> configuration = MoshiDepthConfig()
|
| 45 |
+
|
| 46 |
+
>>> # Initializing a MoshiDepthDecoder (with random weights) from the kmhf/hf-moshiko style configuration
|
| 47 |
+
>>> model = MoshiDepthDecoder(configuration)
|
| 48 |
+
|
| 49 |
+
>>> # Accessing the model configuration
|
| 50 |
+
>>> configuration = model.config
|
| 51 |
+
```"""
|
| 52 |
+
|
| 53 |
+
model_type = "moshi_depth"
|
| 54 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 55 |
+
|
| 56 |
+
vocab_size: int = 32000
|
| 57 |
+
hidden_size: int = 1024
|
| 58 |
+
input_size: int = 4096
|
| 59 |
+
num_hidden_layers: int = 6
|
| 60 |
+
num_attention_heads: int = 16
|
| 61 |
+
num_key_value_heads: int | None = None
|
| 62 |
+
audio_vocab_size: int = 2048
|
| 63 |
+
max_position_embeddings: int = 9
|
| 64 |
+
hidden_act: str = "silu"
|
| 65 |
+
head_dim: int | None = None
|
| 66 |
+
initializer_range: float = 0.02
|
| 67 |
+
use_cache: bool = True
|
| 68 |
+
sliding_window: int = 8
|
| 69 |
+
attention_dropout: float | int = 0.0
|
| 70 |
+
ffn_dim: int = 5632
|
| 71 |
+
rms_norm_eps: float = 1e-8
|
| 72 |
+
num_codebooks: int = 8
|
| 73 |
+
tie_word_embeddings: bool = False
|
| 74 |
+
pad_token_id: int | None = None
|
| 75 |
+
bos_token_id: int | None = None
|
| 76 |
+
eos_token_id: int | list[int] | None = None
|
| 77 |
+
|
| 78 |
+
def __post_init__(self, **kwargs):
|
| 79 |
+
self.num_key_value_heads = (
|
| 80 |
+
self.num_key_value_heads if self.num_key_value_heads is not None else self.num_attention_heads
|
| 81 |
+
)
|
| 82 |
+
self.head_dim = self.head_dim or self.hidden_size // self.num_attention_heads
|
| 83 |
+
super().__post_init__(**kwargs)
|
| 84 |
+
|
| 85 |
+
def validate_architecture(self):
|
| 86 |
+
"""Part of `@strict`-powered validation. Validates the architecture of the config."""
|
| 87 |
+
if self.ffn_dim % 2 == 1:
|
| 88 |
+
raise ValueError(f"`ffn_dim={self.ffn_dim}` must be even.")
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@auto_docstring(checkpoint="kmhf/hf-moshiko")
|
| 92 |
+
@strict
|
| 93 |
+
class MoshiConfig(PreTrainedConfig):
|
| 94 |
+
r"""
|
| 95 |
+
audio_vocab_size (`int`, *optional*):
|
| 96 |
+
Vocabulary size of the audio part of model. Defines the number of different tokens that can be
|
| 97 |
+
represented by the `audio_codes` passed when calling the Moshi models.
|
| 98 |
+
ffn_dim (`int`, *optional*, defaults to 22528):
|
| 99 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the main decoder block. Must be even.
|
| 100 |
+
audio_encoder_config (`PreTrainedConfig | dict`, *optional*):
|
| 101 |
+
Configuration for the audio encoder.
|
| 102 |
+
depth_decoder_config (`PreTrainedConfig | dict`, *optional*):
|
| 103 |
+
Configuration for the depth decoder.
|
| 104 |
+
|
| 105 |
+
Example:
|
| 106 |
+
|
| 107 |
+
```python
|
| 108 |
+
>>> from transformers import (
|
| 109 |
+
... MoshiConfig,
|
| 110 |
+
... MoshiForConditionalGeneration,
|
| 111 |
+
... )
|
| 112 |
+
|
| 113 |
+
>>> configuration = MoshiConfig()
|
| 114 |
+
|
| 115 |
+
>>> # Initializing a MoshiForConditionalGeneration (with random weights) from the kmhf/hf-moshiko style configuration
|
| 116 |
+
>>> model = MoshiForConditionalGeneration(configuration)
|
| 117 |
+
|
| 118 |
+
>>> # Accessing the model configuration
|
| 119 |
+
>>> configuration = model.config
|
| 120 |
+
|
| 121 |
+
>>> # Saving the model, including its configuration
|
| 122 |
+
>>> model.save_pretrained("kmhf/hf-moshiko")
|
| 123 |
+
|
| 124 |
+
>>> # loading model and config from pretrained folder
|
| 125 |
+
>>> moshi_config = MoshiConfig.from_pretrained("kmhf/hf-moshiko")
|
| 126 |
+
>>> model = MoshiForConditionalGeneration.from_pretrained("kmhf/hf-moshiko", config=moshi_config)
|
| 127 |
+
```"""
|
| 128 |
+
|
| 129 |
+
model_type = "moshi"
|
| 130 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 131 |
+
sub_configs = {"audio_encoder_config": AutoConfig, "depth_decoder_config": MoshiDepthConfig}
|
| 132 |
+
|
| 133 |
+
vocab_size: int = 32000
|
| 134 |
+
hidden_size: int = 4096
|
| 135 |
+
num_hidden_layers: int = 32
|
| 136 |
+
num_attention_heads: int = 32
|
| 137 |
+
num_key_value_heads: int | None = None
|
| 138 |
+
audio_vocab_size: int | None = None
|
| 139 |
+
max_position_embeddings: int = 3000
|
| 140 |
+
rope_parameters: RopeParameters | dict | None = None
|
| 141 |
+
hidden_act: str = "silu"
|
| 142 |
+
head_dim: int | None = None
|
| 143 |
+
initializer_range: float = 0.02
|
| 144 |
+
use_cache: bool = True
|
| 145 |
+
sliding_window: int = 3000
|
| 146 |
+
attention_dropout: float | int = 0.0
|
| 147 |
+
ffn_dim: int = 22528
|
| 148 |
+
rms_norm_eps: float = 1e-8
|
| 149 |
+
num_codebooks: int = 8
|
| 150 |
+
tie_word_embeddings: bool = False
|
| 151 |
+
pad_token_id: int | None = None
|
| 152 |
+
bos_token_id: int | None = None
|
| 153 |
+
eos_token_id: int | list[int] | None = None
|
| 154 |
+
audio_encoder_config: dict | PreTrainedConfig | None = None
|
| 155 |
+
depth_decoder_config: dict | PreTrainedConfig | None = None
|
| 156 |
+
|
| 157 |
+
def __post_init__(self, **kwargs):
|
| 158 |
+
self.num_key_value_heads = (
|
| 159 |
+
self.num_key_value_heads if self.num_key_value_heads is not None else self.num_attention_heads
|
| 160 |
+
)
|
| 161 |
+
self.head_dim = self.head_dim or self.hidden_size // self.num_attention_heads
|
| 162 |
+
|
| 163 |
+
if isinstance(self.audio_encoder_config, dict):
|
| 164 |
+
audio_encoder_model_type = self.audio_encoder_config.pop("model_type", "mimi")
|
| 165 |
+
self.audio_encoder_config = AutoConfig.for_model(audio_encoder_model_type, **self.audio_encoder_config)
|
| 166 |
+
elif self.audio_encoder_config is None:
|
| 167 |
+
self.audio_encoder_config = AutoConfig.for_model("mimi")
|
| 168 |
+
|
| 169 |
+
self.audio_vocab_size = (
|
| 170 |
+
self.audio_encoder_config.codebook_size if self.audio_vocab_size is None else self.audio_vocab_size
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
if isinstance(self.depth_decoder_config, dict):
|
| 174 |
+
self.depth_decoder_config.update(
|
| 175 |
+
{
|
| 176 |
+
"audio_vocab_size": self.audio_vocab_size,
|
| 177 |
+
"input_size": self.hidden_size,
|
| 178 |
+
"vocab_size": self.vocab_size,
|
| 179 |
+
"num_codebooks": self.num_codebooks,
|
| 180 |
+
}
|
| 181 |
+
)
|
| 182 |
+
self.depth_decoder_config = MoshiDepthConfig(**self.depth_decoder_config)
|
| 183 |
+
elif self.depth_decoder_config is None:
|
| 184 |
+
self.depth_decoder_config = MoshiDepthConfig()
|
| 185 |
+
super().__post_init__(**kwargs)
|
| 186 |
+
|
| 187 |
+
def validate_architecture(self):
|
| 188 |
+
"""Part of `@strict`-powered validation. Validates the architecture of the config."""
|
| 189 |
+
if self.ffn_dim % 2 == 1:
|
| 190 |
+
raise ValueError(f"`ffn_dim={self.ffn_dim}` must be even.")
|
| 191 |
+
|
| 192 |
+
if self.num_codebooks > self.audio_encoder_config.num_codebooks:
|
| 193 |
+
raise ValueError(
|
| 194 |
+
f"`num_codebooks={self.num_codebooks}` is greater than the maximum number of codebooks that the audio encoder can deal with ({self.audio_encoder_config.num_codebooks}). Please lower it."
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
@property
|
| 198 |
+
def sampling_rate(self):
|
| 199 |
+
return self.audio_encoder_config.sampling_rate
|
| 200 |
+
|
| 201 |
+
@classmethod
|
| 202 |
+
def from_audio_encoder_config(
|
| 203 |
+
cls,
|
| 204 |
+
audio_encoder_config: PreTrainedConfig,
|
| 205 |
+
**kwargs,
|
| 206 |
+
):
|
| 207 |
+
r"""
|
| 208 |
+
Instantiate a [`MoshiConfig`] (or a derived class) from an audio encoder configuration.
|
| 209 |
+
|
| 210 |
+
Returns:
|
| 211 |
+
[`MoshiConfig`]: An instance of a configuration object
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
return cls(
|
| 215 |
+
audio_encoder_config=audio_encoder_config.to_dict(),
|
| 216 |
+
**kwargs,
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
__all__ = ["MoshiConfig", "MoshiDepthConfig"]
|
lib/python3.11/site-packages/transformers/models/moshi/modeling_moshi.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
lib/python3.11/site-packages/transformers/models/mpnet/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_mpnet import *
|
| 22 |
+
from .modeling_mpnet import *
|
| 23 |
+
from .tokenization_mpnet import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (815 Bytes). View file
|
|
|
lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/configuration_mpnet.cpython-311.pyc
ADDED
|
Binary file (2.52 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/modeling_mpnet.cpython-311.pyc
ADDED
|
Binary file (45.4 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/tokenization_mpnet.cpython-311.pyc
ADDED
|
Binary file (8.78 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/mpnet/configuration_mpnet.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 The HuggingFace Inc. team, Microsoft Corporation.
|
| 2 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""MPNet model configuration"""
|
| 16 |
+
|
| 17 |
+
from huggingface_hub.dataclasses import strict
|
| 18 |
+
|
| 19 |
+
from ...configuration_utils import PreTrainedConfig
|
| 20 |
+
from ...utils import auto_docstring
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@auto_docstring(checkpoint="microsoft/mpnet-base")
|
| 24 |
+
@strict
|
| 25 |
+
class MPNetConfig(PreTrainedConfig):
|
| 26 |
+
r"""
|
| 27 |
+
relative_attention_num_buckets (`int`, *optional*, defaults to 32):
|
| 28 |
+
The number of buckets to use for each attention layer.
|
| 29 |
+
|
| 30 |
+
Examples:
|
| 31 |
+
|
| 32 |
+
```python
|
| 33 |
+
>>> from transformers import MPNetModel, MPNetConfig
|
| 34 |
+
|
| 35 |
+
>>> # Initializing a MPNet mpnet-base style configuration
|
| 36 |
+
>>> configuration = MPNetConfig()
|
| 37 |
+
|
| 38 |
+
>>> # Initializing a model from the mpnet-base style configuration
|
| 39 |
+
>>> model = MPNetModel(configuration)
|
| 40 |
+
|
| 41 |
+
>>> # Accessing the model configuration
|
| 42 |
+
>>> configuration = model.config
|
| 43 |
+
```"""
|
| 44 |
+
|
| 45 |
+
model_type = "mpnet"
|
| 46 |
+
|
| 47 |
+
vocab_size: int = 30527
|
| 48 |
+
hidden_size: int = 768
|
| 49 |
+
num_hidden_layers: int = 12
|
| 50 |
+
num_attention_heads: int = 12
|
| 51 |
+
intermediate_size: int = 3072
|
| 52 |
+
hidden_act: str = "gelu"
|
| 53 |
+
hidden_dropout_prob: float | int = 0.1
|
| 54 |
+
attention_probs_dropout_prob: float | int = 0.1
|
| 55 |
+
max_position_embeddings: int = 512
|
| 56 |
+
initializer_range: float = 0.02
|
| 57 |
+
layer_norm_eps: float = 1e-12
|
| 58 |
+
relative_attention_num_buckets: int = 32
|
| 59 |
+
pad_token_id: int | None = 1
|
| 60 |
+
bos_token_id: int | None = 0
|
| 61 |
+
eos_token_id: int | list[int] | None = 2
|
| 62 |
+
tie_word_embeddings: bool = True
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
__all__ = ["MPNetConfig"]
|
lib/python3.11/site-packages/transformers/models/mpnet/modeling_mpnet.py
ADDED
|
@@ -0,0 +1,895 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 The HuggingFace Inc. team, Microsoft Corporation.
|
| 2 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch MPNet model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from torch import nn
|
| 21 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 22 |
+
|
| 23 |
+
from ... import initialization as init
|
| 24 |
+
from ...activations import ACT2FN, gelu
|
| 25 |
+
from ...masking_utils import create_bidirectional_mask
|
| 26 |
+
from ...modeling_outputs import (
|
| 27 |
+
BaseModelOutput,
|
| 28 |
+
BaseModelOutputWithPooling,
|
| 29 |
+
MaskedLMOutput,
|
| 30 |
+
MultipleChoiceModelOutput,
|
| 31 |
+
QuestionAnsweringModelOutput,
|
| 32 |
+
SequenceClassifierOutput,
|
| 33 |
+
TokenClassifierOutput,
|
| 34 |
+
)
|
| 35 |
+
from ...modeling_utils import PreTrainedModel
|
| 36 |
+
from ...utils import auto_docstring, logging
|
| 37 |
+
from .configuration_mpnet import MPNetConfig
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
logger = logging.get_logger(__name__)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@auto_docstring
|
| 44 |
+
class MPNetPreTrainedModel(PreTrainedModel):
|
| 45 |
+
config: MPNetConfig
|
| 46 |
+
base_model_prefix = "mpnet"
|
| 47 |
+
|
| 48 |
+
@torch.no_grad()
|
| 49 |
+
def _init_weights(self, module):
|
| 50 |
+
"""Initialize the weights"""
|
| 51 |
+
super()._init_weights(module)
|
| 52 |
+
if isinstance(module, MPNetLMHead):
|
| 53 |
+
init.zeros_(module.bias)
|
| 54 |
+
elif isinstance(module, MPNetEmbeddings):
|
| 55 |
+
init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class MPNetEmbeddings(nn.Module):
|
| 59 |
+
def __init__(self, config):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.padding_idx = 1
|
| 62 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=self.padding_idx)
|
| 63 |
+
self.position_embeddings = nn.Embedding(
|
| 64 |
+
config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 68 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 69 |
+
self.register_buffer(
|
| 70 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
def forward(self, input_ids=None, position_ids=None, inputs_embeds=None, **kwargs):
|
| 74 |
+
if position_ids is None:
|
| 75 |
+
if input_ids is not None:
|
| 76 |
+
position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx)
|
| 77 |
+
else:
|
| 78 |
+
position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
|
| 79 |
+
|
| 80 |
+
if input_ids is not None:
|
| 81 |
+
input_shape = input_ids.size()
|
| 82 |
+
else:
|
| 83 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 84 |
+
|
| 85 |
+
seq_length = input_shape[1]
|
| 86 |
+
|
| 87 |
+
if position_ids is None:
|
| 88 |
+
position_ids = self.position_ids[:, :seq_length]
|
| 89 |
+
|
| 90 |
+
if inputs_embeds is None:
|
| 91 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 92 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 93 |
+
|
| 94 |
+
embeddings = inputs_embeds + position_embeddings
|
| 95 |
+
embeddings = self.LayerNorm(embeddings)
|
| 96 |
+
embeddings = self.dropout(embeddings)
|
| 97 |
+
return embeddings
|
| 98 |
+
|
| 99 |
+
def create_position_ids_from_inputs_embeds(self, inputs_embeds):
|
| 100 |
+
"""
|
| 101 |
+
We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
|
| 102 |
+
|
| 103 |
+
Args:
|
| 104 |
+
inputs_embeds: torch.Tensor
|
| 105 |
+
|
| 106 |
+
Returns: torch.Tensor
|
| 107 |
+
"""
|
| 108 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 109 |
+
sequence_length = input_shape[1]
|
| 110 |
+
|
| 111 |
+
position_ids = torch.arange(
|
| 112 |
+
self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
|
| 113 |
+
)
|
| 114 |
+
return position_ids.unsqueeze(0).expand(input_shape)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class MPNetSelfAttention(nn.Module):
|
| 118 |
+
def __init__(self, config):
|
| 119 |
+
super().__init__()
|
| 120 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 121 |
+
raise ValueError(
|
| 122 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 123 |
+
f"heads ({config.num_attention_heads})"
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
self.num_attention_heads = config.num_attention_heads
|
| 127 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 128 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 129 |
+
|
| 130 |
+
self.q = nn.Linear(config.hidden_size, self.all_head_size)
|
| 131 |
+
self.k = nn.Linear(config.hidden_size, self.all_head_size)
|
| 132 |
+
self.v = nn.Linear(config.hidden_size, self.all_head_size)
|
| 133 |
+
self.o = nn.Linear(config.hidden_size, config.hidden_size)
|
| 134 |
+
|
| 135 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 136 |
+
|
| 137 |
+
def forward(
|
| 138 |
+
self,
|
| 139 |
+
hidden_states,
|
| 140 |
+
attention_mask=None,
|
| 141 |
+
position_bias=None,
|
| 142 |
+
output_attentions=False,
|
| 143 |
+
**kwargs,
|
| 144 |
+
):
|
| 145 |
+
input_shape = hidden_states.shape[:-1]
|
| 146 |
+
hidden_shape = (*input_shape, -1, self.attention_head_size)
|
| 147 |
+
q = self.q(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 148 |
+
k = self.k(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 149 |
+
v = self.v(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 150 |
+
|
| 151 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 152 |
+
attention_scores = torch.matmul(q, k.transpose(-1, -2))
|
| 153 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 154 |
+
|
| 155 |
+
# Apply relative position embedding (precomputed in MPNetEncoder) if provided.
|
| 156 |
+
if position_bias is not None:
|
| 157 |
+
attention_scores += position_bias
|
| 158 |
+
|
| 159 |
+
if attention_mask is not None:
|
| 160 |
+
attention_scores = attention_scores + attention_mask
|
| 161 |
+
|
| 162 |
+
# Normalize the attention scores to probabilities.
|
| 163 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 164 |
+
|
| 165 |
+
attention_probs = self.dropout(attention_probs)
|
| 166 |
+
|
| 167 |
+
c = torch.matmul(attention_probs, v)
|
| 168 |
+
|
| 169 |
+
c = c.permute(0, 2, 1, 3).contiguous()
|
| 170 |
+
new_c_shape = c.size()[:-2] + (self.all_head_size,)
|
| 171 |
+
c = c.view(*new_c_shape)
|
| 172 |
+
|
| 173 |
+
o = self.o(c)
|
| 174 |
+
|
| 175 |
+
outputs = (o, attention_probs) if output_attentions else (o,)
|
| 176 |
+
return outputs
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class MPNetAttention(nn.Module):
|
| 180 |
+
def __init__(self, config):
|
| 181 |
+
super().__init__()
|
| 182 |
+
self.attn = MPNetSelfAttention(config)
|
| 183 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 184 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 185 |
+
|
| 186 |
+
def forward(
|
| 187 |
+
self,
|
| 188 |
+
hidden_states,
|
| 189 |
+
attention_mask=None,
|
| 190 |
+
position_bias=None,
|
| 191 |
+
output_attentions=False,
|
| 192 |
+
**kwargs,
|
| 193 |
+
):
|
| 194 |
+
self_outputs = self.attn(
|
| 195 |
+
hidden_states,
|
| 196 |
+
attention_mask,
|
| 197 |
+
position_bias,
|
| 198 |
+
output_attentions=output_attentions,
|
| 199 |
+
)
|
| 200 |
+
attention_output = self.LayerNorm(self.dropout(self_outputs[0]) + hidden_states)
|
| 201 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 202 |
+
return outputs
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate
|
| 206 |
+
class MPNetIntermediate(nn.Module):
|
| 207 |
+
def __init__(self, config):
|
| 208 |
+
super().__init__()
|
| 209 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 210 |
+
if isinstance(config.hidden_act, str):
|
| 211 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 212 |
+
else:
|
| 213 |
+
self.intermediate_act_fn = config.hidden_act
|
| 214 |
+
|
| 215 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 216 |
+
hidden_states = self.dense(hidden_states)
|
| 217 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 218 |
+
return hidden_states
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput
|
| 222 |
+
class MPNetOutput(nn.Module):
|
| 223 |
+
def __init__(self, config):
|
| 224 |
+
super().__init__()
|
| 225 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 226 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 227 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 228 |
+
|
| 229 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 230 |
+
hidden_states = self.dense(hidden_states)
|
| 231 |
+
hidden_states = self.dropout(hidden_states)
|
| 232 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 233 |
+
return hidden_states
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
class MPNetLayer(nn.Module):
|
| 237 |
+
def __init__(self, config):
|
| 238 |
+
super().__init__()
|
| 239 |
+
self.attention = MPNetAttention(config)
|
| 240 |
+
self.intermediate = MPNetIntermediate(config)
|
| 241 |
+
self.output = MPNetOutput(config)
|
| 242 |
+
|
| 243 |
+
def forward(
|
| 244 |
+
self,
|
| 245 |
+
hidden_states,
|
| 246 |
+
attention_mask=None,
|
| 247 |
+
position_bias=None,
|
| 248 |
+
output_attentions=False,
|
| 249 |
+
**kwargs,
|
| 250 |
+
):
|
| 251 |
+
self_attention_outputs = self.attention(
|
| 252 |
+
hidden_states,
|
| 253 |
+
attention_mask,
|
| 254 |
+
position_bias=position_bias,
|
| 255 |
+
output_attentions=output_attentions,
|
| 256 |
+
)
|
| 257 |
+
attention_output = self_attention_outputs[0]
|
| 258 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 259 |
+
|
| 260 |
+
intermediate_output = self.intermediate(attention_output)
|
| 261 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 262 |
+
outputs = (layer_output,) + outputs
|
| 263 |
+
return outputs
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
class MPNetEncoder(nn.Module):
|
| 267 |
+
def __init__(self, config):
|
| 268 |
+
super().__init__()
|
| 269 |
+
self.config = config
|
| 270 |
+
self.n_heads = config.num_attention_heads
|
| 271 |
+
self.layer = nn.ModuleList([MPNetLayer(config) for _ in range(config.num_hidden_layers)])
|
| 272 |
+
self.relative_attention_bias = nn.Embedding(config.relative_attention_num_buckets, self.n_heads)
|
| 273 |
+
|
| 274 |
+
def forward(
|
| 275 |
+
self,
|
| 276 |
+
hidden_states: torch.Tensor,
|
| 277 |
+
attention_mask: torch.Tensor | None = None,
|
| 278 |
+
output_attentions: bool = False,
|
| 279 |
+
output_hidden_states: bool = False,
|
| 280 |
+
return_dict: bool = False,
|
| 281 |
+
**kwargs,
|
| 282 |
+
):
|
| 283 |
+
position_bias = self.compute_position_bias(hidden_states)
|
| 284 |
+
all_hidden_states = () if output_hidden_states else None
|
| 285 |
+
all_attentions = () if output_attentions else None
|
| 286 |
+
for i, layer_module in enumerate(self.layer):
|
| 287 |
+
if output_hidden_states:
|
| 288 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 289 |
+
|
| 290 |
+
layer_outputs = layer_module(
|
| 291 |
+
hidden_states,
|
| 292 |
+
attention_mask,
|
| 293 |
+
position_bias,
|
| 294 |
+
output_attentions=output_attentions,
|
| 295 |
+
**kwargs,
|
| 296 |
+
)
|
| 297 |
+
hidden_states = layer_outputs[0]
|
| 298 |
+
|
| 299 |
+
if output_attentions:
|
| 300 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 301 |
+
|
| 302 |
+
# Add last layer
|
| 303 |
+
if output_hidden_states:
|
| 304 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 305 |
+
|
| 306 |
+
if not return_dict:
|
| 307 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
|
| 308 |
+
return BaseModelOutput(
|
| 309 |
+
last_hidden_state=hidden_states,
|
| 310 |
+
hidden_states=all_hidden_states,
|
| 311 |
+
attentions=all_attentions,
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
def compute_position_bias(self, x, position_ids=None, num_buckets=32):
|
| 315 |
+
bsz, qlen, klen = x.size(0), x.size(1), x.size(1)
|
| 316 |
+
if position_ids is not None:
|
| 317 |
+
context_position = position_ids[:, :, None]
|
| 318 |
+
memory_position = position_ids[:, None, :]
|
| 319 |
+
else:
|
| 320 |
+
context_position = torch.arange(qlen, dtype=torch.long)[:, None]
|
| 321 |
+
memory_position = torch.arange(klen, dtype=torch.long)[None, :]
|
| 322 |
+
|
| 323 |
+
relative_position = memory_position - context_position
|
| 324 |
+
|
| 325 |
+
rp_bucket = self.relative_position_bucket(relative_position, num_buckets=num_buckets)
|
| 326 |
+
rp_bucket = rp_bucket.to(x.device)
|
| 327 |
+
values = self.relative_attention_bias(rp_bucket)
|
| 328 |
+
values = values.permute([2, 0, 1]).unsqueeze(0)
|
| 329 |
+
values = values.expand((bsz, -1, qlen, klen)).contiguous()
|
| 330 |
+
return values
|
| 331 |
+
|
| 332 |
+
@staticmethod
|
| 333 |
+
def relative_position_bucket(relative_position, num_buckets=32, max_distance=128):
|
| 334 |
+
ret = 0
|
| 335 |
+
n = -relative_position
|
| 336 |
+
|
| 337 |
+
num_buckets //= 2
|
| 338 |
+
ret += (n < 0).to(torch.long) * num_buckets
|
| 339 |
+
n = torch.abs(n)
|
| 340 |
+
|
| 341 |
+
max_exact = num_buckets // 2
|
| 342 |
+
is_small = n < max_exact
|
| 343 |
+
|
| 344 |
+
val_if_large = max_exact + (
|
| 345 |
+
torch.log(n.float() / max_exact) / math.log(max_distance / max_exact) * (num_buckets - max_exact)
|
| 346 |
+
).to(torch.long)
|
| 347 |
+
|
| 348 |
+
val_if_large = torch.min(val_if_large, torch.full_like(val_if_large, num_buckets - 1))
|
| 349 |
+
ret += torch.where(is_small, n, val_if_large)
|
| 350 |
+
return ret
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
# Copied from transformers.models.bert.modeling_bert.BertPooler
|
| 354 |
+
class MPNetPooler(nn.Module):
|
| 355 |
+
def __init__(self, config):
|
| 356 |
+
super().__init__()
|
| 357 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 358 |
+
self.activation = nn.Tanh()
|
| 359 |
+
|
| 360 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 361 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 362 |
+
# to the first token.
|
| 363 |
+
first_token_tensor = hidden_states[:, 0]
|
| 364 |
+
pooled_output = self.dense(first_token_tensor)
|
| 365 |
+
pooled_output = self.activation(pooled_output)
|
| 366 |
+
return pooled_output
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
@auto_docstring
|
| 370 |
+
class MPNetModel(MPNetPreTrainedModel):
|
| 371 |
+
def __init__(self, config, add_pooling_layer=True):
|
| 372 |
+
r"""
|
| 373 |
+
add_pooling_layer (bool, *optional*, defaults to `True`):
|
| 374 |
+
Whether to add a pooling layer
|
| 375 |
+
"""
|
| 376 |
+
super().__init__(config)
|
| 377 |
+
self.config = config
|
| 378 |
+
|
| 379 |
+
self.embeddings = MPNetEmbeddings(config)
|
| 380 |
+
self.encoder = MPNetEncoder(config)
|
| 381 |
+
self.pooler = MPNetPooler(config) if add_pooling_layer else None
|
| 382 |
+
|
| 383 |
+
# Initialize weights and apply final processing
|
| 384 |
+
self.post_init()
|
| 385 |
+
|
| 386 |
+
def get_input_embeddings(self):
|
| 387 |
+
return self.embeddings.word_embeddings
|
| 388 |
+
|
| 389 |
+
def set_input_embeddings(self, value):
|
| 390 |
+
self.embeddings.word_embeddings = value
|
| 391 |
+
|
| 392 |
+
@auto_docstring
|
| 393 |
+
def forward(
|
| 394 |
+
self,
|
| 395 |
+
input_ids: torch.LongTensor | None = None,
|
| 396 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 397 |
+
position_ids: torch.LongTensor | None = None,
|
| 398 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 399 |
+
output_attentions: bool | None = None,
|
| 400 |
+
output_hidden_states: bool | None = None,
|
| 401 |
+
return_dict: bool | None = None,
|
| 402 |
+
**kwargs,
|
| 403 |
+
) -> tuple[torch.Tensor] | BaseModelOutputWithPooling:
|
| 404 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 405 |
+
output_hidden_states = (
|
| 406 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 407 |
+
)
|
| 408 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 409 |
+
|
| 410 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 411 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 412 |
+
elif input_ids is None and inputs_embeds is None:
|
| 413 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 414 |
+
|
| 415 |
+
embedding_output = self.embeddings(input_ids=input_ids, position_ids=position_ids, inputs_embeds=inputs_embeds)
|
| 416 |
+
|
| 417 |
+
attention_mask = create_bidirectional_mask(
|
| 418 |
+
config=self.config,
|
| 419 |
+
inputs_embeds=embedding_output,
|
| 420 |
+
attention_mask=attention_mask,
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
encoder_outputs = self.encoder(
|
| 424 |
+
embedding_output,
|
| 425 |
+
attention_mask=attention_mask,
|
| 426 |
+
output_attentions=output_attentions,
|
| 427 |
+
output_hidden_states=output_hidden_states,
|
| 428 |
+
return_dict=return_dict,
|
| 429 |
+
)
|
| 430 |
+
sequence_output = encoder_outputs[0]
|
| 431 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 432 |
+
|
| 433 |
+
if not return_dict:
|
| 434 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
| 435 |
+
|
| 436 |
+
return BaseModelOutputWithPooling(
|
| 437 |
+
last_hidden_state=sequence_output,
|
| 438 |
+
pooler_output=pooled_output,
|
| 439 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 440 |
+
attentions=encoder_outputs.attentions,
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
class MPNetForMaskedLM(MPNetPreTrainedModel):
|
| 445 |
+
_tied_weights_keys = {
|
| 446 |
+
"lm_head.decoder.weight": "mpnet.embeddings.word_embeddings.weight",
|
| 447 |
+
"lm_head.decoder.bias": "lm_head.bias",
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
def __init__(self, config):
|
| 451 |
+
super().__init__(config)
|
| 452 |
+
|
| 453 |
+
self.mpnet = MPNetModel(config, add_pooling_layer=False)
|
| 454 |
+
self.lm_head = MPNetLMHead(config)
|
| 455 |
+
|
| 456 |
+
# Initialize weights and apply final processing
|
| 457 |
+
self.post_init()
|
| 458 |
+
|
| 459 |
+
def get_output_embeddings(self):
|
| 460 |
+
return self.lm_head.decoder
|
| 461 |
+
|
| 462 |
+
def set_output_embeddings(self, new_embeddings):
|
| 463 |
+
self.lm_head.decoder = new_embeddings
|
| 464 |
+
self.lm_head.bias = new_embeddings.bias
|
| 465 |
+
|
| 466 |
+
@auto_docstring
|
| 467 |
+
def forward(
|
| 468 |
+
self,
|
| 469 |
+
input_ids: torch.LongTensor | None = None,
|
| 470 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 471 |
+
position_ids: torch.LongTensor | None = None,
|
| 472 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 473 |
+
labels: torch.LongTensor | None = None,
|
| 474 |
+
output_attentions: bool | None = None,
|
| 475 |
+
output_hidden_states: bool | None = None,
|
| 476 |
+
return_dict: bool | None = None,
|
| 477 |
+
**kwargs,
|
| 478 |
+
) -> tuple[torch.Tensor] | MaskedLMOutput:
|
| 479 |
+
r"""
|
| 480 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 481 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 482 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 483 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 484 |
+
"""
|
| 485 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 486 |
+
|
| 487 |
+
outputs = self.mpnet(
|
| 488 |
+
input_ids,
|
| 489 |
+
attention_mask=attention_mask,
|
| 490 |
+
position_ids=position_ids,
|
| 491 |
+
inputs_embeds=inputs_embeds,
|
| 492 |
+
output_attentions=output_attentions,
|
| 493 |
+
output_hidden_states=output_hidden_states,
|
| 494 |
+
return_dict=return_dict,
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
sequence_output = outputs[0]
|
| 498 |
+
prediction_scores = self.lm_head(sequence_output)
|
| 499 |
+
|
| 500 |
+
masked_lm_loss = None
|
| 501 |
+
if labels is not None:
|
| 502 |
+
loss_fct = CrossEntropyLoss()
|
| 503 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 504 |
+
|
| 505 |
+
if not return_dict:
|
| 506 |
+
output = (prediction_scores,) + outputs[2:]
|
| 507 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 508 |
+
|
| 509 |
+
return MaskedLMOutput(
|
| 510 |
+
loss=masked_lm_loss,
|
| 511 |
+
logits=prediction_scores,
|
| 512 |
+
hidden_states=outputs.hidden_states,
|
| 513 |
+
attentions=outputs.attentions,
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
class MPNetLMHead(nn.Module):
|
| 518 |
+
"""MPNet Head for masked and permuted language modeling."""
|
| 519 |
+
|
| 520 |
+
def __init__(self, config):
|
| 521 |
+
super().__init__()
|
| 522 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 523 |
+
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 524 |
+
|
| 525 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
|
| 526 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 527 |
+
|
| 528 |
+
def forward(self, features, **kwargs):
|
| 529 |
+
x = self.dense(features)
|
| 530 |
+
x = gelu(x)
|
| 531 |
+
x = self.layer_norm(x)
|
| 532 |
+
|
| 533 |
+
# project back to size of vocabulary with bias
|
| 534 |
+
x = self.decoder(x)
|
| 535 |
+
|
| 536 |
+
return x
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
@auto_docstring(
|
| 540 |
+
custom_intro="""
|
| 541 |
+
MPNet Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
|
| 542 |
+
output) e.g. for GLUE tasks.
|
| 543 |
+
"""
|
| 544 |
+
)
|
| 545 |
+
class MPNetForSequenceClassification(MPNetPreTrainedModel):
|
| 546 |
+
def __init__(self, config):
|
| 547 |
+
super().__init__(config)
|
| 548 |
+
|
| 549 |
+
self.num_labels = config.num_labels
|
| 550 |
+
self.mpnet = MPNetModel(config, add_pooling_layer=False)
|
| 551 |
+
self.classifier = MPNetClassificationHead(config)
|
| 552 |
+
|
| 553 |
+
# Initialize weights and apply final processing
|
| 554 |
+
self.post_init()
|
| 555 |
+
|
| 556 |
+
@auto_docstring
|
| 557 |
+
def forward(
|
| 558 |
+
self,
|
| 559 |
+
input_ids: torch.LongTensor | None = None,
|
| 560 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 561 |
+
position_ids: torch.LongTensor | None = None,
|
| 562 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 563 |
+
labels: torch.LongTensor | None = None,
|
| 564 |
+
output_attentions: bool | None = None,
|
| 565 |
+
output_hidden_states: bool | None = None,
|
| 566 |
+
return_dict: bool | None = None,
|
| 567 |
+
**kwargs,
|
| 568 |
+
) -> tuple[torch.Tensor] | SequenceClassifierOutput:
|
| 569 |
+
r"""
|
| 570 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 571 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 572 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 573 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 574 |
+
"""
|
| 575 |
+
|
| 576 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 577 |
+
|
| 578 |
+
outputs = self.mpnet(
|
| 579 |
+
input_ids,
|
| 580 |
+
attention_mask=attention_mask,
|
| 581 |
+
position_ids=position_ids,
|
| 582 |
+
inputs_embeds=inputs_embeds,
|
| 583 |
+
output_attentions=output_attentions,
|
| 584 |
+
output_hidden_states=output_hidden_states,
|
| 585 |
+
return_dict=return_dict,
|
| 586 |
+
)
|
| 587 |
+
sequence_output = outputs[0]
|
| 588 |
+
logits = self.classifier(sequence_output)
|
| 589 |
+
|
| 590 |
+
loss = None
|
| 591 |
+
if labels is not None:
|
| 592 |
+
if self.config.problem_type is None:
|
| 593 |
+
if self.num_labels == 1:
|
| 594 |
+
self.config.problem_type = "regression"
|
| 595 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 596 |
+
self.config.problem_type = "single_label_classification"
|
| 597 |
+
else:
|
| 598 |
+
self.config.problem_type = "multi_label_classification"
|
| 599 |
+
|
| 600 |
+
if self.config.problem_type == "regression":
|
| 601 |
+
loss_fct = MSELoss()
|
| 602 |
+
if self.num_labels == 1:
|
| 603 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 604 |
+
else:
|
| 605 |
+
loss = loss_fct(logits, labels)
|
| 606 |
+
elif self.config.problem_type == "single_label_classification":
|
| 607 |
+
loss_fct = CrossEntropyLoss()
|
| 608 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 609 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 610 |
+
loss_fct = BCEWithLogitsLoss()
|
| 611 |
+
loss = loss_fct(logits, labels)
|
| 612 |
+
if not return_dict:
|
| 613 |
+
output = (logits,) + outputs[2:]
|
| 614 |
+
return ((loss,) + output) if loss is not None else output
|
| 615 |
+
|
| 616 |
+
return SequenceClassifierOutput(
|
| 617 |
+
loss=loss,
|
| 618 |
+
logits=logits,
|
| 619 |
+
hidden_states=outputs.hidden_states,
|
| 620 |
+
attentions=outputs.attentions,
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
@auto_docstring
|
| 625 |
+
class MPNetForMultipleChoice(MPNetPreTrainedModel):
|
| 626 |
+
def __init__(self, config):
|
| 627 |
+
super().__init__(config)
|
| 628 |
+
|
| 629 |
+
self.mpnet = MPNetModel(config)
|
| 630 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 631 |
+
self.classifier = nn.Linear(config.hidden_size, 1)
|
| 632 |
+
|
| 633 |
+
# Initialize weights and apply final processing
|
| 634 |
+
self.post_init()
|
| 635 |
+
|
| 636 |
+
@auto_docstring
|
| 637 |
+
def forward(
|
| 638 |
+
self,
|
| 639 |
+
input_ids: torch.LongTensor | None = None,
|
| 640 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 641 |
+
position_ids: torch.LongTensor | None = None,
|
| 642 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 643 |
+
labels: torch.LongTensor | None = None,
|
| 644 |
+
output_attentions: bool | None = None,
|
| 645 |
+
output_hidden_states: bool | None = None,
|
| 646 |
+
return_dict: bool | None = None,
|
| 647 |
+
**kwargs,
|
| 648 |
+
) -> tuple[torch.Tensor] | MultipleChoiceModelOutput:
|
| 649 |
+
r"""
|
| 650 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
|
| 651 |
+
Indices of input sequence tokens in the vocabulary.
|
| 652 |
+
|
| 653 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 654 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 655 |
+
|
| 656 |
+
[What are input IDs?](../glossary#input-ids)
|
| 657 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
|
| 658 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 659 |
+
config.max_position_embeddings - 1]`.
|
| 660 |
+
|
| 661 |
+
[What are position IDs?](../glossary#position-ids)
|
| 662 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
|
| 663 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 664 |
+
is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
|
| 665 |
+
model's internal embedding lookup matrix.
|
| 666 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 667 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
|
| 668 |
+
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
|
| 669 |
+
`input_ids` above)
|
| 670 |
+
"""
|
| 671 |
+
|
| 672 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 673 |
+
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
|
| 674 |
+
|
| 675 |
+
flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
|
| 676 |
+
flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
|
| 677 |
+
flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
|
| 678 |
+
flat_inputs_embeds = (
|
| 679 |
+
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
|
| 680 |
+
if inputs_embeds is not None
|
| 681 |
+
else None
|
| 682 |
+
)
|
| 683 |
+
|
| 684 |
+
outputs = self.mpnet(
|
| 685 |
+
flat_input_ids,
|
| 686 |
+
position_ids=flat_position_ids,
|
| 687 |
+
attention_mask=flat_attention_mask,
|
| 688 |
+
inputs_embeds=flat_inputs_embeds,
|
| 689 |
+
output_attentions=output_attentions,
|
| 690 |
+
output_hidden_states=output_hidden_states,
|
| 691 |
+
return_dict=return_dict,
|
| 692 |
+
)
|
| 693 |
+
pooled_output = outputs[1]
|
| 694 |
+
|
| 695 |
+
pooled_output = self.dropout(pooled_output)
|
| 696 |
+
logits = self.classifier(pooled_output)
|
| 697 |
+
reshaped_logits = logits.view(-1, num_choices)
|
| 698 |
+
|
| 699 |
+
loss = None
|
| 700 |
+
if labels is not None:
|
| 701 |
+
loss_fct = CrossEntropyLoss()
|
| 702 |
+
loss = loss_fct(reshaped_logits, labels)
|
| 703 |
+
|
| 704 |
+
if not return_dict:
|
| 705 |
+
output = (reshaped_logits,) + outputs[2:]
|
| 706 |
+
return ((loss,) + output) if loss is not None else output
|
| 707 |
+
|
| 708 |
+
return MultipleChoiceModelOutput(
|
| 709 |
+
loss=loss,
|
| 710 |
+
logits=reshaped_logits,
|
| 711 |
+
hidden_states=outputs.hidden_states,
|
| 712 |
+
attentions=outputs.attentions,
|
| 713 |
+
)
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
@auto_docstring
|
| 717 |
+
class MPNetForTokenClassification(MPNetPreTrainedModel):
|
| 718 |
+
def __init__(self, config):
|
| 719 |
+
super().__init__(config)
|
| 720 |
+
self.num_labels = config.num_labels
|
| 721 |
+
|
| 722 |
+
self.mpnet = MPNetModel(config, add_pooling_layer=False)
|
| 723 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 724 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 725 |
+
|
| 726 |
+
# Initialize weights and apply final processing
|
| 727 |
+
self.post_init()
|
| 728 |
+
|
| 729 |
+
@auto_docstring
|
| 730 |
+
def forward(
|
| 731 |
+
self,
|
| 732 |
+
input_ids: torch.LongTensor | None = None,
|
| 733 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 734 |
+
position_ids: torch.LongTensor | None = None,
|
| 735 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 736 |
+
labels: torch.LongTensor | None = None,
|
| 737 |
+
output_attentions: bool | None = None,
|
| 738 |
+
output_hidden_states: bool | None = None,
|
| 739 |
+
return_dict: bool | None = None,
|
| 740 |
+
**kwargs,
|
| 741 |
+
) -> tuple[torch.Tensor] | TokenClassifierOutput:
|
| 742 |
+
r"""
|
| 743 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 744 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 745 |
+
"""
|
| 746 |
+
|
| 747 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 748 |
+
|
| 749 |
+
outputs = self.mpnet(
|
| 750 |
+
input_ids,
|
| 751 |
+
attention_mask=attention_mask,
|
| 752 |
+
position_ids=position_ids,
|
| 753 |
+
inputs_embeds=inputs_embeds,
|
| 754 |
+
output_attentions=output_attentions,
|
| 755 |
+
output_hidden_states=output_hidden_states,
|
| 756 |
+
return_dict=return_dict,
|
| 757 |
+
)
|
| 758 |
+
|
| 759 |
+
sequence_output = outputs[0]
|
| 760 |
+
|
| 761 |
+
sequence_output = self.dropout(sequence_output)
|
| 762 |
+
logits = self.classifier(sequence_output)
|
| 763 |
+
|
| 764 |
+
loss = None
|
| 765 |
+
if labels is not None:
|
| 766 |
+
loss_fct = CrossEntropyLoss()
|
| 767 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 768 |
+
|
| 769 |
+
if not return_dict:
|
| 770 |
+
output = (logits,) + outputs[2:]
|
| 771 |
+
return ((loss,) + output) if loss is not None else output
|
| 772 |
+
|
| 773 |
+
return TokenClassifierOutput(
|
| 774 |
+
loss=loss,
|
| 775 |
+
logits=logits,
|
| 776 |
+
hidden_states=outputs.hidden_states,
|
| 777 |
+
attentions=outputs.attentions,
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
class MPNetClassificationHead(nn.Module):
|
| 782 |
+
"""Head for sentence-level classification tasks."""
|
| 783 |
+
|
| 784 |
+
def __init__(self, config):
|
| 785 |
+
super().__init__()
|
| 786 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 787 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 788 |
+
self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
|
| 789 |
+
|
| 790 |
+
def forward(self, features, **kwargs):
|
| 791 |
+
x = features[:, 0, :] # take <s> token (equiv. to BERT's [CLS] token)
|
| 792 |
+
x = self.dropout(x)
|
| 793 |
+
x = self.dense(x)
|
| 794 |
+
x = torch.tanh(x)
|
| 795 |
+
x = self.dropout(x)
|
| 796 |
+
x = self.out_proj(x)
|
| 797 |
+
return x
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
@auto_docstring
|
| 801 |
+
class MPNetForQuestionAnswering(MPNetPreTrainedModel):
|
| 802 |
+
def __init__(self, config):
|
| 803 |
+
super().__init__(config)
|
| 804 |
+
|
| 805 |
+
self.num_labels = config.num_labels
|
| 806 |
+
self.mpnet = MPNetModel(config, add_pooling_layer=False)
|
| 807 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
| 808 |
+
|
| 809 |
+
# Initialize weights and apply final processing
|
| 810 |
+
self.post_init()
|
| 811 |
+
|
| 812 |
+
@auto_docstring
|
| 813 |
+
def forward(
|
| 814 |
+
self,
|
| 815 |
+
input_ids: torch.LongTensor | None = None,
|
| 816 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 817 |
+
position_ids: torch.LongTensor | None = None,
|
| 818 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 819 |
+
start_positions: torch.LongTensor | None = None,
|
| 820 |
+
end_positions: torch.LongTensor | None = None,
|
| 821 |
+
output_attentions: bool | None = None,
|
| 822 |
+
output_hidden_states: bool | None = None,
|
| 823 |
+
return_dict: bool | None = None,
|
| 824 |
+
**kwargs,
|
| 825 |
+
) -> tuple[torch.Tensor] | QuestionAnsweringModelOutput:
|
| 826 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 827 |
+
|
| 828 |
+
outputs = self.mpnet(
|
| 829 |
+
input_ids,
|
| 830 |
+
attention_mask=attention_mask,
|
| 831 |
+
position_ids=position_ids,
|
| 832 |
+
inputs_embeds=inputs_embeds,
|
| 833 |
+
output_attentions=output_attentions,
|
| 834 |
+
output_hidden_states=output_hidden_states,
|
| 835 |
+
return_dict=return_dict,
|
| 836 |
+
)
|
| 837 |
+
|
| 838 |
+
sequence_output = outputs[0]
|
| 839 |
+
|
| 840 |
+
logits = self.qa_outputs(sequence_output)
|
| 841 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 842 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 843 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 844 |
+
|
| 845 |
+
total_loss = None
|
| 846 |
+
if start_positions is not None and end_positions is not None:
|
| 847 |
+
# If we are on multi-GPU, split add a dimension
|
| 848 |
+
if len(start_positions.size()) > 1:
|
| 849 |
+
start_positions = start_positions.squeeze(-1)
|
| 850 |
+
if len(end_positions.size()) > 1:
|
| 851 |
+
end_positions = end_positions.squeeze(-1)
|
| 852 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 853 |
+
ignored_index = start_logits.size(1)
|
| 854 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 855 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 856 |
+
|
| 857 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 858 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 859 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 860 |
+
total_loss = (start_loss + end_loss) / 2
|
| 861 |
+
|
| 862 |
+
if not return_dict:
|
| 863 |
+
output = (start_logits, end_logits) + outputs[2:]
|
| 864 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 865 |
+
|
| 866 |
+
return QuestionAnsweringModelOutput(
|
| 867 |
+
loss=total_loss,
|
| 868 |
+
start_logits=start_logits,
|
| 869 |
+
end_logits=end_logits,
|
| 870 |
+
hidden_states=outputs.hidden_states,
|
| 871 |
+
attentions=outputs.attentions,
|
| 872 |
+
)
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
def create_position_ids_from_input_ids(input_ids, padding_idx):
|
| 876 |
+
"""
|
| 877 |
+
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
|
| 878 |
+
are ignored. This is modified from fairseq's `utils.make_positions`. :param torch.Tensor x: :return torch.Tensor:
|
| 879 |
+
"""
|
| 880 |
+
# The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
|
| 881 |
+
mask = input_ids.ne(padding_idx).int()
|
| 882 |
+
incremental_indices = torch.cumsum(mask, dim=1).type_as(mask) * mask
|
| 883 |
+
return incremental_indices.long() + padding_idx
|
| 884 |
+
|
| 885 |
+
|
| 886 |
+
__all__ = [
|
| 887 |
+
"MPNetForMaskedLM",
|
| 888 |
+
"MPNetForMultipleChoice",
|
| 889 |
+
"MPNetForQuestionAnswering",
|
| 890 |
+
"MPNetForSequenceClassification",
|
| 891 |
+
"MPNetForTokenClassification",
|
| 892 |
+
"MPNetLayer",
|
| 893 |
+
"MPNetModel",
|
| 894 |
+
"MPNetPreTrainedModel",
|
| 895 |
+
]
|
lib/python3.11/site-packages/transformers/models/mpnet/tokenization_mpnet.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 The HuggingFace Inc. team, Microsoft Corporation.
|
| 2 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization classes for MPNet."""
|
| 16 |
+
|
| 17 |
+
from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
|
| 18 |
+
from tokenizers.models import WordPiece
|
| 19 |
+
|
| 20 |
+
from ...tokenization_python import AddedToken
|
| 21 |
+
from ...tokenization_utils_tokenizers import TokenizersBackend
|
| 22 |
+
from ...utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class MPNetTokenizer(TokenizersBackend):
|
| 31 |
+
r"""
|
| 32 |
+
Construct a MPNet tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
|
| 33 |
+
|
| 34 |
+
This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
|
| 35 |
+
refer to this superclass for more information regarding those methods.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
vocab (`str` or `dict[str, int]`, *optional*):
|
| 39 |
+
Dictionary mapping tokens to their IDs. If not provided, an empty vocab is initialized.
|
| 40 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 41 |
+
Whether or not to lowercase the input when tokenizing.
|
| 42 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 43 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 44 |
+
|
| 45 |
+
<Tip>
|
| 46 |
+
|
| 47 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 48 |
+
sequence. The token used is the `cls_token`.
|
| 49 |
+
|
| 50 |
+
</Tip>
|
| 51 |
+
|
| 52 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 53 |
+
The end of sequence token.
|
| 54 |
+
|
| 55 |
+
<Tip>
|
| 56 |
+
|
| 57 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 58 |
+
The token used is the `sep_token`.
|
| 59 |
+
|
| 60 |
+
</Tip>
|
| 61 |
+
|
| 62 |
+
sep_token (`str`, *optional*, defaults to `"</s>"`):
|
| 63 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 64 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 65 |
+
token of a sequence built with special tokens.
|
| 66 |
+
cls_token (`str`, *optional*, defaults to `"<s>"`):
|
| 67 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 68 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 69 |
+
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
|
| 70 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 71 |
+
token instead.
|
| 72 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 73 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 74 |
+
mask_token (`str`, *optional*, defaults to `"<mask>"`):
|
| 75 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 76 |
+
modeling. This is the token which the model will try to predict.
|
| 77 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 78 |
+
Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
|
| 79 |
+
issue](https://github.com/huggingface/transformers/issues/328)).
|
| 80 |
+
strip_accents (`bool`, *optional*):
|
| 81 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 82 |
+
value for `lowercase` (as in the original BERT).
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 86 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 87 |
+
model = WordPiece
|
| 88 |
+
|
| 89 |
+
def __init__(
|
| 90 |
+
self,
|
| 91 |
+
vocab: str | dict[str, int] | None = None,
|
| 92 |
+
do_lower_case=True,
|
| 93 |
+
bos_token="<s>",
|
| 94 |
+
eos_token="</s>",
|
| 95 |
+
sep_token="</s>",
|
| 96 |
+
cls_token="<s>",
|
| 97 |
+
unk_token="[UNK]",
|
| 98 |
+
pad_token="<pad>",
|
| 99 |
+
mask_token="<mask>",
|
| 100 |
+
tokenize_chinese_chars=True,
|
| 101 |
+
strip_accents=None,
|
| 102 |
+
**kwargs,
|
| 103 |
+
):
|
| 104 |
+
# Initialize vocab
|
| 105 |
+
self._vocab = vocab if vocab is not None else {}
|
| 106 |
+
|
| 107 |
+
# Initialize the tokenizer with WordPiece model
|
| 108 |
+
self._tokenizer = Tokenizer(WordPiece(self._vocab, unk_token=str(unk_token)))
|
| 109 |
+
|
| 110 |
+
# Set normalizer based on MPNetConverter logic
|
| 111 |
+
self._tokenizer.normalizer = normalizers.BertNormalizer(
|
| 112 |
+
clean_text=True,
|
| 113 |
+
handle_chinese_chars=tokenize_chinese_chars,
|
| 114 |
+
strip_accents=strip_accents,
|
| 115 |
+
lowercase=do_lower_case,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
# Set pre-tokenizer
|
| 119 |
+
self._tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
|
| 120 |
+
|
| 121 |
+
# Set decoder
|
| 122 |
+
self._tokenizer.decoder = decoders.WordPiece(prefix="##")
|
| 123 |
+
|
| 124 |
+
# Store do_lower_case for later use
|
| 125 |
+
self.do_lower_case = do_lower_case
|
| 126 |
+
|
| 127 |
+
# Handle special token initialization
|
| 128 |
+
bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
|
| 129 |
+
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
|
| 130 |
+
sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
|
| 131 |
+
cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
|
| 132 |
+
unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
|
| 133 |
+
pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
|
| 134 |
+
|
| 135 |
+
# Mask token behave like a normal word, i.e. include the space before it
|
| 136 |
+
mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
|
| 137 |
+
|
| 138 |
+
super().__init__(
|
| 139 |
+
do_lower_case=do_lower_case,
|
| 140 |
+
bos_token=bos_token,
|
| 141 |
+
eos_token=eos_token,
|
| 142 |
+
sep_token=sep_token,
|
| 143 |
+
cls_token=cls_token,
|
| 144 |
+
unk_token=unk_token,
|
| 145 |
+
pad_token=pad_token,
|
| 146 |
+
mask_token=mask_token,
|
| 147 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 148 |
+
strip_accents=strip_accents,
|
| 149 |
+
**kwargs,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
# Set post_processor after super().__init__ to ensure we have token IDs
|
| 153 |
+
cls_str = str(self.cls_token)
|
| 154 |
+
sep_str = str(self.sep_token)
|
| 155 |
+
cls_token_id = self.cls_token_id if self.cls_token_id is not None else 0
|
| 156 |
+
sep_token_id = self.sep_token_id if self.sep_token_id is not None else 2
|
| 157 |
+
|
| 158 |
+
self._tokenizer.post_processor = processors.TemplateProcessing(
|
| 159 |
+
single=f"{cls_str}:0 $A:0 {sep_str}:0",
|
| 160 |
+
pair=f"{cls_str}:0 $A:0 {sep_str}:0 {sep_str}:0 $B:1 {sep_str}:1", # MPNet uses two [SEP] tokens
|
| 161 |
+
special_tokens=[
|
| 162 |
+
(cls_str, cls_token_id),
|
| 163 |
+
(sep_str, sep_token_id),
|
| 164 |
+
],
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
@property
|
| 168 |
+
def mask_token(self) -> str:
|
| 169 |
+
"""
|
| 170 |
+
`str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
|
| 171 |
+
having been set.
|
| 172 |
+
|
| 173 |
+
MPNet tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
|
| 174 |
+
comprise the space before the *<mask>*.
|
| 175 |
+
"""
|
| 176 |
+
if self._mask_token is None:
|
| 177 |
+
if self.verbose:
|
| 178 |
+
logger.error("Using mask_token, but it is not set yet.")
|
| 179 |
+
return None
|
| 180 |
+
return str(self._mask_token)
|
| 181 |
+
|
| 182 |
+
@mask_token.setter
|
| 183 |
+
def mask_token(self, value):
|
| 184 |
+
"""
|
| 185 |
+
Overriding the default behavior of the mask token to have it eat the space before it.
|
| 186 |
+
|
| 187 |
+
This is needed to preserve backward compatibility with all the previously used models based on MPNet.
|
| 188 |
+
"""
|
| 189 |
+
# Mask token behave like a normal word, i.e. include the space before it
|
| 190 |
+
# So we set lstrip to True
|
| 191 |
+
value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
|
| 192 |
+
self._mask_token = value
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
__all__ = ["MPNetTokenizer"]
|
lib/python3.11/site-packages/transformers/models/mpt/__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_mpt import *
|
| 22 |
+
from .modeling_mpt import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.11/site-packages/transformers/models/mpt/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (769 Bytes). View file
|
|
|
lib/python3.11/site-packages/transformers/models/mpt/__pycache__/configuration_mpt.cpython-311.pyc
ADDED
|
Binary file (7.48 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/mpt/__pycache__/modeling_mpt.cpython-311.pyc
ADDED
|
Binary file (35.3 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/mpt/configuration_mpt.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 HuggingFace Inc. team and MosaicML NLP team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Mpt configuration"""
|
| 15 |
+
|
| 16 |
+
from typing import Literal
|
| 17 |
+
|
| 18 |
+
from huggingface_hub.dataclasses import strict
|
| 19 |
+
|
| 20 |
+
from ...configuration_utils import PreTrainedConfig
|
| 21 |
+
from ...utils import auto_docstring
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@auto_docstring(checkpoint="mosaicml/mpt-7b")
|
| 25 |
+
@strict
|
| 26 |
+
class MptAttentionConfig(PreTrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
attn_type (`str`, *optional*, defaults to `"multihead_attention"`):
|
| 29 |
+
type of attention to use. Options: `"multihead_attention"`, `"multiquery_attention"`.
|
| 30 |
+
attn_pdrop (`float`, *optional*, defaults to `0.0`):
|
| 31 |
+
The dropout probability for the attention layers.
|
| 32 |
+
attn_impl (`str`, *optional*, defaults to `"torch"`):
|
| 33 |
+
The attention implementation to use. One of `"torch"`, `"flash"`, or `"triton"`.
|
| 34 |
+
clip_qkv (`float`, *optional*):
|
| 35 |
+
If not `None`, clip the queries, keys, and values in the attention layer to this value.
|
| 36 |
+
softmax_scale (`float`, *optional*):
|
| 37 |
+
If not `None`, scale the softmax in the attention layer by this value. If `None`, will default to
|
| 38 |
+
`1/sqrt(hidden_size)`.
|
| 39 |
+
prefix_lm (`bool`, *optional*, defaults to `False`):
|
| 40 |
+
Whether the model should operate as a Prefix LM. This requires passing an extra `prefix_mask` argument
|
| 41 |
+
which indicates which tokens belong to the prefix. Tokens in the prefix can attend to one another
|
| 42 |
+
bi-directionally. Tokens outside the prefix use causal attention.
|
| 43 |
+
qk_ln (`bool`, *optional*, defaults to `False`):
|
| 44 |
+
Whether to apply layer normalization to the queries and keys in the attention layer.
|
| 45 |
+
attn_uses_sequence_id (`bool`, *optional*, defaults to `False`):
|
| 46 |
+
Whether to restrict attention to tokens that have the same token_type_ids. When the model is in `train`
|
| 47 |
+
mode, this requires passing an extra *token_type_ids* argument which indicates which sub-sequence each
|
| 48 |
+
token belongs to. Defaults to `False` meaning any provided *token_type_ids* will be ignored.
|
| 49 |
+
alibi (`bool`, *optional*, defaults to `True`):
|
| 50 |
+
Whether or not to use the alibi bias instead of positional embedding.
|
| 51 |
+
alibi_bias_max (`int`, *optional*, defaults to 8):
|
| 52 |
+
The maximum value of the alibi bias.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
base_config_key = "attn_config"
|
| 56 |
+
|
| 57 |
+
attn_type: Literal["multihead_attention", "multiquery_attention"] = "multihead_attention"
|
| 58 |
+
attn_pdrop: int = 0
|
| 59 |
+
attn_impl: str = "torch"
|
| 60 |
+
clip_qkv: float | None = None
|
| 61 |
+
softmax_scale: float | None = None
|
| 62 |
+
prefix_lm: bool = False
|
| 63 |
+
qk_ln: bool = False
|
| 64 |
+
attn_uses_sequence_id: bool = False
|
| 65 |
+
alibi: bool = True
|
| 66 |
+
alibi_bias_max: int = 8
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@auto_docstring(checkpoint="mosaicml/mpt-7b")
|
| 70 |
+
@strict
|
| 71 |
+
class MptConfig(PreTrainedConfig):
|
| 72 |
+
r"""
|
| 73 |
+
expansion_ratio (`int`, *optional*, defaults to 4):
|
| 74 |
+
The ratio of the up/down scale in the MLP.
|
| 75 |
+
max_seq_len (`int`, *optional*, defaults to 2048):
|
| 76 |
+
The maximum sequence length of the model.
|
| 77 |
+
layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
|
| 78 |
+
The epsilon to use in the layer normalization layers.
|
| 79 |
+
learned_pos_emb (`bool`, *optional*, defaults to `True`):
|
| 80 |
+
Whether to use learned positional embeddings.
|
| 81 |
+
attn_config (`dict`, *optional*):
|
| 82 |
+
A dictionary used to configure the model's attention module.
|
| 83 |
+
init_device (`str`, *optional*, defaults to `"cpu"`):
|
| 84 |
+
The device to use for parameter initialization. Defined for backward compatibility
|
| 85 |
+
logit_scale (`float`, *optional*):
|
| 86 |
+
If not None, scale the logits by this value.
|
| 87 |
+
no_bias (`bool`, *optional*, defaults to `True`):
|
| 88 |
+
Whether to use bias in all linear layers.
|
| 89 |
+
embedding_fraction (`float`, *optional*, defaults to 1.0):
|
| 90 |
+
The fraction to scale the gradients of the embedding layer by.
|
| 91 |
+
norm_type (`str`, *optional*, defaults to `"low_precision_layernorm"`):
|
| 92 |
+
Type of layer norm to use. All MPT models uses the same layer norm implementation. Defined for backward
|
| 93 |
+
compatibility.
|
| 94 |
+
|
| 95 |
+
Example:
|
| 96 |
+
|
| 97 |
+
```python
|
| 98 |
+
>>> from transformers import MptConfig, MptModel
|
| 99 |
+
|
| 100 |
+
>>> # Initializing a Mpt configuration
|
| 101 |
+
>>> configuration = MptConfig()
|
| 102 |
+
|
| 103 |
+
>>> # Initializing a model (with random weights) from the configuration
|
| 104 |
+
>>> model = MptModel(configuration)
|
| 105 |
+
|
| 106 |
+
>>> # Accessing the model configuration
|
| 107 |
+
>>> configuration = model.config
|
| 108 |
+
```
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
model_type = "mpt"
|
| 112 |
+
sub_configs = {"attn_config": MptAttentionConfig}
|
| 113 |
+
attribute_map = {
|
| 114 |
+
"num_attention_heads": "n_heads",
|
| 115 |
+
"hidden_size": "d_model",
|
| 116 |
+
"num_hidden_layers": "n_layers",
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
d_model: int = 2048
|
| 120 |
+
n_heads: int = 16
|
| 121 |
+
n_layers: int = 24
|
| 122 |
+
expansion_ratio: int = 4
|
| 123 |
+
max_seq_len: int = 2048
|
| 124 |
+
vocab_size: int = 50368
|
| 125 |
+
resid_pdrop: float | int = 0.0
|
| 126 |
+
layer_norm_epsilon: float = 1e-5
|
| 127 |
+
emb_pdrop: float | int = 0.0
|
| 128 |
+
learned_pos_emb: bool = True
|
| 129 |
+
attn_config: dict | MptAttentionConfig | None = None
|
| 130 |
+
init_device: str = "cpu"
|
| 131 |
+
logit_scale: float | str | None = None
|
| 132 |
+
no_bias: bool = True
|
| 133 |
+
embedding_fraction: float = 1.0
|
| 134 |
+
norm_type: str = "low_precision_layernorm"
|
| 135 |
+
use_cache: bool = False
|
| 136 |
+
initializer_range: float = 0.02
|
| 137 |
+
tie_word_embeddings: bool = True
|
| 138 |
+
pad_token_id: int | None = None
|
| 139 |
+
bos_token_id: int | None = None
|
| 140 |
+
eos_token_id: int | list[int] | None = None
|
| 141 |
+
|
| 142 |
+
def __post_init__(self, **kwargs):
|
| 143 |
+
if self.attn_config is None:
|
| 144 |
+
self.attn_config = MptAttentionConfig()
|
| 145 |
+
elif isinstance(self.attn_config, dict):
|
| 146 |
+
self.attn_config = MptAttentionConfig(**self.attn_config)
|
| 147 |
+
super().__post_init__(**kwargs)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
__all__ = ["MptConfig"]
|
lib/python3.11/site-packages/transformers/models/mpt/modeling_mpt.py
ADDED
|
@@ -0,0 +1,761 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PyTorch MPT model."""
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from torch import nn
|
| 20 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss
|
| 21 |
+
from torch.nn import functional as F
|
| 22 |
+
|
| 23 |
+
from ...cache_utils import Cache, DynamicCache
|
| 24 |
+
from ...generation import GenerationMixin
|
| 25 |
+
from ...masking_utils import create_causal_mask
|
| 26 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 27 |
+
from ...modeling_outputs import (
|
| 28 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 29 |
+
CausalLMOutputWithCrossAttentions,
|
| 30 |
+
QuestionAnsweringModelOutput,
|
| 31 |
+
SequenceClassifierOutputWithPast,
|
| 32 |
+
TokenClassifierOutput,
|
| 33 |
+
)
|
| 34 |
+
from ...modeling_utils import PreTrainedModel
|
| 35 |
+
from ...utils import auto_docstring, logging
|
| 36 |
+
from .configuration_mpt import MptConfig
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
logger = logging.get_logger(__name__)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def build_mpt_alibi_tensor(num_heads, sequence_length, alibi_bias_max=8, device=None):
|
| 43 |
+
r"""
|
| 44 |
+
Link to paper: https://huggingface.co/papers/2108.12409 - Alibi tensor is not causal as the original paper mentions, it
|
| 45 |
+
relies on a translation invariance of softmax for quick implementation. This implementation has been copied from
|
| 46 |
+
the alibi implementation of MPT source code that led to slightly different results than the Bloom alibi:
|
| 47 |
+
https://huggingface.co/mosaicml/mpt-7b/blob/main/attention.py#L292
|
| 48 |
+
"""
|
| 49 |
+
alibi = torch.arange(1 - sequence_length, 1, dtype=torch.int32, device=device).view(1, 1, 1, sequence_length)
|
| 50 |
+
num_heads_power_of_2 = 2 ** math.ceil(math.log2(num_heads))
|
| 51 |
+
|
| 52 |
+
base = torch.arange(1, num_heads_power_of_2 + 1, dtype=torch.int64, device=device).float()
|
| 53 |
+
base = base * (alibi_bias_max / num_heads_power_of_2)
|
| 54 |
+
|
| 55 |
+
slopes = 1.0 / torch.pow(2, base)
|
| 56 |
+
slopes = slopes.view(1, num_heads_power_of_2, 1, 1)
|
| 57 |
+
|
| 58 |
+
if num_heads_power_of_2 != num_heads:
|
| 59 |
+
slopes = torch.concat([slopes[:, 1::2, ...], slopes[:, ::2, ...]], dim=1)[:, :num_heads, ...]
|
| 60 |
+
|
| 61 |
+
alibi = alibi * slopes
|
| 62 |
+
return alibi.squeeze(0)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class MptAttention(nn.Module):
|
| 66 |
+
"""Multi-head self attention.
|
| 67 |
+
Using torch or triton attention implementation enables user to also use additive bias.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
def __init__(self, config: MptConfig, layer_idx: int | None = None):
|
| 71 |
+
super().__init__()
|
| 72 |
+
self.hidden_size = config.hidden_size
|
| 73 |
+
self.n_heads = config.n_heads
|
| 74 |
+
self.max_seq_length = config.max_seq_len
|
| 75 |
+
self.head_dim = self.hidden_size // self.n_heads
|
| 76 |
+
self.softmax_scale = config.attn_config.softmax_scale
|
| 77 |
+
if self.softmax_scale is None:
|
| 78 |
+
self.softmax_scale = 1 / math.sqrt(self.hidden_size / self.n_heads)
|
| 79 |
+
|
| 80 |
+
self.attn_dropout_p = config.attn_config.attn_pdrop
|
| 81 |
+
self.clip_qkv = config.attn_config.clip_qkv
|
| 82 |
+
self.Wqkv = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=False)
|
| 83 |
+
self.out_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
| 84 |
+
self.layer_idx = layer_idx
|
| 85 |
+
|
| 86 |
+
def forward(
|
| 87 |
+
self,
|
| 88 |
+
hidden_states: torch.Tensor,
|
| 89 |
+
position_bias: torch.Tensor,
|
| 90 |
+
past_key_values: Cache | None = None,
|
| 91 |
+
attention_mask: torch.Tensor | None = None,
|
| 92 |
+
**kwargs,
|
| 93 |
+
):
|
| 94 |
+
batch_size, seq_length = hidden_states.shape[:2]
|
| 95 |
+
|
| 96 |
+
mixed_qkv = self.Wqkv(hidden_states)
|
| 97 |
+
if self.clip_qkv:
|
| 98 |
+
mixed_qkv = mixed_qkv.clamp(min=-self.clip_qkv, max=self.clip_qkv)
|
| 99 |
+
|
| 100 |
+
query_states, key_states, value_states = mixed_qkv.chunk(3, dim=2)
|
| 101 |
+
query_states = query_states.reshape(batch_size, seq_length, self.n_heads, self.head_dim).transpose(1, 2)
|
| 102 |
+
key_states = key_states.reshape(batch_size, seq_length, self.n_heads, self.head_dim).transpose(1, 2)
|
| 103 |
+
value_states = value_states.reshape(batch_size, seq_length, self.n_heads, self.head_dim).transpose(1, 2)
|
| 104 |
+
|
| 105 |
+
if past_key_values is not None:
|
| 106 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 107 |
+
|
| 108 |
+
attention_scores = torch.matmul(query_states, key_states.transpose(-1, -2)) * self.softmax_scale
|
| 109 |
+
query_length = seq_length if past_key_values is None else seq_length + past_key_values.get_seq_length()
|
| 110 |
+
|
| 111 |
+
if position_bias is not None:
|
| 112 |
+
if len(position_bias.shape) != 3:
|
| 113 |
+
raise ValueError(f"Expecting position_bias shape to be 3 dimensions, got {len(position_bias.shape)}")
|
| 114 |
+
key_length = key_states.shape[-2]
|
| 115 |
+
|
| 116 |
+
position_bias_query_index = max(0, position_bias.size(1) - query_length)
|
| 117 |
+
position_bias_key_index = max(0, position_bias.size(2) - key_length)
|
| 118 |
+
|
| 119 |
+
position_bias = position_bias[:, position_bias_query_index:, position_bias_key_index:]
|
| 120 |
+
|
| 121 |
+
attention_scores = attention_scores + position_bias
|
| 122 |
+
|
| 123 |
+
if attention_mask is not None:
|
| 124 |
+
attention_scores = attention_scores.masked_fill(attention_mask, torch.finfo(query_states.dtype).min)
|
| 125 |
+
|
| 126 |
+
# (batch_size, n_heads, seq_length, key_length)
|
| 127 |
+
attn_weights = nn.functional.softmax(attention_scores.float(), dim=-1).to(value_states.dtype)
|
| 128 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attn_dropout_p, training=self.training)
|
| 129 |
+
|
| 130 |
+
context_states = torch.matmul(attn_weights, value_states)
|
| 131 |
+
context_states = context_states.permute(0, 2, 1, 3).contiguous().view(batch_size, seq_length, -1)
|
| 132 |
+
attn_output = self.out_proj(context_states)
|
| 133 |
+
|
| 134 |
+
return attn_output, attn_weights
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class MptMLP(nn.Module):
|
| 138 |
+
def __init__(self, config: MptConfig):
|
| 139 |
+
super().__init__()
|
| 140 |
+
hidden_size = config.hidden_size
|
| 141 |
+
|
| 142 |
+
self.up_proj = nn.Linear(hidden_size, 4 * hidden_size, bias=False)
|
| 143 |
+
self.act = nn.GELU(approximate="none")
|
| 144 |
+
self.down_proj = nn.Linear(4 * hidden_size, hidden_size, bias=False)
|
| 145 |
+
self.hidden_dropout = config.attn_config.attn_pdrop
|
| 146 |
+
|
| 147 |
+
def forward(self, hidden_states: torch.Tensor, residual: torch.Tensor) -> torch.Tensor:
|
| 148 |
+
hidden_states = self.act(self.up_proj(hidden_states))
|
| 149 |
+
|
| 150 |
+
intermediate_output = self.down_proj(hidden_states)
|
| 151 |
+
|
| 152 |
+
output = F.dropout(intermediate_output, p=self.hidden_dropout, training=self.training)
|
| 153 |
+
output = output + residual
|
| 154 |
+
|
| 155 |
+
return output
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class MptBlock(GradientCheckpointingLayer):
|
| 159 |
+
def __init__(self, config: MptConfig, layer_idx: int | None = None):
|
| 160 |
+
super().__init__()
|
| 161 |
+
hidden_size = config.hidden_size
|
| 162 |
+
|
| 163 |
+
self.norm_1 = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
| 164 |
+
# backward compatibility with weights on the Hub
|
| 165 |
+
self.norm_1.bias = None
|
| 166 |
+
|
| 167 |
+
self.num_heads = config.n_heads
|
| 168 |
+
self.attn = MptAttention(config, layer_idx)
|
| 169 |
+
|
| 170 |
+
self.norm_2 = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
| 171 |
+
# backward compatibility with weights on the Hub
|
| 172 |
+
self.norm_2.bias = None
|
| 173 |
+
|
| 174 |
+
self.ffn = MptMLP(config)
|
| 175 |
+
|
| 176 |
+
self.dropout_rate = config.attn_config.attn_pdrop
|
| 177 |
+
self.resid_attn_dropout = nn.Dropout(self.dropout_rate)
|
| 178 |
+
|
| 179 |
+
def forward(
|
| 180 |
+
self,
|
| 181 |
+
hidden_states: torch.Tensor,
|
| 182 |
+
position_bias: torch.Tensor,
|
| 183 |
+
attention_mask: torch.Tensor,
|
| 184 |
+
layer_past: Cache | None = None,
|
| 185 |
+
use_cache: bool = False,
|
| 186 |
+
output_attentions: bool = False,
|
| 187 |
+
**kwargs,
|
| 188 |
+
):
|
| 189 |
+
# hidden_states: [batch_size, seq_length, hidden_size]
|
| 190 |
+
# Layer norm at the beginning of the transformer layer.
|
| 191 |
+
layernorm_output = self.norm_1(hidden_states)
|
| 192 |
+
|
| 193 |
+
residual = hidden_states
|
| 194 |
+
|
| 195 |
+
# Self attention.
|
| 196 |
+
attn_outputs, attn_weights = self.attn(
|
| 197 |
+
layernorm_output,
|
| 198 |
+
position_bias=position_bias,
|
| 199 |
+
attention_mask=attention_mask,
|
| 200 |
+
past_key_values=layer_past,
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
hidden_states = self.resid_attn_dropout(attn_outputs) + residual
|
| 204 |
+
|
| 205 |
+
layernorm_output = self.norm_2(hidden_states)
|
| 206 |
+
|
| 207 |
+
# Get residual
|
| 208 |
+
residual = hidden_states
|
| 209 |
+
|
| 210 |
+
# MLP.
|
| 211 |
+
output = self.ffn(layernorm_output, residual)
|
| 212 |
+
return output, attn_weights
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
@auto_docstring
|
| 216 |
+
class MptPreTrainedModel(PreTrainedModel):
|
| 217 |
+
config: MptConfig
|
| 218 |
+
base_model_prefix = "transformer"
|
| 219 |
+
supports_gradient_checkpointing = True
|
| 220 |
+
_no_split_modules = ["MptBlock"]
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
@auto_docstring
|
| 224 |
+
class MptModel(MptPreTrainedModel):
|
| 225 |
+
def __init__(self, config: MptConfig):
|
| 226 |
+
super().__init__(config)
|
| 227 |
+
|
| 228 |
+
self.hidden_size = config.hidden_size
|
| 229 |
+
self.num_heads = config.n_heads
|
| 230 |
+
|
| 231 |
+
# Embedding + LN Embedding
|
| 232 |
+
self.wte = nn.Embedding(config.vocab_size, self.hidden_size)
|
| 233 |
+
|
| 234 |
+
# Transformer blocks
|
| 235 |
+
self.blocks = nn.ModuleList([MptBlock(config, layer_idx=i) for i in range(config.n_layers)])
|
| 236 |
+
|
| 237 |
+
# Final Layer Norm
|
| 238 |
+
self.norm_f = LayerNorm(self.hidden_size, eps=config.layer_norm_epsilon)
|
| 239 |
+
# backward compatibility with weights on the Hub
|
| 240 |
+
self.norm_f.bias = None
|
| 241 |
+
|
| 242 |
+
self.gradient_checkpointing = False
|
| 243 |
+
|
| 244 |
+
# Initialize weights and apply final processing
|
| 245 |
+
self.post_init()
|
| 246 |
+
|
| 247 |
+
def get_input_embeddings(self):
|
| 248 |
+
return self.wte
|
| 249 |
+
|
| 250 |
+
def build_mpt_alibi_tensor(self, num_heads, sequence_length, alibi_bias_max=8, device=None):
|
| 251 |
+
return build_mpt_alibi_tensor(num_heads, sequence_length, alibi_bias_max, device)
|
| 252 |
+
|
| 253 |
+
def set_input_embeddings(self, new_embeddings: torch.Tensor):
|
| 254 |
+
self.wte = new_embeddings
|
| 255 |
+
|
| 256 |
+
@auto_docstring
|
| 257 |
+
def forward(
|
| 258 |
+
self,
|
| 259 |
+
input_ids: torch.LongTensor | None = None,
|
| 260 |
+
past_key_values: Cache | None = None,
|
| 261 |
+
attention_mask: torch.Tensor | None = None,
|
| 262 |
+
inputs_embeds: torch.LongTensor | None = None,
|
| 263 |
+
use_cache: bool | None = None,
|
| 264 |
+
output_attentions: bool | None = None,
|
| 265 |
+
output_hidden_states: bool | None = None,
|
| 266 |
+
return_dict: bool | None = None,
|
| 267 |
+
**kwargs, # NOOP kwargs, for now
|
| 268 |
+
) -> tuple[torch.Tensor, ...] | BaseModelOutputWithPastAndCrossAttentions:
|
| 269 |
+
r"""
|
| 270 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
|
| 271 |
+
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
|
| 272 |
+
(`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
|
| 273 |
+
|
| 274 |
+
If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
|
| 275 |
+
`input_ids`.
|
| 276 |
+
|
| 277 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 278 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 279 |
+
|
| 280 |
+
[What are input IDs?](../glossary#input-ids)
|
| 281 |
+
"""
|
| 282 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 283 |
+
output_hidden_states = (
|
| 284 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 285 |
+
)
|
| 286 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 287 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 288 |
+
|
| 289 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 290 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 291 |
+
elif input_ids is not None:
|
| 292 |
+
batch_size, seq_length = input_ids.shape
|
| 293 |
+
elif inputs_embeds is not None:
|
| 294 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
| 295 |
+
else:
|
| 296 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 297 |
+
|
| 298 |
+
if self.gradient_checkpointing and self.training:
|
| 299 |
+
if use_cache:
|
| 300 |
+
logger.warning_once(
|
| 301 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 302 |
+
)
|
| 303 |
+
use_cache = False
|
| 304 |
+
|
| 305 |
+
if inputs_embeds is None:
|
| 306 |
+
inputs_embeds = self.wte(input_ids)
|
| 307 |
+
|
| 308 |
+
if use_cache and past_key_values is None:
|
| 309 |
+
past_key_values = DynamicCache(config=self.config)
|
| 310 |
+
|
| 311 |
+
hidden_states = inputs_embeds
|
| 312 |
+
|
| 313 |
+
all_self_attentions = () if output_attentions else None
|
| 314 |
+
all_hidden_states = () if output_hidden_states else None
|
| 315 |
+
|
| 316 |
+
# Compute alibi tensor: check build_alibi_tensor documentation
|
| 317 |
+
alibi = self.build_mpt_alibi_tensor(self.num_heads, self.config.max_seq_len, device=hidden_states.device)
|
| 318 |
+
|
| 319 |
+
causal_mask = create_causal_mask(
|
| 320 |
+
config=self.config,
|
| 321 |
+
inputs_embeds=inputs_embeds,
|
| 322 |
+
attention_mask=attention_mask,
|
| 323 |
+
past_key_values=past_key_values,
|
| 324 |
+
).to(torch.bool)
|
| 325 |
+
|
| 326 |
+
for block in self.blocks:
|
| 327 |
+
if output_hidden_states:
|
| 328 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 329 |
+
|
| 330 |
+
outputs = block(
|
| 331 |
+
hidden_states,
|
| 332 |
+
layer_past=past_key_values,
|
| 333 |
+
attention_mask=causal_mask,
|
| 334 |
+
use_cache=use_cache,
|
| 335 |
+
output_attentions=output_attentions,
|
| 336 |
+
position_bias=alibi,
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
hidden_states = outputs[0]
|
| 340 |
+
if output_attentions:
|
| 341 |
+
all_self_attentions = all_self_attentions + (outputs[1],)
|
| 342 |
+
|
| 343 |
+
# Add last hidden state
|
| 344 |
+
hidden_states = self.norm_f(hidden_states)
|
| 345 |
+
|
| 346 |
+
if output_hidden_states:
|
| 347 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 348 |
+
|
| 349 |
+
if not return_dict:
|
| 350 |
+
return tuple(
|
| 351 |
+
v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attentions] if v is not None
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 355 |
+
last_hidden_state=hidden_states,
|
| 356 |
+
past_key_values=past_key_values,
|
| 357 |
+
hidden_states=all_hidden_states,
|
| 358 |
+
attentions=all_self_attentions,
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
@auto_docstring(
|
| 363 |
+
custom_intro="""
|
| 364 |
+
The MPT Model transformer with a language modeling head on top (linear layer with weights tied to the input
|
| 365 |
+
embeddings).
|
| 366 |
+
"""
|
| 367 |
+
)
|
| 368 |
+
class MptForCausalLM(MptPreTrainedModel, GenerationMixin):
|
| 369 |
+
_tied_weights_keys = {"lm_head.weight": "transformer.wte.weight"}
|
| 370 |
+
|
| 371 |
+
def __init__(self, config: MptConfig):
|
| 372 |
+
super().__init__(config)
|
| 373 |
+
self.transformer = MptModel(config)
|
| 374 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 375 |
+
|
| 376 |
+
# Initialize weights and apply final processing
|
| 377 |
+
self.post_init()
|
| 378 |
+
|
| 379 |
+
def set_output_embeddings(self, new_embeddings: torch.Tensor):
|
| 380 |
+
self.lm_head = new_embeddings
|
| 381 |
+
|
| 382 |
+
@auto_docstring
|
| 383 |
+
def forward(
|
| 384 |
+
self,
|
| 385 |
+
input_ids: torch.LongTensor | None = None,
|
| 386 |
+
past_key_values: Cache | None = None,
|
| 387 |
+
attention_mask: torch.Tensor | None = None,
|
| 388 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 389 |
+
labels: torch.Tensor | None = None,
|
| 390 |
+
use_cache: bool | None = None,
|
| 391 |
+
output_attentions: bool | None = None,
|
| 392 |
+
output_hidden_states: bool | None = None,
|
| 393 |
+
return_dict: bool | None = None,
|
| 394 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 395 |
+
**kwargs,
|
| 396 |
+
) -> tuple[torch.Tensor] | CausalLMOutputWithCrossAttentions:
|
| 397 |
+
r"""
|
| 398 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
|
| 399 |
+
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
|
| 400 |
+
(`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
|
| 401 |
+
|
| 402 |
+
If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
|
| 403 |
+
`input_ids`.
|
| 404 |
+
|
| 405 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 406 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 407 |
+
|
| 408 |
+
[What are input IDs?](../glossary#input-ids)
|
| 409 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 410 |
+
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
| 411 |
+
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
| 412 |
+
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
| 413 |
+
"""
|
| 414 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 415 |
+
|
| 416 |
+
transformer_outputs = self.transformer(
|
| 417 |
+
input_ids,
|
| 418 |
+
past_key_values=past_key_values,
|
| 419 |
+
attention_mask=attention_mask,
|
| 420 |
+
inputs_embeds=inputs_embeds,
|
| 421 |
+
use_cache=use_cache,
|
| 422 |
+
output_attentions=output_attentions,
|
| 423 |
+
output_hidden_states=output_hidden_states,
|
| 424 |
+
return_dict=return_dict,
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
hidden_states = transformer_outputs[0]
|
| 428 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 429 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 430 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 431 |
+
|
| 432 |
+
loss = None
|
| 433 |
+
if labels is not None:
|
| 434 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 435 |
+
|
| 436 |
+
if not return_dict:
|
| 437 |
+
output = (logits,) + transformer_outputs[1:]
|
| 438 |
+
return ((loss,) + output) if loss is not None else output
|
| 439 |
+
|
| 440 |
+
return CausalLMOutputWithCrossAttentions(
|
| 441 |
+
loss=loss,
|
| 442 |
+
logits=logits,
|
| 443 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 444 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 445 |
+
attentions=transformer_outputs.attentions,
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
@auto_docstring(
|
| 450 |
+
custom_intro="""
|
| 451 |
+
The MPT Model transformer with a sequence classification head on top (linear layer).
|
| 452 |
+
|
| 453 |
+
[`MptForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
| 454 |
+
(e.g. GPT-1) do.
|
| 455 |
+
|
| 456 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
| 457 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
| 458 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
| 459 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
| 460 |
+
each row of the batch).
|
| 461 |
+
"""
|
| 462 |
+
)
|
| 463 |
+
class MptForSequenceClassification(MptPreTrainedModel):
|
| 464 |
+
def __init__(self, config: MptConfig):
|
| 465 |
+
super().__init__(config)
|
| 466 |
+
self.num_labels = config.num_labels
|
| 467 |
+
self.transformer = MptModel(config)
|
| 468 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)
|
| 469 |
+
|
| 470 |
+
# Initialize weights and apply final processing
|
| 471 |
+
self.post_init()
|
| 472 |
+
|
| 473 |
+
def set_output_embeddings(self, new_embeddings: torch.Tensor):
|
| 474 |
+
self.score = new_embeddings
|
| 475 |
+
|
| 476 |
+
@auto_docstring
|
| 477 |
+
def forward(
|
| 478 |
+
self,
|
| 479 |
+
input_ids: torch.LongTensor | None = None,
|
| 480 |
+
past_key_values: Cache | None = None,
|
| 481 |
+
attention_mask: torch.Tensor | None = None,
|
| 482 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 483 |
+
labels: torch.Tensor | None = None,
|
| 484 |
+
use_cache: bool | None = None,
|
| 485 |
+
output_attentions: bool | None = None,
|
| 486 |
+
output_hidden_states: bool | None = None,
|
| 487 |
+
return_dict: bool | None = None,
|
| 488 |
+
**kwargs,
|
| 489 |
+
) -> tuple[torch.Tensor] | SequenceClassifierOutputWithPast:
|
| 490 |
+
r"""
|
| 491 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
|
| 492 |
+
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
|
| 493 |
+
(`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
|
| 494 |
+
|
| 495 |
+
If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
|
| 496 |
+
`input_ids`.
|
| 497 |
+
|
| 498 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 499 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 500 |
+
|
| 501 |
+
[What are input IDs?](../glossary#input-ids)
|
| 502 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 503 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 504 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 505 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 506 |
+
"""
|
| 507 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 508 |
+
|
| 509 |
+
transformer_outputs = self.transformer(
|
| 510 |
+
input_ids,
|
| 511 |
+
past_key_values=past_key_values,
|
| 512 |
+
attention_mask=attention_mask,
|
| 513 |
+
inputs_embeds=inputs_embeds,
|
| 514 |
+
use_cache=use_cache,
|
| 515 |
+
output_attentions=output_attentions,
|
| 516 |
+
output_hidden_states=output_hidden_states,
|
| 517 |
+
return_dict=return_dict,
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
hidden_states = transformer_outputs[0]
|
| 521 |
+
logits = self.score(hidden_states)
|
| 522 |
+
|
| 523 |
+
if input_ids is not None:
|
| 524 |
+
batch_size = input_ids.shape[0]
|
| 525 |
+
else:
|
| 526 |
+
batch_size = inputs_embeds.shape[0]
|
| 527 |
+
|
| 528 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
| 529 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
| 530 |
+
if self.config.pad_token_id is None:
|
| 531 |
+
last_non_pad_token = -1
|
| 532 |
+
elif input_ids is not None:
|
| 533 |
+
# To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
|
| 534 |
+
non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
|
| 535 |
+
token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
|
| 536 |
+
last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
|
| 537 |
+
else:
|
| 538 |
+
last_non_pad_token = -1
|
| 539 |
+
logger.warning_once(
|
| 540 |
+
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
|
| 541 |
+
"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
|
| 545 |
+
|
| 546 |
+
loss = None
|
| 547 |
+
if labels is not None:
|
| 548 |
+
if self.config.problem_type is None:
|
| 549 |
+
if self.num_labels == 1:
|
| 550 |
+
self.config.problem_type = "regression"
|
| 551 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 552 |
+
self.config.problem_type = "single_label_classification"
|
| 553 |
+
else:
|
| 554 |
+
self.config.problem_type = "multi_label_classification"
|
| 555 |
+
|
| 556 |
+
if self.config.problem_type == "regression":
|
| 557 |
+
loss_fct = MSELoss()
|
| 558 |
+
if self.num_labels == 1:
|
| 559 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
| 560 |
+
else:
|
| 561 |
+
loss = loss_fct(pooled_logits, labels)
|
| 562 |
+
elif self.config.problem_type == "single_label_classification":
|
| 563 |
+
loss_fct = CrossEntropyLoss()
|
| 564 |
+
loss = loss_fct(pooled_logits, labels)
|
| 565 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 566 |
+
loss_fct = BCEWithLogitsLoss()
|
| 567 |
+
loss = loss_fct(pooled_logits, labels)
|
| 568 |
+
if not return_dict:
|
| 569 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
| 570 |
+
return ((loss,) + output) if loss is not None else output
|
| 571 |
+
|
| 572 |
+
return SequenceClassifierOutputWithPast(
|
| 573 |
+
loss=loss,
|
| 574 |
+
logits=pooled_logits,
|
| 575 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 576 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 577 |
+
attentions=transformer_outputs.attentions,
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
@auto_docstring
|
| 582 |
+
class MptForTokenClassification(MptPreTrainedModel):
|
| 583 |
+
def __init__(self, config: MptConfig):
|
| 584 |
+
super().__init__(config)
|
| 585 |
+
self.num_labels = config.num_labels
|
| 586 |
+
|
| 587 |
+
self.transformer = MptModel(config)
|
| 588 |
+
if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
|
| 589 |
+
classifier_dropout = config.classifier_dropout
|
| 590 |
+
elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
|
| 591 |
+
classifier_dropout = config.hidden_dropout
|
| 592 |
+
else:
|
| 593 |
+
classifier_dropout = 0.1
|
| 594 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 595 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 596 |
+
|
| 597 |
+
# Initialize weights and apply final processing
|
| 598 |
+
self.post_init()
|
| 599 |
+
|
| 600 |
+
@auto_docstring
|
| 601 |
+
def forward(
|
| 602 |
+
self,
|
| 603 |
+
input_ids: torch.LongTensor | None = None,
|
| 604 |
+
past_key_values: Cache | None = None,
|
| 605 |
+
attention_mask: torch.Tensor | None = None,
|
| 606 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 607 |
+
labels: torch.Tensor | None = None,
|
| 608 |
+
use_cache: bool | None = None,
|
| 609 |
+
output_attentions: bool | None = None,
|
| 610 |
+
output_hidden_states: bool | None = None,
|
| 611 |
+
return_dict: bool | None = None,
|
| 612 |
+
**deprecated_arguments,
|
| 613 |
+
) -> tuple[torch.Tensor] | TokenClassifierOutput:
|
| 614 |
+
r"""
|
| 615 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
|
| 616 |
+
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
|
| 617 |
+
(`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
|
| 618 |
+
|
| 619 |
+
If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
|
| 620 |
+
`input_ids`.
|
| 621 |
+
|
| 622 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 623 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 624 |
+
|
| 625 |
+
[What are input IDs?](../glossary#input-ids)
|
| 626 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 627 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 628 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 629 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 630 |
+
"""
|
| 631 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 632 |
+
|
| 633 |
+
transformer_outputs = self.transformer(
|
| 634 |
+
input_ids,
|
| 635 |
+
past_key_values=past_key_values,
|
| 636 |
+
attention_mask=attention_mask,
|
| 637 |
+
inputs_embeds=inputs_embeds,
|
| 638 |
+
use_cache=use_cache,
|
| 639 |
+
output_attentions=output_attentions,
|
| 640 |
+
output_hidden_states=output_hidden_states,
|
| 641 |
+
return_dict=return_dict,
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
hidden_states = transformer_outputs[0]
|
| 645 |
+
hidden_states = self.dropout(hidden_states)
|
| 646 |
+
logits = self.classifier(hidden_states)
|
| 647 |
+
|
| 648 |
+
loss = None
|
| 649 |
+
if labels is not None:
|
| 650 |
+
# move labels to correct device
|
| 651 |
+
labels = labels.to(logits.device)
|
| 652 |
+
batch_size, seq_length = labels.shape
|
| 653 |
+
loss_fct = CrossEntropyLoss()
|
| 654 |
+
loss = loss_fct(
|
| 655 |
+
logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
|
| 656 |
+
)
|
| 657 |
+
|
| 658 |
+
if not return_dict:
|
| 659 |
+
output = (logits,) + transformer_outputs[2:]
|
| 660 |
+
return ((loss,) + output) if loss is not None else output
|
| 661 |
+
|
| 662 |
+
return TokenClassifierOutput(
|
| 663 |
+
loss=loss,
|
| 664 |
+
logits=logits,
|
| 665 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 666 |
+
attentions=transformer_outputs.attentions,
|
| 667 |
+
)
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
@auto_docstring
|
| 671 |
+
class MptForQuestionAnswering(MptPreTrainedModel):
|
| 672 |
+
def __init__(self, config):
|
| 673 |
+
super().__init__(config)
|
| 674 |
+
self.transformer = MptModel(config)
|
| 675 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
| 676 |
+
|
| 677 |
+
# Initialize weights and apply final processing
|
| 678 |
+
self.post_init()
|
| 679 |
+
|
| 680 |
+
@auto_docstring
|
| 681 |
+
def forward(
|
| 682 |
+
self,
|
| 683 |
+
input_ids: torch.LongTensor | None = None,
|
| 684 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 685 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 686 |
+
start_positions: torch.LongTensor | None = None,
|
| 687 |
+
end_positions: torch.LongTensor | None = None,
|
| 688 |
+
output_attentions: bool | None = None,
|
| 689 |
+
output_hidden_states: bool | None = None,
|
| 690 |
+
return_dict: bool | None = None,
|
| 691 |
+
**kwargs,
|
| 692 |
+
) -> tuple | QuestionAnsweringModelOutput:
|
| 693 |
+
r"""
|
| 694 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
|
| 695 |
+
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
|
| 696 |
+
(`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
|
| 697 |
+
|
| 698 |
+
If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
|
| 699 |
+
`input_ids`.
|
| 700 |
+
|
| 701 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 702 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 703 |
+
|
| 704 |
+
[What are input IDs?](../glossary#input-ids)
|
| 705 |
+
"""
|
| 706 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 707 |
+
|
| 708 |
+
outputs = self.transformer(
|
| 709 |
+
input_ids,
|
| 710 |
+
attention_mask=attention_mask,
|
| 711 |
+
inputs_embeds=inputs_embeds,
|
| 712 |
+
output_attentions=output_attentions,
|
| 713 |
+
output_hidden_states=output_hidden_states,
|
| 714 |
+
return_dict=return_dict,
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
sequence_output = outputs[0]
|
| 718 |
+
|
| 719 |
+
logits = self.qa_outputs(sequence_output)
|
| 720 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 721 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 722 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 723 |
+
|
| 724 |
+
total_loss = None
|
| 725 |
+
if start_positions is not None and end_positions is not None:
|
| 726 |
+
# If we are on multi-GPU, split add a dimension
|
| 727 |
+
if len(start_positions.size()) > 1:
|
| 728 |
+
start_positions = start_positions.squeeze(-1)
|
| 729 |
+
if len(end_positions.size()) > 1:
|
| 730 |
+
end_positions = end_positions.squeeze(-1)
|
| 731 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 732 |
+
ignored_index = start_logits.size(1)
|
| 733 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 734 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 735 |
+
|
| 736 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 737 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 738 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 739 |
+
total_loss = (start_loss + end_loss) / 2
|
| 740 |
+
|
| 741 |
+
if not return_dict:
|
| 742 |
+
output = (start_logits, end_logits) + outputs[2:]
|
| 743 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 744 |
+
|
| 745 |
+
return QuestionAnsweringModelOutput(
|
| 746 |
+
loss=total_loss,
|
| 747 |
+
start_logits=start_logits,
|
| 748 |
+
end_logits=end_logits,
|
| 749 |
+
hidden_states=outputs.hidden_states,
|
| 750 |
+
attentions=outputs.attentions,
|
| 751 |
+
)
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
__all__ = [
|
| 755 |
+
"MptForCausalLM",
|
| 756 |
+
"MptModel",
|
| 757 |
+
"MptPreTrainedModel",
|
| 758 |
+
"MptForSequenceClassification",
|
| 759 |
+
"MptForTokenClassification",
|
| 760 |
+
"MptForQuestionAnswering",
|
| 761 |
+
]
|
lib/python3.11/site-packages/transformers/models/mra/__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_mra import *
|
| 22 |
+
from .modeling_mra import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.11/site-packages/transformers/models/mra/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (769 Bytes). View file
|
|
|
lib/python3.11/site-packages/transformers/models/mra/__pycache__/configuration_mra.cpython-311.pyc
ADDED
|
Binary file (3.34 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/mra/__pycache__/modeling_mra.cpython-311.pyc
ADDED
|
Binary file (69.8 kB). View file
|
|
|
lib/python3.11/site-packages/transformers/models/mra/configuration_mra.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""MRA model configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...utils import auto_docstring
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@auto_docstring(checkpoint="uw-madison/mra-base-512-4")
|
| 23 |
+
@strict
|
| 24 |
+
class MraConfig(PreTrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
block_per_row (`int`, *optional*, defaults to 4):
|
| 27 |
+
Used to set the budget for the high resolution scale.
|
| 28 |
+
approx_mode (`str`, *optional*, defaults to `"full"`):
|
| 29 |
+
Controls whether both low and high resolution approximations are used. Set to `"full"` for both low and
|
| 30 |
+
high resolution and `"sparse"` for only low resolution.
|
| 31 |
+
initial_prior_first_n_blocks (`int`, *optional*, defaults to 0):
|
| 32 |
+
The initial number of blocks for which high resolution is used.
|
| 33 |
+
initial_prior_diagonal_n_blocks (`int`, *optional*, defaults to 0):
|
| 34 |
+
The number of diagonal blocks for which high resolution is used.
|
| 35 |
+
|
| 36 |
+
Example:
|
| 37 |
+
|
| 38 |
+
```python
|
| 39 |
+
>>> from transformers import MraConfig, MraModel
|
| 40 |
+
|
| 41 |
+
>>> # Initializing a Mra uw-madison/mra-base-512-4 style configuration
|
| 42 |
+
>>> configuration = MraConfig()
|
| 43 |
+
|
| 44 |
+
>>> # Initializing a model (with random weights) from the uw-madison/mra-base-512-4 style configuration
|
| 45 |
+
>>> model = MraModel(configuration)
|
| 46 |
+
|
| 47 |
+
>>> # Accessing the model configuration
|
| 48 |
+
>>> configuration = model.config
|
| 49 |
+
```"""
|
| 50 |
+
|
| 51 |
+
model_type = "mra"
|
| 52 |
+
|
| 53 |
+
vocab_size: int = 50265
|
| 54 |
+
hidden_size: int = 768
|
| 55 |
+
num_hidden_layers: int = 12
|
| 56 |
+
num_attention_heads: int = 12
|
| 57 |
+
intermediate_size: int = 3072
|
| 58 |
+
hidden_act: str = "gelu"
|
| 59 |
+
hidden_dropout_prob: float | int = 0.1
|
| 60 |
+
attention_probs_dropout_prob: float | int = 0.1
|
| 61 |
+
max_position_embeddings: int = 512
|
| 62 |
+
type_vocab_size: int = 1
|
| 63 |
+
initializer_range: float = 0.02
|
| 64 |
+
layer_norm_eps: float = 1e-5
|
| 65 |
+
block_per_row: int = 4
|
| 66 |
+
approx_mode: str = "full"
|
| 67 |
+
initial_prior_first_n_blocks: int = 0
|
| 68 |
+
initial_prior_diagonal_n_blocks: int = 0
|
| 69 |
+
pad_token_id: int | None = 1
|
| 70 |
+
bos_token_id: int | None = 0
|
| 71 |
+
eos_token_id: int | list[int] | None = 2
|
| 72 |
+
add_cross_attention: bool = False
|
| 73 |
+
tie_word_embeddings: bool = True
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
__all__ = ["MraConfig"]
|
lib/python3.11/site-packages/transformers/models/mra/modeling_mra.py
ADDED
|
@@ -0,0 +1,1338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 University of Wisconsin-Madison and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PyTorch MRA model."""
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from torch import nn
|
| 20 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 21 |
+
|
| 22 |
+
from ... import initialization as init
|
| 23 |
+
from ...activations import ACT2FN
|
| 24 |
+
from ...masking_utils import create_bidirectional_mask
|
| 25 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 26 |
+
from ...modeling_outputs import (
|
| 27 |
+
BaseModelOutputWithCrossAttentions,
|
| 28 |
+
MaskedLMOutput,
|
| 29 |
+
MultipleChoiceModelOutput,
|
| 30 |
+
QuestionAnsweringModelOutput,
|
| 31 |
+
SequenceClassifierOutput,
|
| 32 |
+
TokenClassifierOutput,
|
| 33 |
+
)
|
| 34 |
+
from ...modeling_utils import PreTrainedModel
|
| 35 |
+
from ...pytorch_utils import apply_chunking_to_forward
|
| 36 |
+
from ...utils import (
|
| 37 |
+
auto_docstring,
|
| 38 |
+
is_cuda_platform,
|
| 39 |
+
is_kernels_available,
|
| 40 |
+
is_ninja_available,
|
| 41 |
+
is_torch_cuda_available,
|
| 42 |
+
logging,
|
| 43 |
+
)
|
| 44 |
+
from .configuration_mra import MraConfig
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
logger = logging.get_logger(__name__)
|
| 48 |
+
|
| 49 |
+
mra_cuda_kernel = None
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def load_cuda_kernels():
|
| 53 |
+
global mra_cuda_kernel
|
| 54 |
+
if not is_kernels_available():
|
| 55 |
+
raise ImportError("kernels is not installed, please install it with `pip install kernels`")
|
| 56 |
+
from ...integrations.hub_kernels import get_kernel
|
| 57 |
+
|
| 58 |
+
mra_cuda_kernel = get_kernel("kernels-community/mra")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def sparse_max(sparse_qk_prod, indices, query_num_block, key_num_block):
|
| 62 |
+
"""
|
| 63 |
+
Computes maximum values for softmax stability.
|
| 64 |
+
"""
|
| 65 |
+
if len(sparse_qk_prod.size()) != 4:
|
| 66 |
+
raise ValueError("sparse_qk_prod must be a 4-dimensional tensor.")
|
| 67 |
+
|
| 68 |
+
if len(indices.size()) != 2:
|
| 69 |
+
raise ValueError("indices must be a 2-dimensional tensor.")
|
| 70 |
+
|
| 71 |
+
if sparse_qk_prod.size(2) != 32:
|
| 72 |
+
raise ValueError("The size of the second dimension of sparse_qk_prod must be 32.")
|
| 73 |
+
|
| 74 |
+
if sparse_qk_prod.size(3) != 32:
|
| 75 |
+
raise ValueError("The size of the third dimension of sparse_qk_prod must be 32.")
|
| 76 |
+
|
| 77 |
+
index_vals = sparse_qk_prod.max(dim=-2).values.transpose(-1, -2)
|
| 78 |
+
index_vals = index_vals.contiguous()
|
| 79 |
+
|
| 80 |
+
indices = indices.int()
|
| 81 |
+
indices = indices.contiguous()
|
| 82 |
+
|
| 83 |
+
max_vals, max_vals_scatter = mra_cuda_kernel.index_max(index_vals, indices, query_num_block, key_num_block)
|
| 84 |
+
max_vals_scatter = max_vals_scatter.transpose(-1, -2)[:, :, None, :]
|
| 85 |
+
|
| 86 |
+
return max_vals, max_vals_scatter
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def sparse_mask(mask, indices, block_size=32):
|
| 90 |
+
"""
|
| 91 |
+
Converts attention mask to a sparse mask for high resolution logits.
|
| 92 |
+
"""
|
| 93 |
+
if len(mask.size()) != 2:
|
| 94 |
+
raise ValueError("mask must be a 2-dimensional tensor.")
|
| 95 |
+
|
| 96 |
+
if len(indices.size()) != 2:
|
| 97 |
+
raise ValueError("indices must be a 2-dimensional tensor.")
|
| 98 |
+
|
| 99 |
+
if mask.shape[0] != indices.shape[0]:
|
| 100 |
+
raise ValueError("mask and indices must have the same size in the zero-th dimension.")
|
| 101 |
+
|
| 102 |
+
batch_size, seq_len = mask.shape
|
| 103 |
+
num_block = seq_len // block_size
|
| 104 |
+
|
| 105 |
+
batch_idx = torch.arange(indices.size(0), dtype=torch.long, device=indices.device)
|
| 106 |
+
mask = mask.reshape(batch_size, num_block, block_size)
|
| 107 |
+
mask = mask[batch_idx[:, None], (indices % num_block).long(), :]
|
| 108 |
+
|
| 109 |
+
return mask
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def mm_to_sparse(dense_query, dense_key, indices, block_size=32):
|
| 113 |
+
"""
|
| 114 |
+
Performs Sampled Dense Matrix Multiplication.
|
| 115 |
+
"""
|
| 116 |
+
batch_size, query_size, dim = dense_query.size()
|
| 117 |
+
_, key_size, dim = dense_key.size()
|
| 118 |
+
|
| 119 |
+
if query_size % block_size != 0:
|
| 120 |
+
raise ValueError("query_size (size of first dimension of dense_query) must be divisible by block_size.")
|
| 121 |
+
|
| 122 |
+
if key_size % block_size != 0:
|
| 123 |
+
raise ValueError("key_size (size of first dimension of dense_key) must be divisible by block_size.")
|
| 124 |
+
|
| 125 |
+
dense_query = dense_query.reshape(batch_size, query_size // block_size, block_size, dim).transpose(-1, -2)
|
| 126 |
+
dense_key = dense_key.reshape(batch_size, key_size // block_size, block_size, dim).transpose(-1, -2)
|
| 127 |
+
|
| 128 |
+
if len(dense_query.size()) != 4:
|
| 129 |
+
raise ValueError("dense_query must be a 4-dimensional tensor.")
|
| 130 |
+
|
| 131 |
+
if len(dense_key.size()) != 4:
|
| 132 |
+
raise ValueError("dense_key must be a 4-dimensional tensor.")
|
| 133 |
+
|
| 134 |
+
if len(indices.size()) != 2:
|
| 135 |
+
raise ValueError("indices must be a 2-dimensional tensor.")
|
| 136 |
+
|
| 137 |
+
if dense_query.size(3) != 32:
|
| 138 |
+
raise ValueError("The third dimension of dense_query must be 32.")
|
| 139 |
+
|
| 140 |
+
if dense_key.size(3) != 32:
|
| 141 |
+
raise ValueError("The third dimension of dense_key must be 32.")
|
| 142 |
+
|
| 143 |
+
dense_query = dense_query.contiguous()
|
| 144 |
+
dense_key = dense_key.contiguous()
|
| 145 |
+
|
| 146 |
+
indices = indices.int()
|
| 147 |
+
indices = indices.contiguous()
|
| 148 |
+
|
| 149 |
+
return mra_cuda_kernel.mm_to_sparse(dense_query, dense_key, indices.int())
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def sparse_dense_mm(sparse_query, indices, dense_key, query_num_block, block_size=32):
|
| 153 |
+
"""
|
| 154 |
+
Performs matrix multiplication of a sparse matrix with a dense matrix.
|
| 155 |
+
"""
|
| 156 |
+
batch_size, key_size, dim = dense_key.size()
|
| 157 |
+
|
| 158 |
+
if key_size % block_size != 0:
|
| 159 |
+
raise ValueError("key_size (size of first dimension of dense_key) must be divisible by block_size.")
|
| 160 |
+
|
| 161 |
+
if sparse_query.size(2) != block_size:
|
| 162 |
+
raise ValueError("The size of the second dimension of sparse_query must be equal to the block_size.")
|
| 163 |
+
|
| 164 |
+
if sparse_query.size(3) != block_size:
|
| 165 |
+
raise ValueError("The size of the third dimension of sparse_query must be equal to the block_size.")
|
| 166 |
+
|
| 167 |
+
dense_key = dense_key.reshape(batch_size, key_size // block_size, block_size, dim).transpose(-1, -2)
|
| 168 |
+
|
| 169 |
+
if len(sparse_query.size()) != 4:
|
| 170 |
+
raise ValueError("sparse_query must be a 4-dimensional tensor.")
|
| 171 |
+
|
| 172 |
+
if len(dense_key.size()) != 4:
|
| 173 |
+
raise ValueError("dense_key must be a 4-dimensional tensor.")
|
| 174 |
+
|
| 175 |
+
if len(indices.size()) != 2:
|
| 176 |
+
raise ValueError("indices must be a 2-dimensional tensor.")
|
| 177 |
+
|
| 178 |
+
if dense_key.size(3) != 32:
|
| 179 |
+
raise ValueError("The size of the third dimension of dense_key must be 32.")
|
| 180 |
+
|
| 181 |
+
sparse_query = sparse_query.contiguous()
|
| 182 |
+
|
| 183 |
+
indices = indices.int()
|
| 184 |
+
indices = indices.contiguous()
|
| 185 |
+
dense_key = dense_key.contiguous()
|
| 186 |
+
|
| 187 |
+
dense_qk_prod = mra_cuda_kernel.sparse_dense_mm(sparse_query, indices, dense_key, query_num_block)
|
| 188 |
+
dense_qk_prod = dense_qk_prod.transpose(-1, -2).reshape(batch_size, query_num_block * block_size, dim)
|
| 189 |
+
return dense_qk_prod
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def transpose_indices(indices, dim_1_block, dim_2_block):
|
| 193 |
+
return ((indices % dim_2_block) * dim_1_block + torch.div(indices, dim_2_block, rounding_mode="floor")).long()
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class MraSampledDenseMatMul(torch.autograd.Function):
|
| 197 |
+
@staticmethod
|
| 198 |
+
def forward(ctx, dense_query, dense_key, indices, block_size):
|
| 199 |
+
sparse_qk_prod = mm_to_sparse(dense_query, dense_key, indices, block_size)
|
| 200 |
+
ctx.save_for_backward(dense_query, dense_key, indices)
|
| 201 |
+
ctx.block_size = block_size
|
| 202 |
+
return sparse_qk_prod
|
| 203 |
+
|
| 204 |
+
@staticmethod
|
| 205 |
+
def backward(ctx, grad):
|
| 206 |
+
dense_query, dense_key, indices = ctx.saved_tensors
|
| 207 |
+
block_size = ctx.block_size
|
| 208 |
+
query_num_block = dense_query.size(1) // block_size
|
| 209 |
+
key_num_block = dense_key.size(1) // block_size
|
| 210 |
+
indices_T = transpose_indices(indices, query_num_block, key_num_block)
|
| 211 |
+
grad_key = sparse_dense_mm(grad.transpose(-1, -2), indices_T, dense_query, key_num_block)
|
| 212 |
+
grad_query = sparse_dense_mm(grad, indices, dense_key, query_num_block)
|
| 213 |
+
return grad_query, grad_key, None, None
|
| 214 |
+
|
| 215 |
+
@staticmethod
|
| 216 |
+
def operator_call(dense_query, dense_key, indices, block_size=32):
|
| 217 |
+
return MraSampledDenseMatMul.apply(dense_query, dense_key, indices, block_size)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class MraSparseDenseMatMul(torch.autograd.Function):
|
| 221 |
+
@staticmethod
|
| 222 |
+
def forward(ctx, sparse_query, indices, dense_key, query_num_block):
|
| 223 |
+
sparse_qk_prod = sparse_dense_mm(sparse_query, indices, dense_key, query_num_block)
|
| 224 |
+
ctx.save_for_backward(sparse_query, indices, dense_key)
|
| 225 |
+
ctx.query_num_block = query_num_block
|
| 226 |
+
return sparse_qk_prod
|
| 227 |
+
|
| 228 |
+
@staticmethod
|
| 229 |
+
def backward(ctx, grad):
|
| 230 |
+
sparse_query, indices, dense_key = ctx.saved_tensors
|
| 231 |
+
query_num_block = ctx.query_num_block
|
| 232 |
+
key_num_block = dense_key.size(1) // sparse_query.size(-1)
|
| 233 |
+
indices_T = transpose_indices(indices, query_num_block, key_num_block)
|
| 234 |
+
grad_key = sparse_dense_mm(sparse_query.transpose(-1, -2), indices_T, grad, key_num_block)
|
| 235 |
+
grad_query = mm_to_sparse(grad, dense_key, indices)
|
| 236 |
+
return grad_query, None, grad_key, None
|
| 237 |
+
|
| 238 |
+
@staticmethod
|
| 239 |
+
def operator_call(sparse_query, indices, dense_key, query_num_block):
|
| 240 |
+
return MraSparseDenseMatMul.apply(sparse_query, indices, dense_key, query_num_block)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class MraReduceSum:
|
| 244 |
+
@staticmethod
|
| 245 |
+
def operator_call(sparse_query, indices, query_num_block, key_num_block):
|
| 246 |
+
batch_size, num_block, block_size, _ = sparse_query.size()
|
| 247 |
+
|
| 248 |
+
if len(sparse_query.size()) != 4:
|
| 249 |
+
raise ValueError("sparse_query must be a 4-dimensional tensor.")
|
| 250 |
+
|
| 251 |
+
if len(indices.size()) != 2:
|
| 252 |
+
raise ValueError("indices must be a 2-dimensional tensor.")
|
| 253 |
+
|
| 254 |
+
_, _, block_size, _ = sparse_query.size()
|
| 255 |
+
batch_size, num_block = indices.size()
|
| 256 |
+
|
| 257 |
+
sparse_query = sparse_query.sum(dim=2).reshape(batch_size * num_block, block_size)
|
| 258 |
+
|
| 259 |
+
batch_idx = torch.arange(indices.size(0), dtype=torch.long, device=indices.device)
|
| 260 |
+
global_idxes = (
|
| 261 |
+
torch.div(indices, key_num_block, rounding_mode="floor").long() + batch_idx[:, None] * query_num_block
|
| 262 |
+
).reshape(batch_size * num_block)
|
| 263 |
+
temp = torch.zeros(
|
| 264 |
+
(batch_size * query_num_block, block_size), dtype=sparse_query.dtype, device=sparse_query.device
|
| 265 |
+
)
|
| 266 |
+
output = temp.index_add(0, global_idxes, sparse_query).reshape(batch_size, query_num_block, block_size)
|
| 267 |
+
|
| 268 |
+
output = output.reshape(batch_size, query_num_block * block_size)
|
| 269 |
+
return output
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def get_low_resolution_logit(query, key, block_size, mask=None, value=None):
|
| 273 |
+
"""
|
| 274 |
+
Compute low resolution approximation.
|
| 275 |
+
"""
|
| 276 |
+
batch_size, seq_len, head_dim = query.size()
|
| 277 |
+
|
| 278 |
+
num_block_per_row = seq_len // block_size
|
| 279 |
+
|
| 280 |
+
value_hat = None
|
| 281 |
+
if mask is not None:
|
| 282 |
+
token_count = mask.reshape(batch_size, num_block_per_row, block_size).sum(dim=-1)
|
| 283 |
+
query_hat = query.reshape(batch_size, num_block_per_row, block_size, head_dim).sum(dim=-2) / (
|
| 284 |
+
token_count[:, :, None] + 1e-6
|
| 285 |
+
)
|
| 286 |
+
key_hat = key.reshape(batch_size, num_block_per_row, block_size, head_dim).sum(dim=-2) / (
|
| 287 |
+
token_count[:, :, None] + 1e-6
|
| 288 |
+
)
|
| 289 |
+
if value is not None:
|
| 290 |
+
value_hat = value.reshape(batch_size, num_block_per_row, block_size, head_dim).sum(dim=-2) / (
|
| 291 |
+
token_count[:, :, None] + 1e-6
|
| 292 |
+
)
|
| 293 |
+
else:
|
| 294 |
+
token_count = block_size * torch.ones(batch_size, num_block_per_row, dtype=torch.float, device=query.device)
|
| 295 |
+
query_hat = query.reshape(batch_size, num_block_per_row, block_size, head_dim).mean(dim=-2)
|
| 296 |
+
key_hat = key.reshape(batch_size, num_block_per_row, block_size, head_dim).mean(dim=-2)
|
| 297 |
+
if value is not None:
|
| 298 |
+
value_hat = value.reshape(batch_size, num_block_per_row, block_size, head_dim).mean(dim=-2)
|
| 299 |
+
|
| 300 |
+
low_resolution_logit = torch.matmul(query_hat, key_hat.transpose(-1, -2)) / math.sqrt(head_dim)
|
| 301 |
+
|
| 302 |
+
low_resolution_logit_row_max = low_resolution_logit.max(dim=-1, keepdims=True).values
|
| 303 |
+
|
| 304 |
+
if mask is not None:
|
| 305 |
+
low_resolution_logit = (
|
| 306 |
+
low_resolution_logit - 1e4 * ((token_count[:, None, :] * token_count[:, :, None]) < 0.5).float()
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
return low_resolution_logit, token_count, low_resolution_logit_row_max, value_hat
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def get_block_idxes(
|
| 313 |
+
low_resolution_logit, num_blocks, approx_mode, initial_prior_first_n_blocks, initial_prior_diagonal_n_blocks
|
| 314 |
+
):
|
| 315 |
+
"""
|
| 316 |
+
Compute the indices of the subset of components to be used in the approximation.
|
| 317 |
+
"""
|
| 318 |
+
batch_size, total_blocks_per_row, _ = low_resolution_logit.shape
|
| 319 |
+
|
| 320 |
+
if initial_prior_diagonal_n_blocks > 0:
|
| 321 |
+
offset = initial_prior_diagonal_n_blocks // 2
|
| 322 |
+
temp_mask = torch.ones(total_blocks_per_row, total_blocks_per_row, device=low_resolution_logit.device)
|
| 323 |
+
diagonal_mask = torch.tril(torch.triu(temp_mask, diagonal=-offset), diagonal=offset)
|
| 324 |
+
low_resolution_logit = low_resolution_logit + diagonal_mask[None, :, :] * 5e3
|
| 325 |
+
|
| 326 |
+
if initial_prior_first_n_blocks > 0:
|
| 327 |
+
low_resolution_logit[:, :initial_prior_first_n_blocks, :] = (
|
| 328 |
+
low_resolution_logit[:, :initial_prior_first_n_blocks, :] + 5e3
|
| 329 |
+
)
|
| 330 |
+
low_resolution_logit[:, :, :initial_prior_first_n_blocks] = (
|
| 331 |
+
low_resolution_logit[:, :, :initial_prior_first_n_blocks] + 5e3
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
top_k_vals = torch.topk(
|
| 335 |
+
low_resolution_logit.reshape(batch_size, -1), num_blocks, dim=-1, largest=True, sorted=False
|
| 336 |
+
)
|
| 337 |
+
indices = top_k_vals.indices
|
| 338 |
+
|
| 339 |
+
if approx_mode == "full":
|
| 340 |
+
threshold = top_k_vals.values.min(dim=-1).values
|
| 341 |
+
high_resolution_mask = (low_resolution_logit >= threshold[:, None, None]).float()
|
| 342 |
+
elif approx_mode == "sparse":
|
| 343 |
+
high_resolution_mask = None
|
| 344 |
+
else:
|
| 345 |
+
raise ValueError(f"{approx_mode} is not a valid approx_model value.")
|
| 346 |
+
|
| 347 |
+
return indices, high_resolution_mask
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def mra2_attention(
|
| 351 |
+
query,
|
| 352 |
+
key,
|
| 353 |
+
value,
|
| 354 |
+
mask,
|
| 355 |
+
num_blocks,
|
| 356 |
+
approx_mode,
|
| 357 |
+
block_size=32,
|
| 358 |
+
initial_prior_first_n_blocks=0,
|
| 359 |
+
initial_prior_diagonal_n_blocks=0,
|
| 360 |
+
):
|
| 361 |
+
"""
|
| 362 |
+
Use Mra to approximate self-attention.
|
| 363 |
+
"""
|
| 364 |
+
if mra_cuda_kernel is None:
|
| 365 |
+
return torch.zeros_like(query).requires_grad_()
|
| 366 |
+
|
| 367 |
+
batch_size, num_head, seq_len, head_dim = query.size()
|
| 368 |
+
meta_batch = batch_size * num_head
|
| 369 |
+
|
| 370 |
+
if seq_len % block_size != 0:
|
| 371 |
+
raise ValueError("sequence length must be divisible by the block_size.")
|
| 372 |
+
|
| 373 |
+
num_block_per_row = seq_len // block_size
|
| 374 |
+
|
| 375 |
+
query = query.reshape(meta_batch, seq_len, head_dim)
|
| 376 |
+
key = key.reshape(meta_batch, seq_len, head_dim)
|
| 377 |
+
value = value.reshape(meta_batch, seq_len, head_dim)
|
| 378 |
+
|
| 379 |
+
if mask is not None:
|
| 380 |
+
query = query * mask[:, :, None]
|
| 381 |
+
key = key * mask[:, :, None]
|
| 382 |
+
value = value * mask[:, :, None]
|
| 383 |
+
|
| 384 |
+
if approx_mode == "full":
|
| 385 |
+
low_resolution_logit, token_count, low_resolution_logit_row_max, value_hat = get_low_resolution_logit(
|
| 386 |
+
query, key, block_size, mask, value
|
| 387 |
+
)
|
| 388 |
+
elif approx_mode == "sparse":
|
| 389 |
+
with torch.no_grad():
|
| 390 |
+
low_resolution_logit, token_count, low_resolution_logit_row_max, _ = get_low_resolution_logit(
|
| 391 |
+
query, key, block_size, mask
|
| 392 |
+
)
|
| 393 |
+
else:
|
| 394 |
+
raise Exception('approx_mode must be "full" or "sparse"')
|
| 395 |
+
|
| 396 |
+
with torch.no_grad():
|
| 397 |
+
low_resolution_logit_normalized = low_resolution_logit - low_resolution_logit_row_max
|
| 398 |
+
indices, high_resolution_mask = get_block_idxes(
|
| 399 |
+
low_resolution_logit_normalized,
|
| 400 |
+
num_blocks,
|
| 401 |
+
approx_mode,
|
| 402 |
+
initial_prior_first_n_blocks,
|
| 403 |
+
initial_prior_diagonal_n_blocks,
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
high_resolution_logit = MraSampledDenseMatMul.operator_call(
|
| 407 |
+
query, key, indices, block_size=block_size
|
| 408 |
+
) / math.sqrt(head_dim)
|
| 409 |
+
max_vals, max_vals_scatter = sparse_max(high_resolution_logit, indices, num_block_per_row, num_block_per_row)
|
| 410 |
+
high_resolution_logit = high_resolution_logit - max_vals_scatter
|
| 411 |
+
if mask is not None:
|
| 412 |
+
high_resolution_logit = high_resolution_logit - 1e4 * (1 - sparse_mask(mask, indices)[:, :, :, None])
|
| 413 |
+
high_resolution_attn = torch.exp(high_resolution_logit)
|
| 414 |
+
high_resolution_attn_out = MraSparseDenseMatMul.operator_call(
|
| 415 |
+
high_resolution_attn, indices, value, num_block_per_row
|
| 416 |
+
)
|
| 417 |
+
high_resolution_normalizer = MraReduceSum.operator_call(
|
| 418 |
+
high_resolution_attn, indices, num_block_per_row, num_block_per_row
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
if approx_mode == "full":
|
| 422 |
+
low_resolution_attn = (
|
| 423 |
+
torch.exp(low_resolution_logit - low_resolution_logit_row_max - 1e4 * high_resolution_mask)
|
| 424 |
+
* token_count[:, None, :]
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
low_resolution_attn_out = (
|
| 428 |
+
torch.matmul(low_resolution_attn, value_hat)[:, :, None, :]
|
| 429 |
+
.repeat(1, 1, block_size, 1)
|
| 430 |
+
.reshape(meta_batch, seq_len, head_dim)
|
| 431 |
+
)
|
| 432 |
+
low_resolution_normalizer = (
|
| 433 |
+
low_resolution_attn.sum(dim=-1)[:, :, None].repeat(1, 1, block_size).reshape(meta_batch, seq_len)
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
log_correction = low_resolution_logit_row_max.repeat(1, 1, block_size).reshape(meta_batch, seq_len) - max_vals
|
| 437 |
+
if mask is not None:
|
| 438 |
+
log_correction = log_correction * mask
|
| 439 |
+
|
| 440 |
+
low_resolution_corr = torch.exp(log_correction * (log_correction <= 0).float())
|
| 441 |
+
low_resolution_attn_out = low_resolution_attn_out * low_resolution_corr[:, :, None]
|
| 442 |
+
low_resolution_normalizer = low_resolution_normalizer * low_resolution_corr
|
| 443 |
+
|
| 444 |
+
high_resolution_corr = torch.exp(-log_correction * (log_correction > 0).float())
|
| 445 |
+
high_resolution_attn_out = high_resolution_attn_out * high_resolution_corr[:, :, None]
|
| 446 |
+
high_resolution_normalizer = high_resolution_normalizer * high_resolution_corr
|
| 447 |
+
|
| 448 |
+
context_layer = (high_resolution_attn_out + low_resolution_attn_out) / (
|
| 449 |
+
high_resolution_normalizer[:, :, None] + low_resolution_normalizer[:, :, None] + 1e-6
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
elif approx_mode == "sparse":
|
| 453 |
+
context_layer = high_resolution_attn_out / (high_resolution_normalizer[:, :, None] + 1e-6)
|
| 454 |
+
else:
|
| 455 |
+
raise Exception('config.approx_mode must be "full" or "sparse"')
|
| 456 |
+
|
| 457 |
+
if mask is not None:
|
| 458 |
+
context_layer = context_layer * mask[:, :, None]
|
| 459 |
+
|
| 460 |
+
context_layer = context_layer.reshape(batch_size, num_head, seq_len, head_dim)
|
| 461 |
+
|
| 462 |
+
return context_layer
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
class MraEmbeddings(nn.Module):
|
| 466 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 467 |
+
|
| 468 |
+
def __init__(self, config):
|
| 469 |
+
super().__init__()
|
| 470 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 471 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings + 2, config.hidden_size)
|
| 472 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
| 473 |
+
|
| 474 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 475 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 476 |
+
|
| 477 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 478 |
+
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)) + 2)
|
| 479 |
+
self.register_buffer(
|
| 480 |
+
"token_type_ids",
|
| 481 |
+
torch.zeros(self.position_ids.size(), dtype=torch.long, device=self.position_ids.device),
|
| 482 |
+
persistent=False,
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
|
| 486 |
+
if input_ids is not None:
|
| 487 |
+
input_shape = input_ids.size()
|
| 488 |
+
else:
|
| 489 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 490 |
+
|
| 491 |
+
seq_length = input_shape[1]
|
| 492 |
+
|
| 493 |
+
if position_ids is None:
|
| 494 |
+
position_ids = self.position_ids[:, :seq_length]
|
| 495 |
+
|
| 496 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
| 497 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
| 498 |
+
# issue #5664
|
| 499 |
+
if token_type_ids is None:
|
| 500 |
+
if hasattr(self, "token_type_ids"):
|
| 501 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
| 502 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
| 503 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 504 |
+
else:
|
| 505 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 506 |
+
|
| 507 |
+
if inputs_embeds is None:
|
| 508 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 509 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 510 |
+
embeddings = inputs_embeds + token_type_embeddings
|
| 511 |
+
|
| 512 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 513 |
+
embeddings += position_embeddings
|
| 514 |
+
|
| 515 |
+
embeddings = self.LayerNorm(embeddings)
|
| 516 |
+
embeddings = self.dropout(embeddings)
|
| 517 |
+
return embeddings
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
class MraSelfAttention(nn.Module):
|
| 521 |
+
def __init__(self, config):
|
| 522 |
+
super().__init__()
|
| 523 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 524 |
+
raise ValueError(
|
| 525 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 526 |
+
f"heads ({config.num_attention_heads})"
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
kernel_loaded = mra_cuda_kernel is not None
|
| 530 |
+
if is_torch_cuda_available() and is_cuda_platform() and is_ninja_available() and not kernel_loaded:
|
| 531 |
+
try:
|
| 532 |
+
load_cuda_kernels()
|
| 533 |
+
except Exception as e:
|
| 534 |
+
logger.warning(f"Could not load the custom kernel for multi-scale deformable attention: {e}")
|
| 535 |
+
|
| 536 |
+
self.num_attention_heads = config.num_attention_heads
|
| 537 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 538 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 539 |
+
|
| 540 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 541 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 542 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 543 |
+
|
| 544 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 545 |
+
|
| 546 |
+
self.num_block = (config.max_position_embeddings // 32) * config.block_per_row
|
| 547 |
+
self.num_block = min(self.num_block, int((config.max_position_embeddings // 32) ** 2))
|
| 548 |
+
|
| 549 |
+
self.approx_mode = config.approx_mode
|
| 550 |
+
self.initial_prior_first_n_blocks = config.initial_prior_first_n_blocks
|
| 551 |
+
self.initial_prior_diagonal_n_blocks = config.initial_prior_diagonal_n_blocks
|
| 552 |
+
|
| 553 |
+
def forward(self, hidden_states, attention_mask=None):
|
| 554 |
+
batch_size, seq_len, _ = hidden_states.shape
|
| 555 |
+
query_layer = (
|
| 556 |
+
self.query(hidden_states)
|
| 557 |
+
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
|
| 558 |
+
.transpose(1, 2)
|
| 559 |
+
)
|
| 560 |
+
key_layer = (
|
| 561 |
+
self.key(hidden_states)
|
| 562 |
+
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
|
| 563 |
+
.transpose(1, 2)
|
| 564 |
+
)
|
| 565 |
+
value_layer = (
|
| 566 |
+
self.value(hidden_states)
|
| 567 |
+
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
|
| 568 |
+
.transpose(1, 2)
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
# revert changes made by float mask
|
| 572 |
+
attention_mask = 1.0 + attention_mask / 10000.0
|
| 573 |
+
attention_mask = (
|
| 574 |
+
attention_mask.squeeze()
|
| 575 |
+
.repeat(1, self.num_attention_heads, 1)
|
| 576 |
+
.reshape(batch_size * self.num_attention_heads, seq_len)
|
| 577 |
+
.int()
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
# The CUDA kernels are most efficient with inputs whose size is a multiple of a GPU's warp size (32). Inputs
|
| 581 |
+
# smaller than this are padded with zeros.
|
| 582 |
+
gpu_warp_size = 32
|
| 583 |
+
|
| 584 |
+
if self.attention_head_size < gpu_warp_size:
|
| 585 |
+
pad_size = batch_size, self.num_attention_heads, seq_len, gpu_warp_size - self.attention_head_size
|
| 586 |
+
|
| 587 |
+
query_layer = torch.cat([query_layer, torch.zeros(pad_size, device=query_layer.device)], dim=-1)
|
| 588 |
+
key_layer = torch.cat([key_layer, torch.zeros(pad_size, device=key_layer.device)], dim=-1)
|
| 589 |
+
value_layer = torch.cat([value_layer, torch.zeros(pad_size, device=value_layer.device)], dim=-1)
|
| 590 |
+
|
| 591 |
+
context_layer = mra2_attention(
|
| 592 |
+
query_layer.float(),
|
| 593 |
+
key_layer.float(),
|
| 594 |
+
value_layer.float(),
|
| 595 |
+
attention_mask.float(),
|
| 596 |
+
self.num_block,
|
| 597 |
+
approx_mode=self.approx_mode,
|
| 598 |
+
initial_prior_first_n_blocks=self.initial_prior_first_n_blocks,
|
| 599 |
+
initial_prior_diagonal_n_blocks=self.initial_prior_diagonal_n_blocks,
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
if self.attention_head_size < gpu_warp_size:
|
| 603 |
+
context_layer = context_layer[:, :, :, : self.attention_head_size]
|
| 604 |
+
|
| 605 |
+
context_layer = context_layer.reshape(batch_size, self.num_attention_heads, seq_len, self.attention_head_size)
|
| 606 |
+
|
| 607 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 608 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 609 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
| 610 |
+
|
| 611 |
+
outputs = (context_layer,)
|
| 612 |
+
|
| 613 |
+
return outputs
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput
|
| 617 |
+
class MraSelfOutput(nn.Module):
|
| 618 |
+
def __init__(self, config):
|
| 619 |
+
super().__init__()
|
| 620 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 621 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 622 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 623 |
+
|
| 624 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 625 |
+
hidden_states = self.dense(hidden_states)
|
| 626 |
+
hidden_states = self.dropout(hidden_states)
|
| 627 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 628 |
+
return hidden_states
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
class MraAttention(nn.Module):
|
| 632 |
+
def __init__(self, config):
|
| 633 |
+
super().__init__()
|
| 634 |
+
self.self = MraSelfAttention(config)
|
| 635 |
+
self.output = MraSelfOutput(config)
|
| 636 |
+
|
| 637 |
+
def forward(self, hidden_states, attention_mask=None):
|
| 638 |
+
self_outputs = self.self(hidden_states, attention_mask)
|
| 639 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 640 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 641 |
+
return outputs
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate
|
| 645 |
+
class MraIntermediate(nn.Module):
|
| 646 |
+
def __init__(self, config):
|
| 647 |
+
super().__init__()
|
| 648 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 649 |
+
if isinstance(config.hidden_act, str):
|
| 650 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 651 |
+
else:
|
| 652 |
+
self.intermediate_act_fn = config.hidden_act
|
| 653 |
+
|
| 654 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 655 |
+
hidden_states = self.dense(hidden_states)
|
| 656 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 657 |
+
return hidden_states
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput
|
| 661 |
+
class MraOutput(nn.Module):
|
| 662 |
+
def __init__(self, config):
|
| 663 |
+
super().__init__()
|
| 664 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 665 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 666 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 667 |
+
|
| 668 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 669 |
+
hidden_states = self.dense(hidden_states)
|
| 670 |
+
hidden_states = self.dropout(hidden_states)
|
| 671 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 672 |
+
return hidden_states
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
class MraLayer(GradientCheckpointingLayer):
|
| 676 |
+
def __init__(self, config):
|
| 677 |
+
super().__init__()
|
| 678 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 679 |
+
self.seq_len_dim = 1
|
| 680 |
+
self.attention = MraAttention(config)
|
| 681 |
+
self.add_cross_attention = config.add_cross_attention
|
| 682 |
+
self.intermediate = MraIntermediate(config)
|
| 683 |
+
self.output = MraOutput(config)
|
| 684 |
+
|
| 685 |
+
def forward(self, hidden_states, attention_mask=None):
|
| 686 |
+
self_attention_outputs = self.attention(hidden_states, attention_mask)
|
| 687 |
+
attention_output = self_attention_outputs[0]
|
| 688 |
+
|
| 689 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 690 |
+
|
| 691 |
+
layer_output = apply_chunking_to_forward(
|
| 692 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 693 |
+
)
|
| 694 |
+
outputs = (layer_output,) + outputs
|
| 695 |
+
|
| 696 |
+
return outputs
|
| 697 |
+
|
| 698 |
+
def feed_forward_chunk(self, attention_output):
|
| 699 |
+
intermediate_output = self.intermediate(attention_output)
|
| 700 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 701 |
+
return layer_output
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
class MraEncoder(nn.Module):
|
| 705 |
+
def __init__(self, config):
|
| 706 |
+
super().__init__()
|
| 707 |
+
self.config = config
|
| 708 |
+
self.layer = nn.ModuleList([MraLayer(config) for _ in range(config.num_hidden_layers)])
|
| 709 |
+
self.gradient_checkpointing = False
|
| 710 |
+
|
| 711 |
+
def forward(
|
| 712 |
+
self,
|
| 713 |
+
hidden_states,
|
| 714 |
+
attention_mask=None,
|
| 715 |
+
output_hidden_states=False,
|
| 716 |
+
return_dict=True,
|
| 717 |
+
):
|
| 718 |
+
all_hidden_states = () if output_hidden_states else None
|
| 719 |
+
|
| 720 |
+
for i, layer_module in enumerate(self.layer):
|
| 721 |
+
if output_hidden_states:
|
| 722 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 723 |
+
|
| 724 |
+
layer_outputs = layer_module(hidden_states, attention_mask)
|
| 725 |
+
|
| 726 |
+
hidden_states = layer_outputs[0]
|
| 727 |
+
|
| 728 |
+
if output_hidden_states:
|
| 729 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 730 |
+
|
| 731 |
+
if not return_dict:
|
| 732 |
+
return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
|
| 733 |
+
return BaseModelOutputWithCrossAttentions(
|
| 734 |
+
last_hidden_state=hidden_states,
|
| 735 |
+
hidden_states=all_hidden_states,
|
| 736 |
+
)
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
# Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform
|
| 740 |
+
class MraPredictionHeadTransform(nn.Module):
|
| 741 |
+
def __init__(self, config):
|
| 742 |
+
super().__init__()
|
| 743 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 744 |
+
if isinstance(config.hidden_act, str):
|
| 745 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
| 746 |
+
else:
|
| 747 |
+
self.transform_act_fn = config.hidden_act
|
| 748 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 749 |
+
|
| 750 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 751 |
+
hidden_states = self.dense(hidden_states)
|
| 752 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
| 753 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 754 |
+
return hidden_states
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->Mra
|
| 758 |
+
class MraLMPredictionHead(nn.Module):
|
| 759 |
+
def __init__(self, config):
|
| 760 |
+
super().__init__()
|
| 761 |
+
self.transform = MraPredictionHeadTransform(config)
|
| 762 |
+
|
| 763 |
+
# The output weights are the same as the input embeddings, but there is
|
| 764 |
+
# an output-only bias for each token.
|
| 765 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
|
| 766 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 767 |
+
|
| 768 |
+
def forward(self, hidden_states):
|
| 769 |
+
hidden_states = self.transform(hidden_states)
|
| 770 |
+
hidden_states = self.decoder(hidden_states)
|
| 771 |
+
return hidden_states
|
| 772 |
+
|
| 773 |
+
|
| 774 |
+
# Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->Mra
|
| 775 |
+
class MraOnlyMLMHead(nn.Module):
|
| 776 |
+
def __init__(self, config):
|
| 777 |
+
super().__init__()
|
| 778 |
+
self.predictions = MraLMPredictionHead(config)
|
| 779 |
+
|
| 780 |
+
def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
|
| 781 |
+
prediction_scores = self.predictions(sequence_output)
|
| 782 |
+
return prediction_scores
|
| 783 |
+
|
| 784 |
+
|
| 785 |
+
@auto_docstring
|
| 786 |
+
# Copied from transformers.models.yoso.modeling_yoso.YosoPreTrainedModel with Yoso->Mra,yoso->mra
|
| 787 |
+
class MraPreTrainedModel(PreTrainedModel):
|
| 788 |
+
config: MraConfig
|
| 789 |
+
base_model_prefix = "mra"
|
| 790 |
+
supports_gradient_checkpointing = True
|
| 791 |
+
|
| 792 |
+
@torch.no_grad()
|
| 793 |
+
def _init_weights(self, module: nn.Module):
|
| 794 |
+
"""Initialize the weights"""
|
| 795 |
+
super()._init_weights(module)
|
| 796 |
+
if isinstance(module, MraLMPredictionHead):
|
| 797 |
+
init.zeros_(module.bias)
|
| 798 |
+
elif isinstance(module, MraEmbeddings):
|
| 799 |
+
init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)) + 2)
|
| 800 |
+
init.zeros_(module.token_type_ids)
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
@auto_docstring
|
| 804 |
+
class MraModel(MraPreTrainedModel):
|
| 805 |
+
def __init__(self, config):
|
| 806 |
+
super().__init__(config)
|
| 807 |
+
self.config = config
|
| 808 |
+
|
| 809 |
+
self.embeddings = MraEmbeddings(config)
|
| 810 |
+
self.encoder = MraEncoder(config)
|
| 811 |
+
|
| 812 |
+
# Initialize weights and apply final processing
|
| 813 |
+
self.post_init()
|
| 814 |
+
|
| 815 |
+
def get_input_embeddings(self):
|
| 816 |
+
return self.embeddings.word_embeddings
|
| 817 |
+
|
| 818 |
+
def set_input_embeddings(self, value):
|
| 819 |
+
self.embeddings.word_embeddings = value
|
| 820 |
+
|
| 821 |
+
@auto_docstring
|
| 822 |
+
def forward(
|
| 823 |
+
self,
|
| 824 |
+
input_ids: torch.Tensor | None = None,
|
| 825 |
+
attention_mask: torch.Tensor | None = None,
|
| 826 |
+
token_type_ids: torch.Tensor | None = None,
|
| 827 |
+
position_ids: torch.Tensor | None = None,
|
| 828 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 829 |
+
output_hidden_states: bool | None = None,
|
| 830 |
+
return_dict: bool | None = None,
|
| 831 |
+
**kwargs,
|
| 832 |
+
) -> tuple | BaseModelOutputWithCrossAttentions:
|
| 833 |
+
output_hidden_states = (
|
| 834 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 835 |
+
)
|
| 836 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 837 |
+
|
| 838 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 839 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 840 |
+
elif input_ids is not None:
|
| 841 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 842 |
+
input_shape = input_ids.size()
|
| 843 |
+
elif inputs_embeds is not None:
|
| 844 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 845 |
+
else:
|
| 846 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 847 |
+
|
| 848 |
+
batch_size, seq_length = input_shape
|
| 849 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 850 |
+
|
| 851 |
+
if attention_mask is None:
|
| 852 |
+
attention_mask = torch.ones(((batch_size, seq_length)), device=device)
|
| 853 |
+
|
| 854 |
+
if token_type_ids is None:
|
| 855 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
| 856 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
| 857 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
| 858 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 859 |
+
else:
|
| 860 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 861 |
+
|
| 862 |
+
embedding_output = self.embeddings(
|
| 863 |
+
input_ids=input_ids,
|
| 864 |
+
position_ids=position_ids,
|
| 865 |
+
token_type_ids=token_type_ids,
|
| 866 |
+
inputs_embeds=inputs_embeds,
|
| 867 |
+
)
|
| 868 |
+
|
| 869 |
+
attention_mask = create_bidirectional_mask(
|
| 870 |
+
config=self.config,
|
| 871 |
+
inputs_embeds=embedding_output[:, 0:1, :], # Force q_len == 1
|
| 872 |
+
attention_mask=attention_mask,
|
| 873 |
+
# Force mask creation
|
| 874 |
+
and_mask_function=lambda *args: torch.tensor(True, dtype=torch.bool),
|
| 875 |
+
)
|
| 876 |
+
|
| 877 |
+
encoder_outputs = self.encoder(
|
| 878 |
+
embedding_output,
|
| 879 |
+
attention_mask=attention_mask,
|
| 880 |
+
output_hidden_states=output_hidden_states,
|
| 881 |
+
return_dict=return_dict,
|
| 882 |
+
)
|
| 883 |
+
sequence_output = encoder_outputs[0]
|
| 884 |
+
|
| 885 |
+
if not return_dict:
|
| 886 |
+
return (sequence_output,) + encoder_outputs[1:]
|
| 887 |
+
|
| 888 |
+
return BaseModelOutputWithCrossAttentions(
|
| 889 |
+
last_hidden_state=sequence_output,
|
| 890 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 891 |
+
attentions=encoder_outputs.attentions,
|
| 892 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
| 893 |
+
)
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
@auto_docstring
|
| 897 |
+
class MraForMaskedLM(MraPreTrainedModel):
|
| 898 |
+
_tied_weights_keys = {
|
| 899 |
+
"cls.predictions.decoder.bias": "cls.predictions.bias",
|
| 900 |
+
"cls.predictions.decoder.weight": "mra.embeddings.word_embeddings.weight",
|
| 901 |
+
}
|
| 902 |
+
|
| 903 |
+
def __init__(self, config):
|
| 904 |
+
super().__init__(config)
|
| 905 |
+
|
| 906 |
+
self.mra = MraModel(config)
|
| 907 |
+
self.cls = MraOnlyMLMHead(config)
|
| 908 |
+
|
| 909 |
+
# Initialize weights and apply final processing
|
| 910 |
+
self.post_init()
|
| 911 |
+
|
| 912 |
+
def get_output_embeddings(self):
|
| 913 |
+
return self.cls.predictions.decoder
|
| 914 |
+
|
| 915 |
+
def set_output_embeddings(self, new_embeddings):
|
| 916 |
+
self.cls.predictions.decoder = new_embeddings
|
| 917 |
+
self.cls.predictions.bias = new_embeddings.bias
|
| 918 |
+
|
| 919 |
+
@auto_docstring
|
| 920 |
+
def forward(
|
| 921 |
+
self,
|
| 922 |
+
input_ids: torch.Tensor | None = None,
|
| 923 |
+
attention_mask: torch.Tensor | None = None,
|
| 924 |
+
token_type_ids: torch.Tensor | None = None,
|
| 925 |
+
position_ids: torch.Tensor | None = None,
|
| 926 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 927 |
+
labels: torch.Tensor | None = None,
|
| 928 |
+
output_hidden_states: bool | None = None,
|
| 929 |
+
return_dict: bool | None = None,
|
| 930 |
+
**kwargs,
|
| 931 |
+
) -> tuple | MaskedLMOutput:
|
| 932 |
+
r"""
|
| 933 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 934 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 935 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 936 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 937 |
+
"""
|
| 938 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 939 |
+
|
| 940 |
+
outputs = self.mra(
|
| 941 |
+
input_ids,
|
| 942 |
+
attention_mask=attention_mask,
|
| 943 |
+
token_type_ids=token_type_ids,
|
| 944 |
+
position_ids=position_ids,
|
| 945 |
+
inputs_embeds=inputs_embeds,
|
| 946 |
+
output_hidden_states=output_hidden_states,
|
| 947 |
+
return_dict=return_dict,
|
| 948 |
+
)
|
| 949 |
+
|
| 950 |
+
sequence_output = outputs[0]
|
| 951 |
+
prediction_scores = self.cls(sequence_output)
|
| 952 |
+
|
| 953 |
+
masked_lm_loss = None
|
| 954 |
+
if labels is not None:
|
| 955 |
+
loss_fct = CrossEntropyLoss() # -100 index = padding token
|
| 956 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 957 |
+
|
| 958 |
+
if not return_dict:
|
| 959 |
+
output = (prediction_scores,) + outputs[1:]
|
| 960 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 961 |
+
|
| 962 |
+
return MaskedLMOutput(
|
| 963 |
+
loss=masked_lm_loss,
|
| 964 |
+
logits=prediction_scores,
|
| 965 |
+
hidden_states=outputs.hidden_states,
|
| 966 |
+
attentions=outputs.attentions,
|
| 967 |
+
)
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
# Copied from transformers.models.yoso.modeling_yoso.YosoClassificationHead with Yoso->Mra
|
| 971 |
+
class MraClassificationHead(nn.Module):
|
| 972 |
+
"""Head for sentence-level classification tasks."""
|
| 973 |
+
|
| 974 |
+
def __init__(self, config):
|
| 975 |
+
super().__init__()
|
| 976 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 977 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 978 |
+
self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
|
| 979 |
+
|
| 980 |
+
self.config = config
|
| 981 |
+
|
| 982 |
+
def forward(self, features, **kwargs):
|
| 983 |
+
x = features[:, 0, :] # take <s> token (equiv. to [CLS])
|
| 984 |
+
x = self.dropout(x)
|
| 985 |
+
x = self.dense(x)
|
| 986 |
+
x = ACT2FN[self.config.hidden_act](x)
|
| 987 |
+
x = self.dropout(x)
|
| 988 |
+
x = self.out_proj(x)
|
| 989 |
+
return x
|
| 990 |
+
|
| 991 |
+
|
| 992 |
+
@auto_docstring(
|
| 993 |
+
custom_intro="""
|
| 994 |
+
MRA Model transformer with a sequence classification/regression head on top (a linear layer on top of
|
| 995 |
+
the pooled output) e.g. for GLUE tasks.
|
| 996 |
+
"""
|
| 997 |
+
)
|
| 998 |
+
class MraForSequenceClassification(MraPreTrainedModel):
|
| 999 |
+
def __init__(self, config):
|
| 1000 |
+
super().__init__(config)
|
| 1001 |
+
self.num_labels = config.num_labels
|
| 1002 |
+
self.mra = MraModel(config)
|
| 1003 |
+
self.classifier = MraClassificationHead(config)
|
| 1004 |
+
|
| 1005 |
+
# Initialize weights and apply final processing
|
| 1006 |
+
self.post_init()
|
| 1007 |
+
|
| 1008 |
+
@auto_docstring
|
| 1009 |
+
def forward(
|
| 1010 |
+
self,
|
| 1011 |
+
input_ids: torch.Tensor | None = None,
|
| 1012 |
+
attention_mask: torch.Tensor | None = None,
|
| 1013 |
+
token_type_ids: torch.Tensor | None = None,
|
| 1014 |
+
position_ids: torch.Tensor | None = None,
|
| 1015 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1016 |
+
labels: torch.Tensor | None = None,
|
| 1017 |
+
output_hidden_states: bool | None = None,
|
| 1018 |
+
return_dict: bool | None = None,
|
| 1019 |
+
**kwargs,
|
| 1020 |
+
) -> tuple | SequenceClassifierOutput:
|
| 1021 |
+
r"""
|
| 1022 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1023 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1024 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1025 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1026 |
+
"""
|
| 1027 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1028 |
+
|
| 1029 |
+
outputs = self.mra(
|
| 1030 |
+
input_ids,
|
| 1031 |
+
attention_mask=attention_mask,
|
| 1032 |
+
token_type_ids=token_type_ids,
|
| 1033 |
+
position_ids=position_ids,
|
| 1034 |
+
inputs_embeds=inputs_embeds,
|
| 1035 |
+
output_hidden_states=output_hidden_states,
|
| 1036 |
+
return_dict=return_dict,
|
| 1037 |
+
)
|
| 1038 |
+
|
| 1039 |
+
sequence_output = outputs[0]
|
| 1040 |
+
logits = self.classifier(sequence_output)
|
| 1041 |
+
|
| 1042 |
+
loss = None
|
| 1043 |
+
if labels is not None:
|
| 1044 |
+
if self.config.problem_type is None:
|
| 1045 |
+
if self.num_labels == 1:
|
| 1046 |
+
self.config.problem_type = "regression"
|
| 1047 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1048 |
+
self.config.problem_type = "single_label_classification"
|
| 1049 |
+
else:
|
| 1050 |
+
self.config.problem_type = "multi_label_classification"
|
| 1051 |
+
|
| 1052 |
+
if self.config.problem_type == "regression":
|
| 1053 |
+
loss_fct = MSELoss()
|
| 1054 |
+
if self.num_labels == 1:
|
| 1055 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 1056 |
+
else:
|
| 1057 |
+
loss = loss_fct(logits, labels)
|
| 1058 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1059 |
+
loss_fct = CrossEntropyLoss()
|
| 1060 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1061 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1062 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1063 |
+
loss = loss_fct(logits, labels)
|
| 1064 |
+
if not return_dict:
|
| 1065 |
+
output = (logits,) + outputs[1:]
|
| 1066 |
+
return ((loss,) + output) if loss is not None else output
|
| 1067 |
+
|
| 1068 |
+
return SequenceClassifierOutput(
|
| 1069 |
+
loss=loss,
|
| 1070 |
+
logits=logits,
|
| 1071 |
+
hidden_states=outputs.hidden_states,
|
| 1072 |
+
attentions=outputs.attentions,
|
| 1073 |
+
)
|
| 1074 |
+
|
| 1075 |
+
|
| 1076 |
+
@auto_docstring
|
| 1077 |
+
class MraForMultipleChoice(MraPreTrainedModel):
|
| 1078 |
+
def __init__(self, config):
|
| 1079 |
+
super().__init__(config)
|
| 1080 |
+
|
| 1081 |
+
self.mra = MraModel(config)
|
| 1082 |
+
self.pre_classifier = nn.Linear(config.hidden_size, config.hidden_size)
|
| 1083 |
+
self.classifier = nn.Linear(config.hidden_size, 1)
|
| 1084 |
+
|
| 1085 |
+
# Initialize weights and apply final processing
|
| 1086 |
+
self.post_init()
|
| 1087 |
+
|
| 1088 |
+
@auto_docstring
|
| 1089 |
+
def forward(
|
| 1090 |
+
self,
|
| 1091 |
+
input_ids: torch.Tensor | None = None,
|
| 1092 |
+
attention_mask: torch.Tensor | None = None,
|
| 1093 |
+
token_type_ids: torch.Tensor | None = None,
|
| 1094 |
+
position_ids: torch.Tensor | None = None,
|
| 1095 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1096 |
+
labels: torch.Tensor | None = None,
|
| 1097 |
+
output_hidden_states: bool | None = None,
|
| 1098 |
+
return_dict: bool | None = None,
|
| 1099 |
+
**kwargs,
|
| 1100 |
+
) -> tuple | MultipleChoiceModelOutput:
|
| 1101 |
+
r"""
|
| 1102 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
|
| 1103 |
+
Indices of input sequence tokens in the vocabulary.
|
| 1104 |
+
|
| 1105 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1106 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1107 |
+
|
| 1108 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1109 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
|
| 1110 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 1111 |
+
1]`:
|
| 1112 |
+
|
| 1113 |
+
- 0 corresponds to a *sentence A* token,
|
| 1114 |
+
- 1 corresponds to a *sentence B* token.
|
| 1115 |
+
|
| 1116 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 1117 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
|
| 1118 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 1119 |
+
config.max_position_embeddings - 1]`.
|
| 1120 |
+
|
| 1121 |
+
[What are position IDs?](../glossary#position-ids)
|
| 1122 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
|
| 1123 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 1124 |
+
is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
|
| 1125 |
+
model's internal embedding lookup matrix.
|
| 1126 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1127 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
|
| 1128 |
+
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
|
| 1129 |
+
`input_ids` above)
|
| 1130 |
+
"""
|
| 1131 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1132 |
+
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
|
| 1133 |
+
|
| 1134 |
+
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
|
| 1135 |
+
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
|
| 1136 |
+
token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
|
| 1137 |
+
position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
|
| 1138 |
+
inputs_embeds = (
|
| 1139 |
+
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
|
| 1140 |
+
if inputs_embeds is not None
|
| 1141 |
+
else None
|
| 1142 |
+
)
|
| 1143 |
+
|
| 1144 |
+
outputs = self.mra(
|
| 1145 |
+
input_ids,
|
| 1146 |
+
attention_mask=attention_mask,
|
| 1147 |
+
token_type_ids=token_type_ids,
|
| 1148 |
+
position_ids=position_ids,
|
| 1149 |
+
inputs_embeds=inputs_embeds,
|
| 1150 |
+
output_hidden_states=output_hidden_states,
|
| 1151 |
+
return_dict=return_dict,
|
| 1152 |
+
)
|
| 1153 |
+
|
| 1154 |
+
hidden_state = outputs[0] # (bs * num_choices, seq_len, dim)
|
| 1155 |
+
pooled_output = hidden_state[:, 0] # (bs * num_choices, dim)
|
| 1156 |
+
pooled_output = self.pre_classifier(pooled_output) # (bs * num_choices, dim)
|
| 1157 |
+
pooled_output = nn.ReLU()(pooled_output) # (bs * num_choices, dim)
|
| 1158 |
+
logits = self.classifier(pooled_output)
|
| 1159 |
+
|
| 1160 |
+
reshaped_logits = logits.view(-1, num_choices)
|
| 1161 |
+
|
| 1162 |
+
loss = None
|
| 1163 |
+
if labels is not None:
|
| 1164 |
+
loss_fct = CrossEntropyLoss()
|
| 1165 |
+
loss = loss_fct(reshaped_logits, labels)
|
| 1166 |
+
|
| 1167 |
+
if not return_dict:
|
| 1168 |
+
output = (reshaped_logits,) + outputs[1:]
|
| 1169 |
+
return ((loss,) + output) if loss is not None else output
|
| 1170 |
+
|
| 1171 |
+
return MultipleChoiceModelOutput(
|
| 1172 |
+
loss=loss,
|
| 1173 |
+
logits=reshaped_logits,
|
| 1174 |
+
hidden_states=outputs.hidden_states,
|
| 1175 |
+
attentions=outputs.attentions,
|
| 1176 |
+
)
|
| 1177 |
+
|
| 1178 |
+
|
| 1179 |
+
@auto_docstring
|
| 1180 |
+
class MraForTokenClassification(MraPreTrainedModel):
|
| 1181 |
+
def __init__(self, config):
|
| 1182 |
+
super().__init__(config)
|
| 1183 |
+
self.num_labels = config.num_labels
|
| 1184 |
+
|
| 1185 |
+
self.mra = MraModel(config)
|
| 1186 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 1187 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 1188 |
+
|
| 1189 |
+
# Initialize weights and apply final processing
|
| 1190 |
+
self.post_init()
|
| 1191 |
+
|
| 1192 |
+
@auto_docstring
|
| 1193 |
+
def forward(
|
| 1194 |
+
self,
|
| 1195 |
+
input_ids: torch.Tensor | None = None,
|
| 1196 |
+
attention_mask: torch.Tensor | None = None,
|
| 1197 |
+
token_type_ids: torch.Tensor | None = None,
|
| 1198 |
+
position_ids: torch.Tensor | None = None,
|
| 1199 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1200 |
+
labels: torch.Tensor | None = None,
|
| 1201 |
+
output_hidden_states: bool | None = None,
|
| 1202 |
+
return_dict: bool | None = None,
|
| 1203 |
+
**kwargs,
|
| 1204 |
+
) -> tuple | TokenClassifierOutput:
|
| 1205 |
+
r"""
|
| 1206 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1207 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 1208 |
+
"""
|
| 1209 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1210 |
+
|
| 1211 |
+
outputs = self.mra(
|
| 1212 |
+
input_ids,
|
| 1213 |
+
attention_mask=attention_mask,
|
| 1214 |
+
token_type_ids=token_type_ids,
|
| 1215 |
+
position_ids=position_ids,
|
| 1216 |
+
inputs_embeds=inputs_embeds,
|
| 1217 |
+
output_hidden_states=output_hidden_states,
|
| 1218 |
+
return_dict=return_dict,
|
| 1219 |
+
)
|
| 1220 |
+
|
| 1221 |
+
sequence_output = outputs[0]
|
| 1222 |
+
|
| 1223 |
+
sequence_output = self.dropout(sequence_output)
|
| 1224 |
+
logits = self.classifier(sequence_output)
|
| 1225 |
+
|
| 1226 |
+
loss = None
|
| 1227 |
+
if labels is not None:
|
| 1228 |
+
loss_fct = CrossEntropyLoss()
|
| 1229 |
+
# Only keep active parts of the loss
|
| 1230 |
+
if attention_mask is not None:
|
| 1231 |
+
active_loss = attention_mask.view(-1) == 1
|
| 1232 |
+
active_logits = logits.view(-1, self.num_labels)
|
| 1233 |
+
active_labels = torch.where(
|
| 1234 |
+
active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
|
| 1235 |
+
)
|
| 1236 |
+
loss = loss_fct(active_logits, active_labels)
|
| 1237 |
+
else:
|
| 1238 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1239 |
+
|
| 1240 |
+
if not return_dict:
|
| 1241 |
+
output = (logits,) + outputs[1:]
|
| 1242 |
+
return ((loss,) + output) if loss is not None else output
|
| 1243 |
+
|
| 1244 |
+
return TokenClassifierOutput(
|
| 1245 |
+
loss=loss,
|
| 1246 |
+
logits=logits,
|
| 1247 |
+
hidden_states=outputs.hidden_states,
|
| 1248 |
+
attentions=outputs.attentions,
|
| 1249 |
+
)
|
| 1250 |
+
|
| 1251 |
+
|
| 1252 |
+
@auto_docstring
|
| 1253 |
+
class MraForQuestionAnswering(MraPreTrainedModel):
|
| 1254 |
+
def __init__(self, config):
|
| 1255 |
+
super().__init__(config)
|
| 1256 |
+
|
| 1257 |
+
config.num_labels = 2
|
| 1258 |
+
self.num_labels = config.num_labels
|
| 1259 |
+
|
| 1260 |
+
self.mra = MraModel(config)
|
| 1261 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
| 1262 |
+
|
| 1263 |
+
# Initialize weights and apply final processing
|
| 1264 |
+
self.post_init()
|
| 1265 |
+
|
| 1266 |
+
@auto_docstring
|
| 1267 |
+
def forward(
|
| 1268 |
+
self,
|
| 1269 |
+
input_ids: torch.Tensor | None = None,
|
| 1270 |
+
attention_mask: torch.Tensor | None = None,
|
| 1271 |
+
token_type_ids: torch.Tensor | None = None,
|
| 1272 |
+
position_ids: torch.Tensor | None = None,
|
| 1273 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1274 |
+
start_positions: torch.Tensor | None = None,
|
| 1275 |
+
end_positions: torch.Tensor | None = None,
|
| 1276 |
+
output_hidden_states: bool | None = None,
|
| 1277 |
+
return_dict: bool | None = None,
|
| 1278 |
+
**kwargs,
|
| 1279 |
+
) -> tuple | QuestionAnsweringModelOutput:
|
| 1280 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1281 |
+
|
| 1282 |
+
outputs = self.mra(
|
| 1283 |
+
input_ids,
|
| 1284 |
+
attention_mask=attention_mask,
|
| 1285 |
+
token_type_ids=token_type_ids,
|
| 1286 |
+
position_ids=position_ids,
|
| 1287 |
+
inputs_embeds=inputs_embeds,
|
| 1288 |
+
output_hidden_states=output_hidden_states,
|
| 1289 |
+
return_dict=return_dict,
|
| 1290 |
+
)
|
| 1291 |
+
|
| 1292 |
+
sequence_output = outputs[0]
|
| 1293 |
+
|
| 1294 |
+
logits = self.qa_outputs(sequence_output)
|
| 1295 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1296 |
+
start_logits = start_logits.squeeze(-1)
|
| 1297 |
+
end_logits = end_logits.squeeze(-1)
|
| 1298 |
+
|
| 1299 |
+
total_loss = None
|
| 1300 |
+
if start_positions is not None and end_positions is not None:
|
| 1301 |
+
# If we are on multi-GPU, split add a dimension
|
| 1302 |
+
if len(start_positions.size()) > 1:
|
| 1303 |
+
start_positions = start_positions.squeeze(-1)
|
| 1304 |
+
if len(end_positions.size()) > 1:
|
| 1305 |
+
end_positions = end_positions.squeeze(-1)
|
| 1306 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1307 |
+
ignored_index = start_logits.size(1)
|
| 1308 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 1309 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 1310 |
+
|
| 1311 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 1312 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1313 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1314 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1315 |
+
|
| 1316 |
+
if not return_dict:
|
| 1317 |
+
output = (start_logits, end_logits) + outputs[1:]
|
| 1318 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 1319 |
+
|
| 1320 |
+
return QuestionAnsweringModelOutput(
|
| 1321 |
+
loss=total_loss,
|
| 1322 |
+
start_logits=start_logits,
|
| 1323 |
+
end_logits=end_logits,
|
| 1324 |
+
hidden_states=outputs.hidden_states,
|
| 1325 |
+
attentions=outputs.attentions,
|
| 1326 |
+
)
|
| 1327 |
+
|
| 1328 |
+
|
| 1329 |
+
__all__ = [
|
| 1330 |
+
"MraForMaskedLM",
|
| 1331 |
+
"MraForMultipleChoice",
|
| 1332 |
+
"MraForQuestionAnswering",
|
| 1333 |
+
"MraForSequenceClassification",
|
| 1334 |
+
"MraForTokenClassification",
|
| 1335 |
+
"MraLayer",
|
| 1336 |
+
"MraModel",
|
| 1337 |
+
"MraPreTrainedModel",
|
| 1338 |
+
]
|
lib/python3.11/site-packages/transformers/models/mt5/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_mt5 import *
|
| 22 |
+
from .modeling_mt5 import *
|
| 23 |
+
from .tokenization_mt5 import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.11/site-packages/transformers/models/mt5/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (807 Bytes). View file
|
|
|