Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- janus/lib/python3.10/site-packages/transformers/models/aria/__init__.py +30 -0
- janus/lib/python3.10/site-packages/transformers/models/aria/__pycache__/modeling_aria.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/aria/image_processing_aria.py +504 -0
- janus/lib/python3.10/site-packages/transformers/models/aria/processing_aria.py +164 -0
- janus/lib/python3.10/site-packages/transformers/models/bert_generation/__pycache__/tokenization_bert_generation.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/bert_generation/configuration_bert_generation.py +127 -0
- janus/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_blenderbot_small.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_flax_blenderbot_small.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/blip_2/__pycache__/processing_blip_2.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/blip_2/modeling_blip_2.py +0 -0
- janus/lib/python3.10/site-packages/transformers/models/byt5/__pycache__/__init__.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/byt5/__pycache__/tokenization_byt5.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/byt5/tokenization_byt5.py +236 -0
- janus/lib/python3.10/site-packages/transformers/models/chinese_clip/__init__.py +30 -0
- janus/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/__init__.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/configuration_chinese_clip.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/feature_extraction_chinese_clip.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/image_processing_chinese_clip.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/modeling_chinese_clip.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/chinese_clip/configuration_chinese_clip.py +434 -0
- janus/lib/python3.10/site-packages/transformers/models/chinese_clip/feature_extraction_chinese_clip.py +36 -0
- janus/lib/python3.10/site-packages/transformers/models/chinese_clip/image_processing_chinese_clip.py +310 -0
- janus/lib/python3.10/site-packages/transformers/models/chinese_clip/modeling_chinese_clip.py +1630 -0
- janus/lib/python3.10/site-packages/transformers/models/chinese_clip/processing_chinese_clip.py +163 -0
- janus/lib/python3.10/site-packages/transformers/models/cvt/__pycache__/modeling_tf_cvt.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/diffllama/__init__.py +27 -0
- janus/lib/python3.10/site-packages/transformers/models/diffllama/__pycache__/configuration_diffllama.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/diffllama/__pycache__/modular_diffllama.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/diffllama/modeling_diffllama.py +1420 -0
- janus/lib/python3.10/site-packages/transformers/models/diffllama/modular_diffllama.py +464 -0
- janus/lib/python3.10/site-packages/transformers/models/granite/__pycache__/configuration_granite.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/granite/__pycache__/modeling_granite.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/granite/__pycache__/modular_granite.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/maskformer/__pycache__/__init__.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/maskformer/__pycache__/configuration_maskformer.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/maskformer/__pycache__/configuration_maskformer_swin.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/maskformer/__pycache__/feature_extraction_maskformer.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/pegasus_x/__pycache__/__init__.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/pegasus_x/__pycache__/configuration_pegasus_x.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/pegasus_x/__pycache__/modeling_pegasus_x.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/pegasus_x/configuration_pegasus_x.py +177 -0
- janus/lib/python3.10/site-packages/transformers/models/pegasus_x/modeling_pegasus_x.py +1621 -0
- janus/lib/python3.10/site-packages/transformers/models/phi3/__init__.py +27 -0
- janus/lib/python3.10/site-packages/transformers/models/phi3/__pycache__/__init__.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/phi3/__pycache__/configuration_phi3.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/phi3/__pycache__/modeling_phi3.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/phi3/__pycache__/modular_phi3.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/transformers/models/phi3/configuration_phi3.py +224 -0
- janus/lib/python3.10/site-packages/transformers/models/phi3/modeling_phi3.py +1171 -0
- janus/lib/python3.10/site-packages/transformers/models/phi3/modular_phi3.py +320 -0
janus/lib/python3.10/site-packages/transformers/models/aria/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_aria import *
|
| 22 |
+
from .image_processing_aria import *
|
| 23 |
+
from .modeling_aria import *
|
| 24 |
+
from .processing_aria import *
|
| 25 |
+
|
| 26 |
+
else:
|
| 27 |
+
import sys
|
| 28 |
+
|
| 29 |
+
_file = globals()["__file__"]
|
| 30 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
janus/lib/python3.10/site-packages/transformers/models/aria/__pycache__/modeling_aria.cpython-310.pyc
ADDED
|
Binary file (54.6 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/aria/image_processing_aria.py
ADDED
|
@@ -0,0 +1,504 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/aria/modular_aria.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_aria.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2024 The Rhymes-AI Teams Authors and The HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
import math
|
| 22 |
+
from typing import Iterable, List, Optional, Tuple, Union
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
|
| 26 |
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature, select_best_resolution
|
| 27 |
+
from ...image_transforms import PaddingMode, convert_to_rgb, pad, resize, to_channel_dimension_format
|
| 28 |
+
from ...image_utils import (
|
| 29 |
+
ChannelDimension,
|
| 30 |
+
ImageInput,
|
| 31 |
+
PILImageResampling,
|
| 32 |
+
get_image_size,
|
| 33 |
+
infer_channel_dimension_format,
|
| 34 |
+
is_valid_image,
|
| 35 |
+
to_numpy_array,
|
| 36 |
+
valid_images,
|
| 37 |
+
validate_preprocess_arguments,
|
| 38 |
+
)
|
| 39 |
+
from ...utils import TensorType
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def make_batched_images(images) -> List[List[ImageInput]]:
|
| 43 |
+
"""
|
| 44 |
+
Accepts images in list or nested list format, and makes a list of images for preprocessing.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
images (`Union[List[List[ImageInput]], List[ImageInput], ImageInput]`):
|
| 48 |
+
The input image.
|
| 49 |
+
|
| 50 |
+
Returns:
|
| 51 |
+
list: A list of images.
|
| 52 |
+
"""
|
| 53 |
+
if isinstance(images, (list, tuple)) and isinstance(images[0], (list, tuple)) and is_valid_image(images[0][0]):
|
| 54 |
+
return [img for img_list in images for img in img_list]
|
| 55 |
+
|
| 56 |
+
elif isinstance(images, (list, tuple)) and is_valid_image(images[0]):
|
| 57 |
+
return images
|
| 58 |
+
|
| 59 |
+
elif is_valid_image(images):
|
| 60 |
+
return [images]
|
| 61 |
+
|
| 62 |
+
raise ValueError(f"Could not make batched video from {images}")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def divide_to_patches(image: np.array, patch_size: int, input_data_format) -> List[np.array]:
|
| 66 |
+
"""
|
| 67 |
+
Divides an image into patches of a specified size.
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
image (`np.array`):
|
| 71 |
+
The input image.
|
| 72 |
+
patch_size (`int`):
|
| 73 |
+
The size of each patch.
|
| 74 |
+
input_data_format (`ChannelDimension` or `str`):
|
| 75 |
+
The channel dimension format of the input image.
|
| 76 |
+
|
| 77 |
+
Returns:
|
| 78 |
+
list: A list of np.array representing the patches.
|
| 79 |
+
"""
|
| 80 |
+
patches = []
|
| 81 |
+
height, width = get_image_size(image, channel_dim=input_data_format)
|
| 82 |
+
for i in range(0, height, patch_size):
|
| 83 |
+
for j in range(0, width, patch_size):
|
| 84 |
+
if input_data_format == ChannelDimension.LAST:
|
| 85 |
+
patch = image[i : i + patch_size, j : j + patch_size]
|
| 86 |
+
else:
|
| 87 |
+
patch = image[:, i : i + patch_size, j : j + patch_size]
|
| 88 |
+
patches.append(patch)
|
| 89 |
+
|
| 90 |
+
return patches
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _get_patch_output_size(image, target_resolution, input_data_format):
|
| 94 |
+
original_height, original_width = get_image_size(image, channel_dim=input_data_format)
|
| 95 |
+
target_height, target_width = target_resolution
|
| 96 |
+
|
| 97 |
+
scale_w = target_width / original_width
|
| 98 |
+
scale_h = target_height / original_height
|
| 99 |
+
|
| 100 |
+
if scale_w < scale_h:
|
| 101 |
+
new_width = target_width
|
| 102 |
+
new_height = min(math.ceil(original_height * scale_w), target_height)
|
| 103 |
+
else:
|
| 104 |
+
new_height = target_height
|
| 105 |
+
new_width = min(math.ceil(original_width * scale_h), target_width)
|
| 106 |
+
|
| 107 |
+
return new_height, new_width
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class AriaImageProcessor(BaseImageProcessor):
|
| 111 |
+
"""
|
| 112 |
+
A vision processor for the Aria model that handles image preprocessing.
|
| 113 |
+
Initialize the AriaImageProcessor.
|
| 114 |
+
|
| 115 |
+
Args:
|
| 116 |
+
image_mean (`list`, *optional*, defaults to [0.5, 0.5, 0.5]):
|
| 117 |
+
Mean values for normalization.
|
| 118 |
+
image_std (`list`, *optional*, defaults to [0.5, 0.5, 0.5]):
|
| 119 |
+
Standard deviation values for normalization.
|
| 120 |
+
max_image_size (`int`, *optional*, defaults to 980):
|
| 121 |
+
Maximum image size.
|
| 122 |
+
min_image_size (`int`, *optional*, defaults to 336):
|
| 123 |
+
Minimum image size.
|
| 124 |
+
split_resolutions (`list`, *optional*, defaults to a list of optimal,resolutions as tuples):
|
| 125 |
+
The optimal resolutions for splitting the image.
|
| 126 |
+
split_image (`bool`, *optional*, defaults to `False`):
|
| 127 |
+
Whether to split the image.
|
| 128 |
+
do_convert_rgb (`bool`, *optional*, defaults to `True`):
|
| 129 |
+
Whether to convert the image to RGB.
|
| 130 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 131 |
+
Whether to normalize the image.
|
| 132 |
+
resample (PILImageResampling, *optional*, defaults to `BICUBIC`):
|
| 133 |
+
The resampling filter to use if resizing the image.
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
def __init__(
|
| 137 |
+
self,
|
| 138 |
+
image_mean: List[float] = None,
|
| 139 |
+
image_std: List[float] = None,
|
| 140 |
+
max_image_size: int = 980,
|
| 141 |
+
min_image_size: int = 336,
|
| 142 |
+
split_resolutions: Optional[List[Tuple[int, int]]] = None,
|
| 143 |
+
split_image: Optional[bool] = False,
|
| 144 |
+
do_convert_rgb: Optional[bool] = True,
|
| 145 |
+
do_normalize: Optional[bool] = True,
|
| 146 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 147 |
+
**kwargs,
|
| 148 |
+
):
|
| 149 |
+
super().__init__(**kwargs)
|
| 150 |
+
|
| 151 |
+
if image_mean is None:
|
| 152 |
+
image_mean = [0.5, 0.5, 0.5]
|
| 153 |
+
if image_std is None:
|
| 154 |
+
image_std = [0.5, 0.5, 0.5]
|
| 155 |
+
self.max_image_size = max_image_size
|
| 156 |
+
self.min_image_size = min_image_size
|
| 157 |
+
self.image_mean = image_mean
|
| 158 |
+
self.image_std = image_std
|
| 159 |
+
self.split_image = split_image
|
| 160 |
+
if split_resolutions is None:
|
| 161 |
+
split_resolutions = [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (2, 4), (2, 3), (2, 2), (2, 1), (3, 1), (3, 2), (4, 1), (4, 2), (5, 1), (6, 1), (7, 1), (8, 1)] # fmt: skip
|
| 162 |
+
split_resolutions = [(el[0] * 490, el[1] * 490) for el in split_resolutions]
|
| 163 |
+
self.split_resolutions = split_resolutions
|
| 164 |
+
self.do_convert_rgb = do_convert_rgb
|
| 165 |
+
self.do_normalize = do_normalize
|
| 166 |
+
self.resample = resample
|
| 167 |
+
|
| 168 |
+
def preprocess(
|
| 169 |
+
self,
|
| 170 |
+
images: Union[ImageInput, List[ImageInput]],
|
| 171 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 172 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 173 |
+
max_image_size: Optional[int] = None,
|
| 174 |
+
min_image_size: Optional[int] = None,
|
| 175 |
+
split_image: Optional[bool] = None,
|
| 176 |
+
do_convert_rgb: Optional[bool] = None,
|
| 177 |
+
do_normalize: Optional[bool] = None,
|
| 178 |
+
resample: PILImageResampling = None,
|
| 179 |
+
return_tensors: Optional[Union[str, TensorType]] = "pt",
|
| 180 |
+
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
|
| 181 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 182 |
+
):
|
| 183 |
+
"""
|
| 184 |
+
Process a list of images.
|
| 185 |
+
|
| 186 |
+
Args:
|
| 187 |
+
images (ImageInput or list of ImageInput):
|
| 188 |
+
The input image or a list of images.
|
| 189 |
+
image_mean (`list`, *optional*, defaults to [0.5, 0.5, 0.5]):
|
| 190 |
+
Mean values for normalization.
|
| 191 |
+
image_std (`list`, *optional*, defaults to [0.5, 0.5, 0.5]):
|
| 192 |
+
Standard deviation values for normalization.
|
| 193 |
+
max_image_size (`int`, *optional*, defaults to `self.max_image_size` (980)):
|
| 194 |
+
Maximum image size.
|
| 195 |
+
min_image_size (`int`, *optional*, defaults to `self.min_image_size` (336)):
|
| 196 |
+
Minimum image size.
|
| 197 |
+
split_image (`bool`, *optional*, defaults to `self.split_image` (False)):
|
| 198 |
+
Whether to split the image.
|
| 199 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb` (True)):
|
| 200 |
+
Whether to convert the image to RGB.
|
| 201 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize` (True)):
|
| 202 |
+
Whether to normalize the image.
|
| 203 |
+
resample (PILImageResampling, *optional*, defaults to `self.resample` (BICUBIC)):
|
| 204 |
+
The resampling filter to use if resizing the image.
|
| 205 |
+
return_tensors (`str` or `TensorType`, *optional*, defaults to "pt"):
|
| 206 |
+
The type of tensor to return.
|
| 207 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 208 |
+
The channel dimension format for the output image. Can be one of:
|
| 209 |
+
- `"channels_first"` or `ChannelDimension.FIRST`:
|
| 210 |
+
image in (num_channels, height, width) format.
|
| 211 |
+
- `"channels_last"` or `ChannelDimension.LAST`:
|
| 212 |
+
image in (height, width, num_channels) format.
|
| 213 |
+
If unset, will use same as the input image.
|
| 214 |
+
input_data_format (`str` or `ChannelDimension`, *optional*):
|
| 215 |
+
The channel dimension format for the input image. Can be one of:
|
| 216 |
+
- `"channels_first"` or `ChannelDimension.FIRST`:
|
| 217 |
+
image in (num_channels, height, width) format.
|
| 218 |
+
- `"channels_last"` or `ChannelDimension.LAST`:
|
| 219 |
+
image in (height, width, num_channels) format.
|
| 220 |
+
If unset, will use the inferred format of the input image.
|
| 221 |
+
|
| 222 |
+
Returns:
|
| 223 |
+
BatchFeature:
|
| 224 |
+
A BatchFeature object containing:
|
| 225 |
+
- 'pixel_values':
|
| 226 |
+
Tensor of processed image pixel values.
|
| 227 |
+
- 'pixel_mask':
|
| 228 |
+
Boolean pixel mask. This mask is a 2D tensor of shape (max_image_size, max_image_size) where:
|
| 229 |
+
- True (1) values indicate pixels that belong to the original resized image.
|
| 230 |
+
- False (0) values indicate pixels that are part of the padding.
|
| 231 |
+
The mask helps distinguish between actual image content and padded areas in subsequent processing steps.
|
| 232 |
+
- 'num_crops':
|
| 233 |
+
The maximum number of crops across all images.
|
| 234 |
+
"""
|
| 235 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 236 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 237 |
+
max_image_size = max_image_size if max_image_size is not None else self.max_image_size
|
| 238 |
+
min_image_size = min_image_size if min_image_size is not None else self.min_image_size
|
| 239 |
+
split_image = split_image if split_image is not None else self.split_image
|
| 240 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
| 241 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 242 |
+
resample = resample if resample is not None else self.resample
|
| 243 |
+
|
| 244 |
+
if max_image_size not in [490, 980]:
|
| 245 |
+
raise ValueError("max_image_size must be either 490 or 980")
|
| 246 |
+
|
| 247 |
+
images = make_batched_images(images)
|
| 248 |
+
|
| 249 |
+
if not valid_images(images):
|
| 250 |
+
raise ValueError(
|
| 251 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 252 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
validate_preprocess_arguments(
|
| 256 |
+
do_normalize=do_normalize,
|
| 257 |
+
image_mean=image_mean,
|
| 258 |
+
image_std=image_std,
|
| 259 |
+
resample=resample,
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
if do_convert_rgb:
|
| 263 |
+
images = [convert_to_rgb(image) for image in images]
|
| 264 |
+
|
| 265 |
+
# All transformations expect numpy arrays.
|
| 266 |
+
images = [to_numpy_array(image) for image in images]
|
| 267 |
+
|
| 268 |
+
if input_data_format is None:
|
| 269 |
+
# We assume that all images have the same channel dimension format.
|
| 270 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 271 |
+
|
| 272 |
+
pixel_values = []
|
| 273 |
+
pixel_masks = []
|
| 274 |
+
num_crops = None
|
| 275 |
+
|
| 276 |
+
for image in images:
|
| 277 |
+
if split_image:
|
| 278 |
+
crop_images = self.get_image_patches(
|
| 279 |
+
image,
|
| 280 |
+
self.split_resolutions,
|
| 281 |
+
max_image_size,
|
| 282 |
+
resample,
|
| 283 |
+
data_format=input_data_format,
|
| 284 |
+
input_data_format=input_data_format,
|
| 285 |
+
)
|
| 286 |
+
else:
|
| 287 |
+
crop_images = [image]
|
| 288 |
+
if num_crops is None or len(crop_images) > num_crops:
|
| 289 |
+
num_crops = len(crop_images)
|
| 290 |
+
|
| 291 |
+
for crop_image in crop_images:
|
| 292 |
+
# At this point the scale is the rescaling factor that would bring the image to max_size in its larger dimension
|
| 293 |
+
h, w = get_image_size(crop_image)
|
| 294 |
+
scale = max_image_size / max(h, w)
|
| 295 |
+
if w >= h:
|
| 296 |
+
new_size = (max(int(h * scale), min_image_size), max_image_size) # h, w
|
| 297 |
+
else:
|
| 298 |
+
new_size = (max_image_size, max(int(w * scale), min_image_size)) # h, w
|
| 299 |
+
|
| 300 |
+
crop_image_resized = resize(
|
| 301 |
+
crop_image,
|
| 302 |
+
new_size,
|
| 303 |
+
resample=resample,
|
| 304 |
+
data_format=input_data_format,
|
| 305 |
+
input_data_format=input_data_format,
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
padding_bottom, padding_right = max_image_size - new_size[0], max_image_size - new_size[1]
|
| 309 |
+
crop_image_padded = pad(
|
| 310 |
+
crop_image_resized,
|
| 311 |
+
((0, padding_bottom), (0, padding_right)),
|
| 312 |
+
data_format=input_data_format,
|
| 313 |
+
input_data_format=input_data_format,
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
# Create a pixel mask
|
| 317 |
+
pixel_mask = np.zeros((max_image_size, max_image_size), dtype=bool)
|
| 318 |
+
pixel_mask[: new_size[0], : new_size[1]] = 1
|
| 319 |
+
pixel_masks.append(pixel_mask)
|
| 320 |
+
|
| 321 |
+
if do_normalize:
|
| 322 |
+
crop_image_padded = self.normalize(
|
| 323 |
+
crop_image_padded / 255.0,
|
| 324 |
+
self.image_mean,
|
| 325 |
+
self.image_std,
|
| 326 |
+
data_format=input_data_format,
|
| 327 |
+
input_data_format=input_data_format,
|
| 328 |
+
)
|
| 329 |
+
crop_image_padded = (
|
| 330 |
+
to_channel_dimension_format(crop_image_padded, data_format, input_data_format)
|
| 331 |
+
if data_format is not None
|
| 332 |
+
else crop_image_padded
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
pixel_values.append(crop_image_padded)
|
| 336 |
+
return BatchFeature(
|
| 337 |
+
data={
|
| 338 |
+
"pixel_values": np.stack(pixel_values, axis=0),
|
| 339 |
+
"pixel_mask": np.stack(pixel_masks, axis=0),
|
| 340 |
+
"num_crops": num_crops,
|
| 341 |
+
},
|
| 342 |
+
tensor_type=return_tensors,
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
def _resize_for_patching(
|
| 346 |
+
self, image: np.array, target_resolution: tuple, resample, input_data_format: ChannelDimension
|
| 347 |
+
) -> np.array:
|
| 348 |
+
"""
|
| 349 |
+
Resizes an image to a target resolution while maintaining aspect ratio.
|
| 350 |
+
|
| 351 |
+
Args:
|
| 352 |
+
image (np.array):
|
| 353 |
+
The input image.
|
| 354 |
+
target_resolution (tuple):
|
| 355 |
+
The target resolution (height, width) of the image.
|
| 356 |
+
resample (`PILImageResampling`):
|
| 357 |
+
Resampling filter to use if resizing the image.
|
| 358 |
+
input_data_format (`ChannelDimension` or `str`):
|
| 359 |
+
The channel dimension format of the input image.
|
| 360 |
+
|
| 361 |
+
Returns:
|
| 362 |
+
np.array: The resized and padded image.
|
| 363 |
+
"""
|
| 364 |
+
new_height, new_width = _get_patch_output_size(image, target_resolution, input_data_format)
|
| 365 |
+
|
| 366 |
+
# Resize the image
|
| 367 |
+
resized_image = resize(image, (new_height, new_width), resample=resample, input_data_format=input_data_format)
|
| 368 |
+
|
| 369 |
+
return resized_image
|
| 370 |
+
|
| 371 |
+
def _pad_for_patching(
|
| 372 |
+
self, image: np.array, target_resolution: tuple, input_data_format: ChannelDimension
|
| 373 |
+
) -> np.array:
|
| 374 |
+
"""
|
| 375 |
+
Pad an image to a target resolution while maintaining aspect ratio.
|
| 376 |
+
"""
|
| 377 |
+
target_height, target_width = target_resolution
|
| 378 |
+
new_height, new_width = _get_patch_output_size(image, target_resolution, input_data_format)
|
| 379 |
+
|
| 380 |
+
paste_x = (target_width - new_width) // 2
|
| 381 |
+
paste_y = (target_height - new_height) // 2
|
| 382 |
+
|
| 383 |
+
padded_image = self.pad(image, padding=((paste_y, paste_y), (paste_x, paste_x)))
|
| 384 |
+
|
| 385 |
+
return padded_image
|
| 386 |
+
|
| 387 |
+
def pad(
|
| 388 |
+
self,
|
| 389 |
+
image: np.ndarray,
|
| 390 |
+
padding: Union[int, Tuple[int, int], Iterable[Tuple[int, int]]],
|
| 391 |
+
mode: PaddingMode = PaddingMode.CONSTANT,
|
| 392 |
+
constant_values: Union[float, Iterable[float]] = 0.0,
|
| 393 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 394 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 395 |
+
) -> np.ndarray:
|
| 396 |
+
"""
|
| 397 |
+
Pads the `image` with the specified `padding` and `mode`. Padding can be in the (`height`, `width`)
|
| 398 |
+
dimension of in the (`num_patches`) dimension. In the second case an iterable if tuples is expected
|
| 399 |
+
as input.
|
| 400 |
+
|
| 401 |
+
Args:
|
| 402 |
+
image (`np.ndarray`):
|
| 403 |
+
The image to pad.
|
| 404 |
+
padding (`int` or `Tuple[int, int]` or `Iterable[Tuple[int, int]]`):
|
| 405 |
+
Padding to apply to the edges of the height, width axes. Can be one of three formats:
|
| 406 |
+
- `((before_height, after_height), (before_width, after_width))` unique pad widths for each axis.
|
| 407 |
+
- `((before, after),)` yields same before and after pad for height and width.
|
| 408 |
+
- `(pad,)` or int is a shortcut for before = after = pad width for all axes.
|
| 409 |
+
mode (`PaddingMode`):
|
| 410 |
+
The padding mode to use. Can be one of:
|
| 411 |
+
- `"constant"`: pads with a constant value.
|
| 412 |
+
- `"reflect"`: pads with the reflection of the vector mirrored on the first and last values of the
|
| 413 |
+
vector along each axis.
|
| 414 |
+
- `"replicate"`: pads with the replication of the last value on the edge of the array along each axis.
|
| 415 |
+
- `"symmetric"`: pads with the reflection of the vector mirrored along the edge of the array.
|
| 416 |
+
constant_values (`float` or `Iterable[float]`, *optional*):
|
| 417 |
+
The value to use for the padding if `mode` is `"constant"`.
|
| 418 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 419 |
+
The channel dimension format for the output image. Can be one of:
|
| 420 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 421 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 422 |
+
If unset, will use same as the input image.
|
| 423 |
+
input_data_format (`str` or `ChannelDimension`, *optional*):
|
| 424 |
+
The channel dimension format for the input image. Can be one of:
|
| 425 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 426 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 427 |
+
If unset, will use the inferred format of the input image.
|
| 428 |
+
|
| 429 |
+
Returns:
|
| 430 |
+
`np.ndarray`: The padded image.
|
| 431 |
+
|
| 432 |
+
"""
|
| 433 |
+
|
| 434 |
+
# call the general `pad` if padding on `height/width`, otherwise it's the `num_patched` dim
|
| 435 |
+
if isinstance(padding, int) or len(padding) != 4:
|
| 436 |
+
return pad(image, padding, mode, constant_values, data_format, input_data_format)
|
| 437 |
+
|
| 438 |
+
if input_data_format is None:
|
| 439 |
+
input_data_format = infer_channel_dimension_format(image)
|
| 440 |
+
|
| 441 |
+
padding_mode_mapping = {
|
| 442 |
+
PaddingMode.CONSTANT: "constant",
|
| 443 |
+
PaddingMode.REFLECT: "reflect",
|
| 444 |
+
PaddingMode.REPLICATE: "edge",
|
| 445 |
+
PaddingMode.SYMMETRIC: "symmetric",
|
| 446 |
+
}
|
| 447 |
+
image = np.pad(image, padding, mode=padding_mode_mapping[mode], constant_values=constant_values)
|
| 448 |
+
image = (
|
| 449 |
+
to_channel_dimension_format(image, data_format, input_data_format) if data_format is not None else image
|
| 450 |
+
)
|
| 451 |
+
return image
|
| 452 |
+
|
| 453 |
+
def get_image_patches(
|
| 454 |
+
self,
|
| 455 |
+
image: np.array,
|
| 456 |
+
grid_pinpoints: List[Tuple[int, int]],
|
| 457 |
+
patch_size: int,
|
| 458 |
+
resample: PILImageResampling,
|
| 459 |
+
data_format: ChannelDimension,
|
| 460 |
+
input_data_format: ChannelDimension,
|
| 461 |
+
) -> List[np.array]:
|
| 462 |
+
"""
|
| 463 |
+
Process an image with variable resolutions by dividing it into patches.
|
| 464 |
+
|
| 465 |
+
Args:
|
| 466 |
+
image (`np.array`):
|
| 467 |
+
The input image to be processed.
|
| 468 |
+
grid_pinpoints (List[Tuple[int, int]]):
|
| 469 |
+
A list of possible resolutions as tuples.
|
| 470 |
+
patch_size (`int`):
|
| 471 |
+
Size of the patches to divide the image into.
|
| 472 |
+
resample (`PILImageResampling`):
|
| 473 |
+
Resampling filter to use if resizing the image.
|
| 474 |
+
data_format (`ChannelDimension` or `str`):
|
| 475 |
+
The channel dimension format for the output image.
|
| 476 |
+
input_data_format (`ChannelDimension` or `str`):
|
| 477 |
+
The channel dimension format of the input image.
|
| 478 |
+
|
| 479 |
+
Returns:
|
| 480 |
+
`List[np.array]`: A list of NumPy arrays containing the processed image patches.
|
| 481 |
+
"""
|
| 482 |
+
if not isinstance(grid_pinpoints, list):
|
| 483 |
+
raise TypeError("grid_pinpoints must be a list of possible resolutions.")
|
| 484 |
+
|
| 485 |
+
possible_resolutions = grid_pinpoints
|
| 486 |
+
|
| 487 |
+
image_size = get_image_size(image, channel_dim=input_data_format)
|
| 488 |
+
best_resolution = select_best_resolution(image_size, possible_resolutions)
|
| 489 |
+
resized_image = self._resize_for_patching(
|
| 490 |
+
image, best_resolution, resample=resample, input_data_format=input_data_format
|
| 491 |
+
)
|
| 492 |
+
padded_image = self._pad_for_patching(resized_image, best_resolution, input_data_format=input_data_format)
|
| 493 |
+
|
| 494 |
+
patches = divide_to_patches(padded_image, patch_size=patch_size, input_data_format=input_data_format)
|
| 495 |
+
|
| 496 |
+
# make sure that all patches are in the input data format
|
| 497 |
+
patches = [
|
| 498 |
+
to_channel_dimension_format(patch, channel_dim=data_format, input_channel_dim=input_data_format)
|
| 499 |
+
for patch in patches
|
| 500 |
+
]
|
| 501 |
+
return patches
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
__all__ = ["AriaImageProcessor"]
|
janus/lib/python3.10/site-packages/transformers/models/aria/processing_aria.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/aria/modular_aria.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_aria.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2024 The Rhymes-AI Teams Authors and The HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
from typing import Dict, List, Optional, Union
|
| 22 |
+
|
| 23 |
+
from ...image_processing_utils import BatchFeature
|
| 24 |
+
from ...image_utils import ImageInput
|
| 25 |
+
from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
|
| 26 |
+
from ...tokenization_utils import PreTokenizedInput, TextInput
|
| 27 |
+
from ...utils import TensorType
|
| 28 |
+
from ..auto import AutoTokenizer
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class AriaProcessorKwargs(ProcessingKwargs, total=False):
|
| 32 |
+
_defaults = {
|
| 33 |
+
"text_kwargs": {
|
| 34 |
+
"padding": False,
|
| 35 |
+
},
|
| 36 |
+
"images_kwargs": {
|
| 37 |
+
"max_image_size": 980,
|
| 38 |
+
"split_image": False,
|
| 39 |
+
},
|
| 40 |
+
"return_tensors": TensorType.PYTORCH,
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class AriaProcessor(ProcessorMixin):
|
| 45 |
+
"""
|
| 46 |
+
AriaProcessor is a processor for the Aria model which wraps the Aria image preprocessor and the LLama slow tokenizer.
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
image_processor (`AriaImageProcessor`, *optional*):
|
| 50 |
+
The AriaImageProcessor to use for image preprocessing.
|
| 51 |
+
tokenizer (`PreTrainedTokenizerBase`, *optional*):
|
| 52 |
+
An instance of [`PreTrainedTokenizerBase`]. This should correspond with the model's text model. The tokenizer is a required input.
|
| 53 |
+
chat_template (`str`, *optional*):
|
| 54 |
+
A Jinja template which will be used to convert lists of messages in a chat into a tokenizable string.
|
| 55 |
+
size_conversion (`Dict`, *optional*):
|
| 56 |
+
A dictionary indicating size conversions for images.
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
attributes = ["image_processor", "tokenizer"]
|
| 60 |
+
valid_kwargs = ["chat_template", "size_conversion"]
|
| 61 |
+
image_processor_class = "AriaImageProcessor"
|
| 62 |
+
tokenizer_class = "AutoTokenizer"
|
| 63 |
+
|
| 64 |
+
def __init__(
|
| 65 |
+
self,
|
| 66 |
+
image_processor=None,
|
| 67 |
+
tokenizer: Union[AutoTokenizer, str] = None,
|
| 68 |
+
chat_template: Optional[str] = None,
|
| 69 |
+
size_conversion: Optional[Dict[Union[float, int], int]] = None,
|
| 70 |
+
):
|
| 71 |
+
if size_conversion is None:
|
| 72 |
+
size_conversion = {490: 128, 980: 256}
|
| 73 |
+
self.size_conversion = {int(k): v for k, v in size_conversion.items()}
|
| 74 |
+
|
| 75 |
+
if tokenizer is not None and tokenizer.pad_token is None:
|
| 76 |
+
tokenizer.pad_token = tokenizer.unk_token
|
| 77 |
+
|
| 78 |
+
super().__init__(image_processor, tokenizer, chat_template=chat_template)
|
| 79 |
+
|
| 80 |
+
def __call__(
|
| 81 |
+
self,
|
| 82 |
+
text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],
|
| 83 |
+
images: Optional[ImageInput] = None,
|
| 84 |
+
audio=None,
|
| 85 |
+
videos=None,
|
| 86 |
+
**kwargs: Unpack[AriaProcessorKwargs],
|
| 87 |
+
) -> BatchFeature:
|
| 88 |
+
"""
|
| 89 |
+
Main method to prepare for the model one or several sequences(s) and image(s).
|
| 90 |
+
|
| 91 |
+
Args:
|
| 92 |
+
text (`TextInput`, `PreTokenizedInput`, `List[TextInput]`, `List[PreTokenizedInput]`):
|
| 93 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 94 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 95 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 96 |
+
images (`ImageInput`):
|
| 97 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 98 |
+
tensor. Both channels-first and channels-last formats are supported.
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
Returns:
|
| 102 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 103 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
| 104 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 105 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 106 |
+
`None`).
|
| 107 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 108 |
+
- **pixel_mask** -- Pixel mask to be fed to a model. Returned when `images` is not `None`.
|
| 109 |
+
"""
|
| 110 |
+
output_kwargs = self._merge_kwargs(
|
| 111 |
+
AriaProcessorKwargs,
|
| 112 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 113 |
+
**kwargs,
|
| 114 |
+
)
|
| 115 |
+
if isinstance(text, str):
|
| 116 |
+
text = [text]
|
| 117 |
+
elif not isinstance(text, list) and not isinstance(text[0], str):
|
| 118 |
+
raise ValueError("Invalid input text. Please provide a string, or a list of strings")
|
| 119 |
+
if images is not None:
|
| 120 |
+
image_inputs = self.image_processor(
|
| 121 |
+
images,
|
| 122 |
+
**output_kwargs["images_kwargs"],
|
| 123 |
+
)
|
| 124 |
+
# expand the image_token according to the num_crops and tokens per image
|
| 125 |
+
tokens_per_image = self.size_conversion[image_inputs.pixel_values.shape[2]]
|
| 126 |
+
prompt_strings = []
|
| 127 |
+
num_crops = image_inputs.pop("num_crops") * tokens_per_image
|
| 128 |
+
for sample in text:
|
| 129 |
+
sample = sample.replace(self.tokenizer.image_token, self.tokenizer.image_token * num_crops)
|
| 130 |
+
prompt_strings.append(sample)
|
| 131 |
+
|
| 132 |
+
else:
|
| 133 |
+
image_inputs = {}
|
| 134 |
+
prompt_strings = text
|
| 135 |
+
|
| 136 |
+
text_inputs = self.tokenizer(
|
| 137 |
+
prompt_strings,
|
| 138 |
+
**output_kwargs["text_kwargs"],
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
return BatchFeature(data={**text_inputs, **image_inputs})
|
| 142 |
+
|
| 143 |
+
def batch_decode(self, *args, **kwargs):
|
| 144 |
+
"""
|
| 145 |
+
This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
|
| 146 |
+
refer to the docstring of this method for more information.
|
| 147 |
+
"""
|
| 148 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
| 149 |
+
|
| 150 |
+
def decode(self, *args, **kwargs):
|
| 151 |
+
"""
|
| 152 |
+
This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
|
| 153 |
+
the docstring of this method for more information.
|
| 154 |
+
"""
|
| 155 |
+
return self.tokenizer.decode(*args, **kwargs)
|
| 156 |
+
|
| 157 |
+
@property
|
| 158 |
+
def model_input_names(self):
|
| 159 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
| 160 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 161 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
__all__ = ["AriaProcessor"]
|
janus/lib/python3.10/site-packages/transformers/models/bert_generation/__pycache__/tokenization_bert_generation.cpython-310.pyc
ADDED
|
Binary file (6.89 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/bert_generation/configuration_bert_generation.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""BertGeneration model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class BertGenerationConfig(PretrainedConfig):
|
| 21 |
+
r"""
|
| 22 |
+
This is the configuration class to store the configuration of a [`BertGenerationPreTrainedModel`]. It is used to
|
| 23 |
+
instantiate a BertGeneration model according to the specified arguments, defining the model architecture.
|
| 24 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the BertGeneration
|
| 25 |
+
[google/bert_for_seq_generation_L-24_bbc_encoder](https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder)
|
| 26 |
+
architecture.
|
| 27 |
+
|
| 28 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 29 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
vocab_size (`int`, *optional*, defaults to 50358):
|
| 33 |
+
Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
|
| 34 |
+
`inputs_ids` passed when calling [`BertGeneration`].
|
| 35 |
+
hidden_size (`int`, *optional*, defaults to 1024):
|
| 36 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 37 |
+
num_hidden_layers (`int`, *optional*, defaults to 24):
|
| 38 |
+
Number of hidden layers in the Transformer encoder.
|
| 39 |
+
num_attention_heads (`int`, *optional*, defaults to 16):
|
| 40 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 41 |
+
intermediate_size (`int`, *optional*, defaults to 4096):
|
| 42 |
+
Dimensionality of the "intermediate" (often called feed-forward) layer in the Transformer encoder.
|
| 43 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 44 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 45 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 46 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 47 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 48 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 49 |
+
The dropout ratio for the attention probabilities.
|
| 50 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 51 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 52 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 53 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 54 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 55 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 56 |
+
The epsilon used by the layer normalization layers.
|
| 57 |
+
pad_token_id (`int`, *optional*, defaults to 0):
|
| 58 |
+
Padding token id.
|
| 59 |
+
bos_token_id (`int`, *optional*, defaults to 2):
|
| 60 |
+
Beginning of stream token id.
|
| 61 |
+
eos_token_id (`int`, *optional*, defaults to 1):
|
| 62 |
+
End of stream token id.
|
| 63 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 64 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 65 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 66 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
| 67 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 68 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
| 69 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 70 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 71 |
+
relevant if `config.is_decoder=True`.
|
| 72 |
+
|
| 73 |
+
Examples:
|
| 74 |
+
|
| 75 |
+
```python
|
| 76 |
+
>>> from transformers import BertGenerationConfig, BertGenerationEncoder
|
| 77 |
+
|
| 78 |
+
>>> # Initializing a BertGeneration config
|
| 79 |
+
>>> configuration = BertGenerationConfig()
|
| 80 |
+
|
| 81 |
+
>>> # Initializing a model (with random weights) from the config
|
| 82 |
+
>>> model = BertGenerationEncoder(configuration)
|
| 83 |
+
|
| 84 |
+
>>> # Accessing the model configuration
|
| 85 |
+
>>> configuration = model.config
|
| 86 |
+
```"""
|
| 87 |
+
|
| 88 |
+
model_type = "bert-generation"
|
| 89 |
+
|
| 90 |
+
def __init__(
|
| 91 |
+
self,
|
| 92 |
+
vocab_size=50358,
|
| 93 |
+
hidden_size=1024,
|
| 94 |
+
num_hidden_layers=24,
|
| 95 |
+
num_attention_heads=16,
|
| 96 |
+
intermediate_size=4096,
|
| 97 |
+
hidden_act="gelu",
|
| 98 |
+
hidden_dropout_prob=0.1,
|
| 99 |
+
attention_probs_dropout_prob=0.1,
|
| 100 |
+
max_position_embeddings=512,
|
| 101 |
+
initializer_range=0.02,
|
| 102 |
+
layer_norm_eps=1e-12,
|
| 103 |
+
pad_token_id=0,
|
| 104 |
+
bos_token_id=2,
|
| 105 |
+
eos_token_id=1,
|
| 106 |
+
position_embedding_type="absolute",
|
| 107 |
+
use_cache=True,
|
| 108 |
+
**kwargs,
|
| 109 |
+
):
|
| 110 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 111 |
+
|
| 112 |
+
self.vocab_size = vocab_size
|
| 113 |
+
self.hidden_size = hidden_size
|
| 114 |
+
self.num_hidden_layers = num_hidden_layers
|
| 115 |
+
self.num_attention_heads = num_attention_heads
|
| 116 |
+
self.hidden_act = hidden_act
|
| 117 |
+
self.intermediate_size = intermediate_size
|
| 118 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 119 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 120 |
+
self.max_position_embeddings = max_position_embeddings
|
| 121 |
+
self.initializer_range = initializer_range
|
| 122 |
+
self.layer_norm_eps = layer_norm_eps
|
| 123 |
+
self.position_embedding_type = position_embedding_type
|
| 124 |
+
self.use_cache = use_cache
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
__all__ = ["BertGenerationConfig"]
|
janus/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_blenderbot_small.cpython-310.pyc
ADDED
|
Binary file (51.6 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_flax_blenderbot_small.cpython-310.pyc
ADDED
|
Binary file (43.2 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/blip_2/__pycache__/processing_blip_2.cpython-310.pyc
ADDED
|
Binary file (6.77 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/blip_2/modeling_blip_2.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
janus/lib/python3.10/site-packages/transformers/models/byt5/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (505 Bytes). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/byt5/__pycache__/tokenization_byt5.cpython-310.pyc
ADDED
|
Binary file (9.22 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/byt5/tokenization_byt5.py
ADDED
|
@@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 T5 Authors and HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization class for model ByT5."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
from typing import List, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
|
| 21 |
+
from ...utils import logging
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class ByT5Tokenizer(PreTrainedTokenizer):
|
| 28 |
+
"""
|
| 29 |
+
Construct a ByT5 tokenizer. ByT5 simply uses raw bytes utf-8 encoding.
|
| 30 |
+
|
| 31 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 32 |
+
this superclass for more information regarding those methods.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 36 |
+
The end of sequence token.
|
| 37 |
+
|
| 38 |
+
<Tip>
|
| 39 |
+
|
| 40 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 41 |
+
The token used is the `sep_token`.
|
| 42 |
+
|
| 43 |
+
</Tip>
|
| 44 |
+
|
| 45 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 46 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 47 |
+
token instead.
|
| 48 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 49 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 50 |
+
extra_ids (`int`, *optional*, defaults to 125):
|
| 51 |
+
Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are
|
| 52 |
+
accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. Extra tokens are
|
| 53 |
+
indexed from the end of the vocabulary up to beginning ("<extra_id_0>" is the last token in the vocabulary
|
| 54 |
+
like in ByT5 preprocessing see
|
| 55 |
+
[here](https://github.com/google-research/text-to-text-transfer-transformer/blob/9fd7b14a769417be33bc6c850f9598764913c833/t5/data/preprocessors.py#L2117)).
|
| 56 |
+
additional_special_tokens (`List[str]`, *optional*):
|
| 57 |
+
Additional special tokens used by the tokenizer.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 61 |
+
|
| 62 |
+
def __init__(
|
| 63 |
+
self,
|
| 64 |
+
eos_token="</s>",
|
| 65 |
+
unk_token="<unk>",
|
| 66 |
+
pad_token="<pad>",
|
| 67 |
+
extra_ids=125,
|
| 68 |
+
additional_special_tokens=None,
|
| 69 |
+
**kwargs,
|
| 70 |
+
) -> None:
|
| 71 |
+
# Add extra_ids to the special token list
|
| 72 |
+
if extra_ids > 0 and additional_special_tokens is None:
|
| 73 |
+
additional_special_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
|
| 74 |
+
elif extra_ids > 0 and additional_special_tokens is not None and len(additional_special_tokens) > 0:
|
| 75 |
+
# Check that we have the right number of extra_id special tokens
|
| 76 |
+
extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens)))
|
| 77 |
+
if extra_tokens != extra_ids:
|
| 78 |
+
raise ValueError(
|
| 79 |
+
f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
|
| 80 |
+
" provided to ByT5Tokenizer. In this case the additional_special_tokens must include the"
|
| 81 |
+
" extra_ids tokens"
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
pad_token = AddedToken(pad_token, lstrip=True, rstrip=True) if isinstance(pad_token, str) else pad_token
|
| 85 |
+
# we force left and right stripping for backward compatibility. The byt5tests depend on this.
|
| 86 |
+
eos_token = AddedToken(eos_token, lstrip=True, rstrip=True) if isinstance(eos_token, str) else eos_token
|
| 87 |
+
unk_token = AddedToken(unk_token, lstrip=True, rstrip=True) if isinstance(unk_token, str) else unk_token
|
| 88 |
+
# unk token needs to be in the vocab with correct index
|
| 89 |
+
self._added_tokens_decoder = {0: pad_token, 1: eos_token, 2: unk_token}
|
| 90 |
+
self.offset = len(self._added_tokens_decoder)
|
| 91 |
+
self._utf_vocab_size = 2**8 # utf is 8 bits
|
| 92 |
+
super().__init__(
|
| 93 |
+
eos_token=eos_token,
|
| 94 |
+
unk_token=unk_token,
|
| 95 |
+
pad_token=pad_token,
|
| 96 |
+
extra_ids=0,
|
| 97 |
+
additional_special_tokens=additional_special_tokens, # TODO extra ids are not used :sweatywmile:
|
| 98 |
+
**kwargs,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
@property
|
| 102 |
+
def vocab_size(self):
|
| 103 |
+
return self._utf_vocab_size
|
| 104 |
+
|
| 105 |
+
def get_vocab(self):
|
| 106 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size + self.offset)}
|
| 107 |
+
vocab.update(self.added_tokens_encoder)
|
| 108 |
+
return vocab
|
| 109 |
+
|
| 110 |
+
def get_special_tokens_mask(
|
| 111 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 112 |
+
) -> List[int]:
|
| 113 |
+
"""
|
| 114 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 115 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
token_ids_0 (`List[int]`):
|
| 119 |
+
List of IDs.
|
| 120 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 121 |
+
Optional second list of IDs for sequence pairs.
|
| 122 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 123 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 124 |
+
|
| 125 |
+
Returns:
|
| 126 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 127 |
+
"""
|
| 128 |
+
if already_has_special_tokens:
|
| 129 |
+
return super().get_special_tokens_mask(
|
| 130 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
# normal case: some special tokens
|
| 134 |
+
if token_ids_1 is None:
|
| 135 |
+
return ([0] * len(token_ids_0)) + [1]
|
| 136 |
+
return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
|
| 137 |
+
|
| 138 |
+
def _add_eos_if_not_present(self, token_ids: List[int]) -> List[int]:
|
| 139 |
+
"""Do not add eos again if user already added it."""
|
| 140 |
+
if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
|
| 141 |
+
warnings.warn(
|
| 142 |
+
f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"
|
| 143 |
+
" eos tokens being added."
|
| 144 |
+
)
|
| 145 |
+
return token_ids
|
| 146 |
+
else:
|
| 147 |
+
return token_ids + [self.eos_token_id]
|
| 148 |
+
|
| 149 |
+
def create_token_type_ids_from_sequences(
|
| 150 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 151 |
+
) -> List[int]:
|
| 152 |
+
"""
|
| 153 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. ByT5 does not
|
| 154 |
+
make use of token type ids, therefore a list of zeros is returned.
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
token_ids_0 (`List[int]`):
|
| 158 |
+
List of IDs.
|
| 159 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 160 |
+
Optional second list of IDs for sequence pairs.
|
| 161 |
+
|
| 162 |
+
Returns:
|
| 163 |
+
`List[int]`: List of zeros.
|
| 164 |
+
"""
|
| 165 |
+
eos = [self.eos_token_id]
|
| 166 |
+
|
| 167 |
+
if token_ids_1 is None:
|
| 168 |
+
return len(token_ids_0 + eos) * [0]
|
| 169 |
+
return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
|
| 170 |
+
|
| 171 |
+
def build_inputs_with_special_tokens(
|
| 172 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 173 |
+
) -> List[int]:
|
| 174 |
+
"""
|
| 175 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 176 |
+
adding special tokens. A sequence has the following format:
|
| 177 |
+
|
| 178 |
+
- single sequence: `X </s>`
|
| 179 |
+
- pair of sequences: `A </s> B </s>`
|
| 180 |
+
|
| 181 |
+
Args:
|
| 182 |
+
token_ids_0 (`List[int]`):
|
| 183 |
+
List of IDs to which the special tokens will be added.
|
| 184 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 185 |
+
Optional second list of IDs for sequence pairs.
|
| 186 |
+
|
| 187 |
+
Returns:
|
| 188 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 189 |
+
"""
|
| 190 |
+
token_ids_0 = self._add_eos_if_not_present(token_ids_0)
|
| 191 |
+
if token_ids_1 is None:
|
| 192 |
+
return token_ids_0
|
| 193 |
+
else:
|
| 194 |
+
token_ids_1 = self._add_eos_if_not_present(token_ids_1)
|
| 195 |
+
return token_ids_0 + token_ids_1
|
| 196 |
+
|
| 197 |
+
def _tokenize(self, text: str) -> List[str]:
|
| 198 |
+
"""Take as input a string and return a list of strings (tokens) for words/sub-words"""
|
| 199 |
+
tokens = [chr(i) for i in text.encode("utf-8")]
|
| 200 |
+
return tokens
|
| 201 |
+
|
| 202 |
+
def _convert_token_to_id(self, token):
|
| 203 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 204 |
+
|
| 205 |
+
if len(token) != 1:
|
| 206 |
+
token_id = None
|
| 207 |
+
else:
|
| 208 |
+
token_id = ord(token) + self.offset
|
| 209 |
+
|
| 210 |
+
return token_id
|
| 211 |
+
|
| 212 |
+
def _convert_id_to_token(self, index):
|
| 213 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 214 |
+
token = chr(index - self.offset)
|
| 215 |
+
return token
|
| 216 |
+
|
| 217 |
+
def convert_tokens_to_string(self, tokens):
|
| 218 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 219 |
+
bstring = b""
|
| 220 |
+
for token in tokens:
|
| 221 |
+
if token in self.added_tokens_decoder:
|
| 222 |
+
tok_string = self.added_tokens_decoder[token].encode("utf-8")
|
| 223 |
+
elif token in self.added_tokens_encoder:
|
| 224 |
+
tok_string = token.encode("utf-8")
|
| 225 |
+
else:
|
| 226 |
+
tok_string = bytes([ord(token)])
|
| 227 |
+
bstring += tok_string
|
| 228 |
+
string = bstring.decode("utf-8", errors="ignore")
|
| 229 |
+
return string
|
| 230 |
+
|
| 231 |
+
# ByT5Tokenizer has no vocab file
|
| 232 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 233 |
+
return ()
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
__all__ = ["ByT5Tokenizer"]
|
janus/lib/python3.10/site-packages/transformers/models/chinese_clip/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_chinese_clip import *
|
| 22 |
+
from .feature_extraction_chinese_clip import *
|
| 23 |
+
from .image_processing_chinese_clip import *
|
| 24 |
+
from .modeling_chinese_clip import *
|
| 25 |
+
from .processing_chinese_clip import *
|
| 26 |
+
else:
|
| 27 |
+
import sys
|
| 28 |
+
|
| 29 |
+
_file = globals()["__file__"]
|
| 30 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
janus/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (674 Bytes). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/configuration_chinese_clip.cpython-310.pyc
ADDED
|
Binary file (16.9 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/feature_extraction_chinese_clip.cpython-310.pyc
ADDED
|
Binary file (1.06 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/image_processing_chinese_clip.cpython-310.pyc
ADDED
|
Binary file (12.5 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/modeling_chinese_clip.cpython-310.pyc
ADDED
|
Binary file (50.5 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/chinese_clip/configuration_chinese_clip.py
ADDED
|
@@ -0,0 +1,434 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The OFA-Sys Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Chinese-CLIP model configuration"""
|
| 16 |
+
|
| 17 |
+
from collections import OrderedDict
|
| 18 |
+
from typing import TYPE_CHECKING, Any, Mapping, Optional
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING:
|
| 22 |
+
from ...processing_utils import ProcessorMixin
|
| 23 |
+
from ...utils import TensorType
|
| 24 |
+
|
| 25 |
+
from ...configuration_utils import PretrainedConfig
|
| 26 |
+
from ...onnx import OnnxConfig
|
| 27 |
+
from ...utils import logging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class ChineseCLIPTextConfig(PretrainedConfig):
|
| 34 |
+
r"""
|
| 35 |
+
This is the configuration class to store the configuration of a [`ChineseCLIPModel`]. It is used to instantiate a
|
| 36 |
+
Chinese CLIP model according to the specified arguments, defining the model architecture. Instantiating a
|
| 37 |
+
configuration with the defaults will yield a similar configuration to that of the Chinese CLIP
|
| 38 |
+
[OFA-Sys/chinese-clip-vit-base-patch16](https:
|
| 39 |
+
//huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16) architecture.
|
| 40 |
+
|
| 41 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 42 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
| 47 |
+
Vocabulary size of the CHINESE_CLIP model. Defines the number of different tokens that can be represented
|
| 48 |
+
by the `inputs_ids` passed when calling [`ChineseCLIPModel`].
|
| 49 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 50 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 51 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 52 |
+
Number of hidden layers in the Transformer encoder.
|
| 53 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 54 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 55 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 56 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 57 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
| 58 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 59 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 60 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 61 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 62 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 63 |
+
The dropout ratio for the attention probabilities.
|
| 64 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 65 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 66 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 67 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
| 68 |
+
The vocabulary size of the `token_type_ids` passed when calling [`ChineseCLIPModel`].
|
| 69 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 70 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 71 |
+
initializer_factor (`float`, *optional*, defaults to 1.0):
|
| 72 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
| 73 |
+
testing).
|
| 74 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 75 |
+
The epsilon used by the layer normalization layers.
|
| 76 |
+
pad_token_id (`int`, *optional*, defaults to 0):
|
| 77 |
+
Padding token id.
|
| 78 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 79 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 80 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 81 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
| 82 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 83 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
| 84 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 85 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 86 |
+
relevant if `config.is_decoder=True`.
|
| 87 |
+
|
| 88 |
+
Example:
|
| 89 |
+
|
| 90 |
+
```python
|
| 91 |
+
>>> from transformers import ChineseCLIPTextConfig, ChineseCLIPTextModel
|
| 92 |
+
|
| 93 |
+
>>> # Initializing a ChineseCLIPTextConfig with OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
| 94 |
+
>>> configuration = ChineseCLIPTextConfig()
|
| 95 |
+
|
| 96 |
+
>>> # Initializing a ChineseCLIPTextModel (with random weights) from the OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
| 97 |
+
>>> model = ChineseCLIPTextModel(configuration)
|
| 98 |
+
|
| 99 |
+
>>> # Accessing the model configuration
|
| 100 |
+
>>> configuration = model.config
|
| 101 |
+
```"""
|
| 102 |
+
|
| 103 |
+
model_type = "chinese_clip_text_model"
|
| 104 |
+
base_config_key = "text_config"
|
| 105 |
+
|
| 106 |
+
def __init__(
|
| 107 |
+
self,
|
| 108 |
+
vocab_size=30522,
|
| 109 |
+
hidden_size=768,
|
| 110 |
+
num_hidden_layers=12,
|
| 111 |
+
num_attention_heads=12,
|
| 112 |
+
intermediate_size=3072,
|
| 113 |
+
hidden_act="gelu",
|
| 114 |
+
hidden_dropout_prob=0.1,
|
| 115 |
+
attention_probs_dropout_prob=0.1,
|
| 116 |
+
max_position_embeddings=512,
|
| 117 |
+
type_vocab_size=2,
|
| 118 |
+
initializer_range=0.02,
|
| 119 |
+
initializer_factor=1.0,
|
| 120 |
+
layer_norm_eps=1e-12,
|
| 121 |
+
pad_token_id=0,
|
| 122 |
+
position_embedding_type="absolute",
|
| 123 |
+
use_cache=True,
|
| 124 |
+
**kwargs,
|
| 125 |
+
):
|
| 126 |
+
super().__init__(pad_token_id=pad_token_id, **kwargs)
|
| 127 |
+
|
| 128 |
+
self.vocab_size = vocab_size
|
| 129 |
+
self.hidden_size = hidden_size
|
| 130 |
+
self.num_hidden_layers = num_hidden_layers
|
| 131 |
+
self.num_attention_heads = num_attention_heads
|
| 132 |
+
self.hidden_act = hidden_act
|
| 133 |
+
self.intermediate_size = intermediate_size
|
| 134 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 135 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 136 |
+
self.max_position_embeddings = max_position_embeddings
|
| 137 |
+
self.type_vocab_size = type_vocab_size
|
| 138 |
+
self.initializer_range = initializer_range
|
| 139 |
+
self.initializer_factor = initializer_factor
|
| 140 |
+
self.layer_norm_eps = layer_norm_eps
|
| 141 |
+
self.position_embedding_type = position_embedding_type
|
| 142 |
+
self.use_cache = use_cache
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class ChineseCLIPVisionConfig(PretrainedConfig):
|
| 146 |
+
r"""
|
| 147 |
+
This is the configuration class to store the configuration of a [`ChineseCLIPModel`]. It is used to instantiate an
|
| 148 |
+
ChineseCLIP model according to the specified arguments, defining the model architecture. Instantiating a
|
| 149 |
+
configuration with the defaults will yield a similar configuration to that of the ChineseCLIP
|
| 150 |
+
[OFA-Sys/chinese-clip-vit-base-patch16](https://huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16) architecture.
|
| 151 |
+
|
| 152 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 153 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 158 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 159 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 160 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 161 |
+
projection_dim (`int`, *optional*, defaults to 512):
|
| 162 |
+
Dimensionality of text and vision projection layers.
|
| 163 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 164 |
+
Number of hidden layers in the Transformer encoder.
|
| 165 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 166 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 167 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 168 |
+
The number of input channels.
|
| 169 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 170 |
+
The size (resolution) of each image.
|
| 171 |
+
patch_size (`int`, *optional*, defaults to 32):
|
| 172 |
+
The size (resolution) of each patch.
|
| 173 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
|
| 174 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 175 |
+
`"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
|
| 176 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 177 |
+
The epsilon used by the layer normalization layers.
|
| 178 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 179 |
+
The dropout ratio for the attention probabilities.
|
| 180 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 181 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 182 |
+
initializer_factor (`float`, *optional*, defaults to 1.0):
|
| 183 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
| 184 |
+
testing).
|
| 185 |
+
Example:
|
| 186 |
+
```python
|
| 187 |
+
>>> from transformers import ChineseCLIPVisionConfig, ChineseCLIPVisionModel
|
| 188 |
+
|
| 189 |
+
>>> # Initializing a ChineseCLIPVisionConfig with OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
| 190 |
+
>>> configuration = ChineseCLIPVisionConfig()
|
| 191 |
+
|
| 192 |
+
>>> # Initializing a ChineseCLIPVisionModel (with random weights) from the OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
| 193 |
+
>>> model = ChineseCLIPVisionModel(configuration)
|
| 194 |
+
|
| 195 |
+
>>> # Accessing the model configuration
|
| 196 |
+
>>> configuration = model.config
|
| 197 |
+
```"""
|
| 198 |
+
|
| 199 |
+
model_type = "chinese_clip_vision_model"
|
| 200 |
+
base_config_key = "vision_config"
|
| 201 |
+
|
| 202 |
+
def __init__(
|
| 203 |
+
self,
|
| 204 |
+
hidden_size=768,
|
| 205 |
+
intermediate_size=3072,
|
| 206 |
+
projection_dim=512,
|
| 207 |
+
num_hidden_layers=12,
|
| 208 |
+
num_attention_heads=12,
|
| 209 |
+
num_channels=3,
|
| 210 |
+
image_size=224,
|
| 211 |
+
patch_size=32,
|
| 212 |
+
hidden_act="quick_gelu",
|
| 213 |
+
layer_norm_eps=1e-5,
|
| 214 |
+
attention_dropout=0.0,
|
| 215 |
+
initializer_range=0.02,
|
| 216 |
+
initializer_factor=1.0,
|
| 217 |
+
**kwargs,
|
| 218 |
+
):
|
| 219 |
+
super().__init__(**kwargs)
|
| 220 |
+
|
| 221 |
+
self.hidden_size = hidden_size
|
| 222 |
+
self.intermediate_size = intermediate_size
|
| 223 |
+
self.projection_dim = projection_dim
|
| 224 |
+
self.num_hidden_layers = num_hidden_layers
|
| 225 |
+
self.num_attention_heads = num_attention_heads
|
| 226 |
+
self.num_channels = num_channels
|
| 227 |
+
self.patch_size = patch_size
|
| 228 |
+
self.image_size = image_size
|
| 229 |
+
self.initializer_range = initializer_range
|
| 230 |
+
self.initializer_factor = initializer_factor
|
| 231 |
+
self.attention_dropout = attention_dropout
|
| 232 |
+
self.layer_norm_eps = layer_norm_eps
|
| 233 |
+
self.hidden_act = hidden_act
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
class ChineseCLIPConfig(PretrainedConfig):
|
| 237 |
+
r"""
|
| 238 |
+
[`ChineseCLIPConfig`] is the configuration class to store the configuration of a [`ChineseCLIPModel`]. It is used
|
| 239 |
+
to instantiate Chinese-CLIP model according to the specified arguments, defining the text model and vision model
|
| 240 |
+
configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the
|
| 241 |
+
Chinese-CLIP [OFA-Sys/chinese-clip-vit-base-patch16](https://huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16)
|
| 242 |
+
architecture.
|
| 243 |
+
|
| 244 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 245 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 246 |
+
|
| 247 |
+
Args:
|
| 248 |
+
text_config (`dict`, *optional*):
|
| 249 |
+
Dictionary of configuration options used to initialize [`ChineseCLIPTextConfig`].
|
| 250 |
+
vision_config (`dict`, *optional*):
|
| 251 |
+
Dictionary of configuration options used to initialize [`ChineseCLIPVisionConfig`].
|
| 252 |
+
projection_dim (`int`, *optional*, defaults to 512):
|
| 253 |
+
Dimensionality of text and vision projection layers.
|
| 254 |
+
logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
|
| 255 |
+
The initial value of the *logit_scale* parameter. Default is used as per the original ChineseCLIP
|
| 256 |
+
implementation.
|
| 257 |
+
kwargs (*optional*):
|
| 258 |
+
Dictionary of keyword arguments.
|
| 259 |
+
|
| 260 |
+
Example:
|
| 261 |
+
|
| 262 |
+
```python
|
| 263 |
+
>>> from transformers import ChineseCLIPConfig, ChineseCLIPModel
|
| 264 |
+
|
| 265 |
+
>>> # Initializing a ChineseCLIPConfig with OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
| 266 |
+
>>> configuration = ChineseCLIPConfig()
|
| 267 |
+
|
| 268 |
+
>>> # Initializing a ChineseCLIPModel (with random weights) from the OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
| 269 |
+
>>> model = ChineseCLIPModel(configuration)
|
| 270 |
+
|
| 271 |
+
>>> # Accessing the model configuration
|
| 272 |
+
>>> configuration = model.config
|
| 273 |
+
|
| 274 |
+
>>> # We can also initialize a ChineseCLIPConfig from a ChineseCLIPTextConfig and a ChineseCLIPVisionConfig
|
| 275 |
+
|
| 276 |
+
>>> # Initializing a ChineseCLIPTextConfig and ChineseCLIPVisionConfig configuration
|
| 277 |
+
>>> config_text = ChineseCLIPTextConfig()
|
| 278 |
+
>>> config_vision = ChineseCLIPVisionConfig()
|
| 279 |
+
|
| 280 |
+
>>> config = ChineseCLIPConfig.from_text_vision_configs(config_text, config_vision)
|
| 281 |
+
```"""
|
| 282 |
+
|
| 283 |
+
model_type = "chinese_clip"
|
| 284 |
+
sub_configs = {"text_config": ChineseCLIPTextConfig, "vision_config": ChineseCLIPVisionConfig}
|
| 285 |
+
|
| 286 |
+
def __init__(
|
| 287 |
+
self, text_config=None, vision_config=None, projection_dim=512, logit_scale_init_value=2.6592, **kwargs
|
| 288 |
+
):
|
| 289 |
+
# If `_config_dict` exist, we use them for the backward compatibility.
|
| 290 |
+
# We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
|
| 291 |
+
# of confusion!).
|
| 292 |
+
text_config_dict = kwargs.pop("text_config_dict", None)
|
| 293 |
+
vision_config_dict = kwargs.pop("vision_config_dict", None)
|
| 294 |
+
|
| 295 |
+
super().__init__(**kwargs)
|
| 296 |
+
|
| 297 |
+
# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
|
| 298 |
+
# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
|
| 299 |
+
# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
|
| 300 |
+
if text_config_dict is not None:
|
| 301 |
+
if text_config is None:
|
| 302 |
+
text_config = {}
|
| 303 |
+
|
| 304 |
+
# This is the complete result when using `text_config_dict`.
|
| 305 |
+
_text_config_dict = ChineseCLIPTextConfig(**text_config_dict).to_dict()
|
| 306 |
+
|
| 307 |
+
# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
|
| 308 |
+
for key, value in _text_config_dict.items():
|
| 309 |
+
if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
|
| 310 |
+
# If specified in `text_config_dict`
|
| 311 |
+
if key in text_config_dict:
|
| 312 |
+
message = (
|
| 313 |
+
f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
|
| 314 |
+
f'The value `text_config_dict["{key}"]` will be used instead.'
|
| 315 |
+
)
|
| 316 |
+
# If inferred from default argument values (just to be super careful)
|
| 317 |
+
else:
|
| 318 |
+
message = (
|
| 319 |
+
f"`text_config_dict` is provided which will be used to initialize `ChineseCLIPTextConfig`. "
|
| 320 |
+
f'The value `text_config["{key}"]` will be overridden.'
|
| 321 |
+
)
|
| 322 |
+
logger.info(message)
|
| 323 |
+
|
| 324 |
+
# Update all values in `text_config` with the ones in `_text_config_dict`.
|
| 325 |
+
text_config.update(_text_config_dict)
|
| 326 |
+
|
| 327 |
+
if vision_config_dict is not None:
|
| 328 |
+
if vision_config is None:
|
| 329 |
+
vision_config = {}
|
| 330 |
+
|
| 331 |
+
# This is the complete result when using `vision_config_dict`.
|
| 332 |
+
_vision_config_dict = ChineseCLIPVisionConfig(**vision_config_dict).to_dict()
|
| 333 |
+
# convert keys to string instead of integer
|
| 334 |
+
if "id2label" in _vision_config_dict:
|
| 335 |
+
_vision_config_dict["id2label"] = {
|
| 336 |
+
str(key): value for key, value in _vision_config_dict["id2label"].items()
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
|
| 340 |
+
for key, value in _vision_config_dict.items():
|
| 341 |
+
if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
|
| 342 |
+
# If specified in `vision_config_dict`
|
| 343 |
+
if key in vision_config_dict:
|
| 344 |
+
message = (
|
| 345 |
+
f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
|
| 346 |
+
f'values. The value `vision_config_dict["{key}"]` will be used instead.'
|
| 347 |
+
)
|
| 348 |
+
# If inferred from default argument values (just to be super careful)
|
| 349 |
+
else:
|
| 350 |
+
message = (
|
| 351 |
+
f"`vision_config_dict` is provided which will be used to initialize "
|
| 352 |
+
f'`ChineseCLIPVisionConfig`. The value `vision_config["{key}"]` will be overridden.'
|
| 353 |
+
)
|
| 354 |
+
logger.info(message)
|
| 355 |
+
|
| 356 |
+
# Update all values in `vision_config` with the ones in `_vision_config_dict`.
|
| 357 |
+
vision_config.update(_vision_config_dict)
|
| 358 |
+
|
| 359 |
+
if text_config is None:
|
| 360 |
+
text_config = {}
|
| 361 |
+
logger.info("`text_config` is `None`. Initializing the `ChineseCLIPTextConfig` with default values.")
|
| 362 |
+
|
| 363 |
+
if vision_config is None:
|
| 364 |
+
vision_config = {}
|
| 365 |
+
logger.info("`vision_config` is `None`. initializing the `ChineseCLIPVisionConfig` with default values.")
|
| 366 |
+
|
| 367 |
+
self.text_config = ChineseCLIPTextConfig(**text_config)
|
| 368 |
+
self.vision_config = ChineseCLIPVisionConfig(**vision_config)
|
| 369 |
+
|
| 370 |
+
self.projection_dim = projection_dim
|
| 371 |
+
self.logit_scale_init_value = logit_scale_init_value
|
| 372 |
+
self.initializer_factor = 1.0
|
| 373 |
+
self.initializer_range = 0.02
|
| 374 |
+
|
| 375 |
+
@classmethod
|
| 376 |
+
def from_text_vision_configs(
|
| 377 |
+
cls, text_config: ChineseCLIPTextConfig, vision_config: ChineseCLIPVisionConfig, **kwargs
|
| 378 |
+
):
|
| 379 |
+
r"""
|
| 380 |
+
Instantiate a [`ChineseCLIPConfig`] (or a derived class) from Chinese-CLIP text model configuration and
|
| 381 |
+
Chinese-CLIP vision model configuration. Returns:
|
| 382 |
+
[`ChineseCLIPConfig`]: An instance of a configuration object
|
| 383 |
+
"""
|
| 384 |
+
|
| 385 |
+
return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
class ChineseCLIPOnnxConfig(OnnxConfig):
|
| 389 |
+
@property
|
| 390 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 391 |
+
return OrderedDict(
|
| 392 |
+
[
|
| 393 |
+
("input_ids", {0: "batch", 1: "sequence"}),
|
| 394 |
+
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
|
| 395 |
+
("attention_mask", {0: "batch", 1: "sequence"}),
|
| 396 |
+
]
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
@property
|
| 400 |
+
def outputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 401 |
+
return OrderedDict(
|
| 402 |
+
[
|
| 403 |
+
("logits_per_image", {0: "batch"}),
|
| 404 |
+
("logits_per_text", {0: "batch"}),
|
| 405 |
+
("text_embeds", {0: "batch"}),
|
| 406 |
+
("image_embeds", {0: "batch"}),
|
| 407 |
+
]
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
@property
|
| 411 |
+
def atol_for_validation(self) -> float:
|
| 412 |
+
return 1e-4
|
| 413 |
+
|
| 414 |
+
def generate_dummy_inputs(
|
| 415 |
+
self,
|
| 416 |
+
processor: "ProcessorMixin",
|
| 417 |
+
batch_size: int = -1,
|
| 418 |
+
seq_length: int = -1,
|
| 419 |
+
framework: Optional["TensorType"] = None,
|
| 420 |
+
) -> Mapping[str, Any]:
|
| 421 |
+
text_input_dict = super().generate_dummy_inputs(
|
| 422 |
+
processor.tokenizer, batch_size=batch_size, seq_length=seq_length, framework=framework
|
| 423 |
+
)
|
| 424 |
+
image_input_dict = super().generate_dummy_inputs(
|
| 425 |
+
processor.image_processor, batch_size=batch_size, framework=framework
|
| 426 |
+
)
|
| 427 |
+
return {**text_input_dict, **image_input_dict}
|
| 428 |
+
|
| 429 |
+
@property
|
| 430 |
+
def default_onnx_opset(self) -> int:
|
| 431 |
+
return 14
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
__all__ = ["ChineseCLIPConfig", "ChineseCLIPOnnxConfig", "ChineseCLIPTextConfig", "ChineseCLIPVisionConfig"]
|
janus/lib/python3.10/site-packages/transformers/models/chinese_clip/feature_extraction_chinese_clip.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The OFA-Sys Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Feature extractor class for Chinese-CLIP."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
|
| 19 |
+
from ...utils import logging
|
| 20 |
+
from .image_processing_chinese_clip import ChineseCLIPImageProcessor
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ChineseCLIPFeatureExtractor(ChineseCLIPImageProcessor):
|
| 27 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 28 |
+
warnings.warn(
|
| 29 |
+
"The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers."
|
| 30 |
+
" Please use ChineseCLIPImageProcessor instead.",
|
| 31 |
+
FutureWarning,
|
| 32 |
+
)
|
| 33 |
+
super().__init__(*args, **kwargs)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
__all__ = ["ChineseCLIPFeatureExtractor"]
|
janus/lib/python3.10/site-packages/transformers/models/chinese_clip/image_processing_chinese_clip.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The OFA-Sys Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Image processor class for Chinese-CLIP."""
|
| 16 |
+
|
| 17 |
+
from typing import Dict, List, Optional, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
| 22 |
+
from ...image_transforms import (
|
| 23 |
+
convert_to_rgb,
|
| 24 |
+
get_resize_output_image_size,
|
| 25 |
+
resize,
|
| 26 |
+
to_channel_dimension_format,
|
| 27 |
+
)
|
| 28 |
+
from ...image_utils import (
|
| 29 |
+
OPENAI_CLIP_MEAN,
|
| 30 |
+
OPENAI_CLIP_STD,
|
| 31 |
+
ChannelDimension,
|
| 32 |
+
ImageInput,
|
| 33 |
+
PILImageResampling,
|
| 34 |
+
infer_channel_dimension_format,
|
| 35 |
+
is_scaled_image,
|
| 36 |
+
make_list_of_images,
|
| 37 |
+
to_numpy_array,
|
| 38 |
+
valid_images,
|
| 39 |
+
validate_preprocess_arguments,
|
| 40 |
+
)
|
| 41 |
+
from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
logger = logging.get_logger(__name__)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if is_vision_available():
|
| 48 |
+
import PIL
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class ChineseCLIPImageProcessor(BaseImageProcessor):
|
| 52 |
+
r"""
|
| 53 |
+
Constructs a Chinese-CLIP image processor.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 57 |
+
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
|
| 58 |
+
`do_resize` in the `preprocess` method.
|
| 59 |
+
size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
|
| 60 |
+
Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with
|
| 61 |
+
the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess`
|
| 62 |
+
method.
|
| 63 |
+
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
|
| 64 |
+
Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
|
| 65 |
+
do_center_crop (`bool`, *optional*, defaults to `True`):
|
| 66 |
+
Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
|
| 67 |
+
`preprocess` method.
|
| 68 |
+
crop_size (`Dict[str, int]` *optional*, defaults to 224):
|
| 69 |
+
Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
|
| 70 |
+
method.
|
| 71 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 72 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
|
| 73 |
+
the `preprocess` method.
|
| 74 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
| 75 |
+
Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
|
| 76 |
+
method.
|
| 77 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 78 |
+
Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
|
| 79 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
|
| 80 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
| 81 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
| 82 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
|
| 83 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
| 84 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 85 |
+
Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 86 |
+
do_convert_rgb (`bool`, *optional*, defaults to `True`):
|
| 87 |
+
Whether to convert the image to RGB.
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
model_input_names = ["pixel_values"]
|
| 91 |
+
|
| 92 |
+
def __init__(
|
| 93 |
+
self,
|
| 94 |
+
do_resize: bool = True,
|
| 95 |
+
size: Dict[str, int] = None,
|
| 96 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 97 |
+
do_center_crop: bool = True,
|
| 98 |
+
crop_size: Dict[str, int] = None,
|
| 99 |
+
do_rescale: bool = True,
|
| 100 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 101 |
+
do_normalize: bool = True,
|
| 102 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 103 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 104 |
+
do_convert_rgb: bool = True,
|
| 105 |
+
**kwargs,
|
| 106 |
+
) -> None:
|
| 107 |
+
super().__init__(**kwargs)
|
| 108 |
+
size = size if size is not None else {"shortest_edge": 224}
|
| 109 |
+
size = get_size_dict(size, default_to_square=False)
|
| 110 |
+
crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
|
| 111 |
+
crop_size = get_size_dict(crop_size)
|
| 112 |
+
|
| 113 |
+
self.do_resize = do_resize
|
| 114 |
+
self.size = size
|
| 115 |
+
self.resample = resample
|
| 116 |
+
self.do_center_crop = do_center_crop
|
| 117 |
+
self.crop_size = crop_size
|
| 118 |
+
self.do_rescale = do_rescale
|
| 119 |
+
self.rescale_factor = rescale_factor
|
| 120 |
+
self.do_normalize = do_normalize
|
| 121 |
+
self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
|
| 122 |
+
self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
|
| 123 |
+
self.do_convert_rgb = do_convert_rgb
|
| 124 |
+
|
| 125 |
+
def resize(
|
| 126 |
+
self,
|
| 127 |
+
image: np.ndarray,
|
| 128 |
+
size: Dict[str, int],
|
| 129 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 130 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 131 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 132 |
+
**kwargs,
|
| 133 |
+
) -> np.ndarray:
|
| 134 |
+
"""
|
| 135 |
+
Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
|
| 136 |
+
resized to keep the input aspect ratio.
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
image (`np.ndarray`):
|
| 140 |
+
Image to resize.
|
| 141 |
+
size (`Dict[str, int]`):
|
| 142 |
+
Size of the output image.
|
| 143 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
| 144 |
+
Resampling filter to use when resiizing the image.
|
| 145 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 146 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
| 147 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 148 |
+
The channel dimension format of the input image. If not provided, it will be inferred from the input
|
| 149 |
+
image.
|
| 150 |
+
"""
|
| 151 |
+
size = get_size_dict(size, default_to_square=False)
|
| 152 |
+
output_size = get_resize_output_image_size(
|
| 153 |
+
image, size=(size["height"], size["width"]), default_to_square=False, input_data_format=input_data_format
|
| 154 |
+
)
|
| 155 |
+
return resize(
|
| 156 |
+
image,
|
| 157 |
+
size=output_size,
|
| 158 |
+
resample=resample,
|
| 159 |
+
data_format=data_format,
|
| 160 |
+
input_data_format=input_data_format,
|
| 161 |
+
**kwargs,
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
@filter_out_non_signature_kwargs()
|
| 165 |
+
def preprocess(
|
| 166 |
+
self,
|
| 167 |
+
images: ImageInput,
|
| 168 |
+
do_resize: bool = None,
|
| 169 |
+
size: Dict[str, int] = None,
|
| 170 |
+
resample: PILImageResampling = None,
|
| 171 |
+
do_center_crop: bool = None,
|
| 172 |
+
crop_size: int = None,
|
| 173 |
+
do_rescale: bool = None,
|
| 174 |
+
rescale_factor: float = None,
|
| 175 |
+
do_normalize: bool = None,
|
| 176 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 177 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 178 |
+
do_convert_rgb: bool = None,
|
| 179 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 180 |
+
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
|
| 181 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 182 |
+
) -> PIL.Image.Image:
|
| 183 |
+
"""
|
| 184 |
+
Preprocess an image or batch of images.
|
| 185 |
+
|
| 186 |
+
Args:
|
| 187 |
+
images (`ImageInput`):
|
| 188 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 189 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 190 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 191 |
+
Whether to resize the image.
|
| 192 |
+
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
|
| 193 |
+
Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
|
| 194 |
+
the longest edge resized to keep the input aspect ratio.
|
| 195 |
+
resample (`int`, *optional*, defaults to `self.resample`):
|
| 196 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
|
| 197 |
+
has an effect if `do_resize` is set to `True`.
|
| 198 |
+
do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
|
| 199 |
+
Whether to center crop the image.
|
| 200 |
+
crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
|
| 201 |
+
Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
|
| 202 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 203 |
+
Whether to rescale the image.
|
| 204 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 205 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 206 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 207 |
+
Whether to normalize the image.
|
| 208 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
| 209 |
+
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
| 210 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
| 211 |
+
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
|
| 212 |
+
`True`.
|
| 213 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
| 214 |
+
Whether to convert the image to RGB.
|
| 215 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 216 |
+
The type of tensors to return. Can be one of:
|
| 217 |
+
- Unset: Return a list of `np.ndarray`.
|
| 218 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 219 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 220 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 221 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 222 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 223 |
+
The channel dimension format for the output image. Can be one of:
|
| 224 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 225 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 226 |
+
- Unset: Use the channel dimension format of the input image.
|
| 227 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 228 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 229 |
+
from the input image. Can be one of:
|
| 230 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 231 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 232 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 233 |
+
"""
|
| 234 |
+
|
| 235 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 236 |
+
size = size if size is not None else self.size
|
| 237 |
+
size = get_size_dict(size, default_to_square=False)
|
| 238 |
+
resample = resample if resample is not None else self.resample
|
| 239 |
+
do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
|
| 240 |
+
crop_size = crop_size if crop_size is not None else self.crop_size
|
| 241 |
+
crop_size = get_size_dict(crop_size)
|
| 242 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 243 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 244 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 245 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 246 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 247 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
| 248 |
+
|
| 249 |
+
images = make_list_of_images(images)
|
| 250 |
+
|
| 251 |
+
if not valid_images(images):
|
| 252 |
+
raise ValueError(
|
| 253 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 254 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 255 |
+
)
|
| 256 |
+
validate_preprocess_arguments(
|
| 257 |
+
do_rescale=do_rescale,
|
| 258 |
+
rescale_factor=rescale_factor,
|
| 259 |
+
do_normalize=do_normalize,
|
| 260 |
+
image_mean=image_mean,
|
| 261 |
+
image_std=image_std,
|
| 262 |
+
do_center_crop=do_center_crop,
|
| 263 |
+
crop_size=crop_size,
|
| 264 |
+
do_resize=do_resize,
|
| 265 |
+
size=size,
|
| 266 |
+
resample=resample,
|
| 267 |
+
)
|
| 268 |
+
if do_convert_rgb:
|
| 269 |
+
images = [convert_to_rgb(image) for image in images]
|
| 270 |
+
|
| 271 |
+
# All transformations expect numpy arrays.
|
| 272 |
+
images = [to_numpy_array(image) for image in images]
|
| 273 |
+
|
| 274 |
+
if do_rescale and is_scaled_image(images[0]):
|
| 275 |
+
logger.warning_once(
|
| 276 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 277 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
if input_data_format is None:
|
| 281 |
+
# We assume that all images have the same channel dimension format.
|
| 282 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 283 |
+
|
| 284 |
+
all_images = []
|
| 285 |
+
for image in images:
|
| 286 |
+
if do_resize:
|
| 287 |
+
image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
|
| 288 |
+
|
| 289 |
+
if do_center_crop:
|
| 290 |
+
image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)
|
| 291 |
+
|
| 292 |
+
if do_rescale:
|
| 293 |
+
image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
| 294 |
+
|
| 295 |
+
if do_normalize:
|
| 296 |
+
image = self.normalize(
|
| 297 |
+
image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
all_images.append(image)
|
| 301 |
+
images = [
|
| 302 |
+
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
| 303 |
+
for image in all_images
|
| 304 |
+
]
|
| 305 |
+
|
| 306 |
+
data = {"pixel_values": images}
|
| 307 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
__all__ = ["ChineseCLIPImageProcessor"]
|
janus/lib/python3.10/site-packages/transformers/models/chinese_clip/modeling_chinese_clip.py
ADDED
|
@@ -0,0 +1,1630 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The OFA-Sys Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch Chinese-CLIP model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import Any, List, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.utils.checkpoint
|
| 23 |
+
from torch import nn
|
| 24 |
+
|
| 25 |
+
from ...activations import ACT2FN
|
| 26 |
+
from ...modeling_outputs import (
|
| 27 |
+
BaseModelOutput,
|
| 28 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 29 |
+
BaseModelOutputWithPooling,
|
| 30 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
| 31 |
+
)
|
| 32 |
+
from ...modeling_utils import PreTrainedModel
|
| 33 |
+
from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
|
| 34 |
+
from ...utils import (
|
| 35 |
+
ModelOutput,
|
| 36 |
+
add_code_sample_docstrings,
|
| 37 |
+
add_start_docstrings,
|
| 38 |
+
add_start_docstrings_to_model_forward,
|
| 39 |
+
logging,
|
| 40 |
+
replace_return_docstrings,
|
| 41 |
+
torch_int,
|
| 42 |
+
)
|
| 43 |
+
from .configuration_chinese_clip import ChineseCLIPConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__)
|
| 47 |
+
|
| 48 |
+
_CHECKPOINT_FOR_DOC = "OFA-Sys/chinese-clip-vit-base-patch16"
|
| 49 |
+
_CONFIG_FOR_DOC = "ChineseCLIPConfig"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# https://sachinruk.github.io/blog/pytorch/pytorch%20lightning/loss%20function/gpu/2021/03/07/CLIP.html
|
| 53 |
+
# Copied from transformers.models.clip.modeling_clip.contrastive_loss
|
| 54 |
+
def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
|
| 55 |
+
return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def chinese_clip_loss(similarity: torch.Tensor) -> torch.Tensor:
|
| 59 |
+
caption_loss = contrastive_loss(similarity)
|
| 60 |
+
image_loss = contrastive_loss(similarity.t())
|
| 61 |
+
return (caption_loss + image_loss) / 2.0
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@dataclass
|
| 65 |
+
class ChineseCLIPOutput(ModelOutput):
|
| 66 |
+
"""
|
| 67 |
+
Args:
|
| 68 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
| 69 |
+
Contrastive loss for image-text similarity.
|
| 70 |
+
logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
|
| 71 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
| 72 |
+
similarity scores.
|
| 73 |
+
logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
|
| 74 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
| 75 |
+
similarity scores.
|
| 76 |
+
text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 77 |
+
The text embeddings obtained by applying the projection layer to the pooled output of
|
| 78 |
+
[`ChineseCLIPTextModel`].
|
| 79 |
+
image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 80 |
+
The image embeddings obtained by applying the projection layer to the pooled output of
|
| 81 |
+
[`ChineseCLIPVisionModel`].
|
| 82 |
+
text_model_output(`BaseModelOutputWithPoolingAndCrossAttentions`):
|
| 83 |
+
The output of the [`ChineseCLIPTextModel`].
|
| 84 |
+
vision_model_output(`BaseModelOutputWithPoolingAndCrossAttentions`):
|
| 85 |
+
The output of the [`ChineseCLIPVisionModel`].
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
loss: Optional[torch.FloatTensor] = None
|
| 89 |
+
logits_per_image: torch.FloatTensor = None
|
| 90 |
+
logits_per_text: torch.FloatTensor = None
|
| 91 |
+
text_embeds: torch.FloatTensor = None
|
| 92 |
+
image_embeds: torch.FloatTensor = None
|
| 93 |
+
text_model_output: BaseModelOutputWithPoolingAndCrossAttentions = None
|
| 94 |
+
vision_model_output: BaseModelOutputWithPoolingAndCrossAttentions = None
|
| 95 |
+
|
| 96 |
+
def to_tuple(self) -> Tuple[Any]:
|
| 97 |
+
return tuple(
|
| 98 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
| 99 |
+
for k in self.keys()
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# Copied from transformers.models.bert.modeling_bert.BertEmbeddings with Bert->ChineseCLIPText
|
| 104 |
+
class ChineseCLIPTextEmbeddings(nn.Module):
|
| 105 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 106 |
+
|
| 107 |
+
def __init__(self, config):
|
| 108 |
+
super().__init__()
|
| 109 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 110 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 111 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
| 112 |
+
|
| 113 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 114 |
+
# any TensorFlow checkpoint file
|
| 115 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 116 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 117 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 118 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 119 |
+
self.register_buffer(
|
| 120 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 121 |
+
)
|
| 122 |
+
self.register_buffer(
|
| 123 |
+
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
def forward(
|
| 127 |
+
self,
|
| 128 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 129 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 130 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 131 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 132 |
+
past_key_values_length: int = 0,
|
| 133 |
+
) -> torch.Tensor:
|
| 134 |
+
if input_ids is not None:
|
| 135 |
+
input_shape = input_ids.size()
|
| 136 |
+
else:
|
| 137 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 138 |
+
|
| 139 |
+
seq_length = input_shape[1]
|
| 140 |
+
|
| 141 |
+
if position_ids is None:
|
| 142 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
| 143 |
+
|
| 144 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
| 145 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
| 146 |
+
# issue #5664
|
| 147 |
+
if token_type_ids is None:
|
| 148 |
+
if hasattr(self, "token_type_ids"):
|
| 149 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
| 150 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
| 151 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 152 |
+
else:
|
| 153 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 154 |
+
|
| 155 |
+
if inputs_embeds is None:
|
| 156 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 157 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 158 |
+
|
| 159 |
+
embeddings = inputs_embeds + token_type_embeddings
|
| 160 |
+
if self.position_embedding_type == "absolute":
|
| 161 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 162 |
+
embeddings += position_embeddings
|
| 163 |
+
embeddings = self.LayerNorm(embeddings)
|
| 164 |
+
embeddings = self.dropout(embeddings)
|
| 165 |
+
return embeddings
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPVisionEmbeddings with CLIP->ChineseCLIP
|
| 169 |
+
class ChineseCLIPVisionEmbeddings(nn.Module):
|
| 170 |
+
def __init__(self, config: ChineseCLIPVisionConfig):
|
| 171 |
+
super().__init__()
|
| 172 |
+
self.config = config
|
| 173 |
+
self.embed_dim = config.hidden_size
|
| 174 |
+
self.image_size = config.image_size
|
| 175 |
+
self.patch_size = config.patch_size
|
| 176 |
+
|
| 177 |
+
self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
|
| 178 |
+
|
| 179 |
+
self.patch_embedding = nn.Conv2d(
|
| 180 |
+
in_channels=config.num_channels,
|
| 181 |
+
out_channels=self.embed_dim,
|
| 182 |
+
kernel_size=self.patch_size,
|
| 183 |
+
stride=self.patch_size,
|
| 184 |
+
bias=False,
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
| 188 |
+
self.num_positions = self.num_patches + 1
|
| 189 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
| 190 |
+
self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
|
| 191 |
+
|
| 192 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 193 |
+
"""
|
| 194 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
|
| 195 |
+
images. This method is also adapted to support torch.jit tracing.
|
| 196 |
+
|
| 197 |
+
Adapted from:
|
| 198 |
+
- https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
|
| 199 |
+
- https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
|
| 200 |
+
"""
|
| 201 |
+
|
| 202 |
+
num_patches = embeddings.shape[1] - 1
|
| 203 |
+
position_embedding = self.position_embedding.weight.unsqueeze(0)
|
| 204 |
+
num_positions = position_embedding.shape[1] - 1
|
| 205 |
+
|
| 206 |
+
# always interpolate when tracing to ensure the exported model works for dynamic input shapes
|
| 207 |
+
if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
|
| 208 |
+
return self.position_embedding(self.position_ids)
|
| 209 |
+
|
| 210 |
+
class_pos_embed = position_embedding[:, :1]
|
| 211 |
+
patch_pos_embed = position_embedding[:, 1:]
|
| 212 |
+
|
| 213 |
+
dim = embeddings.shape[-1]
|
| 214 |
+
|
| 215 |
+
new_height = height // self.patch_size
|
| 216 |
+
new_width = width // self.patch_size
|
| 217 |
+
|
| 218 |
+
sqrt_num_positions = torch_int(num_positions**0.5)
|
| 219 |
+
patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
|
| 220 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 221 |
+
|
| 222 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 223 |
+
patch_pos_embed,
|
| 224 |
+
size=(new_height, new_width),
|
| 225 |
+
mode="bicubic",
|
| 226 |
+
align_corners=False,
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 230 |
+
|
| 231 |
+
return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
|
| 232 |
+
|
| 233 |
+
def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding=False) -> torch.Tensor:
|
| 234 |
+
batch_size, _, height, width = pixel_values.shape
|
| 235 |
+
if not interpolate_pos_encoding and (height != self.image_size or width != self.image_size):
|
| 236 |
+
raise ValueError(
|
| 237 |
+
f"Input image size ({height}*{width}) doesn't match model" f" ({self.image_size}*{self.image_size})."
|
| 238 |
+
)
|
| 239 |
+
target_dtype = self.patch_embedding.weight.dtype
|
| 240 |
+
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
|
| 241 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
| 242 |
+
|
| 243 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1)
|
| 244 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
| 245 |
+
if interpolate_pos_encoding:
|
| 246 |
+
embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
|
| 247 |
+
else:
|
| 248 |
+
embeddings = embeddings + self.position_embedding(self.position_ids)
|
| 249 |
+
return embeddings
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->ChineseCLIPText
|
| 253 |
+
class ChineseCLIPTextSelfAttention(nn.Module):
|
| 254 |
+
def __init__(self, config, position_embedding_type=None):
|
| 255 |
+
super().__init__()
|
| 256 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 257 |
+
raise ValueError(
|
| 258 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 259 |
+
f"heads ({config.num_attention_heads})"
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
self.num_attention_heads = config.num_attention_heads
|
| 263 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 264 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 265 |
+
|
| 266 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 267 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 268 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 269 |
+
|
| 270 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 271 |
+
self.position_embedding_type = position_embedding_type or getattr(
|
| 272 |
+
config, "position_embedding_type", "absolute"
|
| 273 |
+
)
|
| 274 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 275 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 276 |
+
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
|
| 277 |
+
|
| 278 |
+
self.is_decoder = config.is_decoder
|
| 279 |
+
|
| 280 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 281 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 282 |
+
x = x.view(new_x_shape)
|
| 283 |
+
return x.permute(0, 2, 1, 3)
|
| 284 |
+
|
| 285 |
+
def forward(
|
| 286 |
+
self,
|
| 287 |
+
hidden_states: torch.Tensor,
|
| 288 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 289 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 290 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 291 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 292 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 293 |
+
output_attentions: Optional[bool] = False,
|
| 294 |
+
) -> Tuple[torch.Tensor]:
|
| 295 |
+
mixed_query_layer = self.query(hidden_states)
|
| 296 |
+
|
| 297 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 298 |
+
# and values come from an encoder; the attention mask needs to be
|
| 299 |
+
# such that the encoder's padding tokens are not attended to.
|
| 300 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 301 |
+
|
| 302 |
+
if is_cross_attention and past_key_value is not None:
|
| 303 |
+
# reuse k,v, cross_attentions
|
| 304 |
+
key_layer = past_key_value[0]
|
| 305 |
+
value_layer = past_key_value[1]
|
| 306 |
+
attention_mask = encoder_attention_mask
|
| 307 |
+
elif is_cross_attention:
|
| 308 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
| 309 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
| 310 |
+
attention_mask = encoder_attention_mask
|
| 311 |
+
elif past_key_value is not None:
|
| 312 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 313 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 314 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
| 315 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
| 316 |
+
else:
|
| 317 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 318 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 319 |
+
|
| 320 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 321 |
+
|
| 322 |
+
use_cache = past_key_value is not None
|
| 323 |
+
if self.is_decoder:
|
| 324 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 325 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 326 |
+
# key/value_states (first "if" case)
|
| 327 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 328 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 329 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 330 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 331 |
+
past_key_value = (key_layer, value_layer)
|
| 332 |
+
|
| 333 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 334 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 335 |
+
|
| 336 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 337 |
+
query_length, key_length = query_layer.shape[2], key_layer.shape[2]
|
| 338 |
+
if use_cache:
|
| 339 |
+
position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
|
| 340 |
+
-1, 1
|
| 341 |
+
)
|
| 342 |
+
else:
|
| 343 |
+
position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
|
| 344 |
+
position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
|
| 345 |
+
distance = position_ids_l - position_ids_r
|
| 346 |
+
|
| 347 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
| 348 |
+
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
|
| 349 |
+
|
| 350 |
+
if self.position_embedding_type == "relative_key":
|
| 351 |
+
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 352 |
+
attention_scores = attention_scores + relative_position_scores
|
| 353 |
+
elif self.position_embedding_type == "relative_key_query":
|
| 354 |
+
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 355 |
+
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
| 356 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
| 357 |
+
|
| 358 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 359 |
+
if attention_mask is not None:
|
| 360 |
+
# Apply the attention mask is (precomputed for all layers in ChineseCLIPTextModel forward() function)
|
| 361 |
+
attention_scores = attention_scores + attention_mask
|
| 362 |
+
|
| 363 |
+
# Normalize the attention scores to probabilities.
|
| 364 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 365 |
+
|
| 366 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 367 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 368 |
+
attention_probs = self.dropout(attention_probs)
|
| 369 |
+
|
| 370 |
+
# Mask heads if we want to
|
| 371 |
+
if head_mask is not None:
|
| 372 |
+
attention_probs = attention_probs * head_mask
|
| 373 |
+
|
| 374 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 375 |
+
|
| 376 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 377 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 378 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 379 |
+
|
| 380 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 381 |
+
|
| 382 |
+
if self.is_decoder:
|
| 383 |
+
outputs = outputs + (past_key_value,)
|
| 384 |
+
return outputs
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->ChineseCLIPText
|
| 388 |
+
class ChineseCLIPTextSelfOutput(nn.Module):
|
| 389 |
+
def __init__(self, config):
|
| 390 |
+
super().__init__()
|
| 391 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 392 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 393 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 394 |
+
|
| 395 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 396 |
+
hidden_states = self.dense(hidden_states)
|
| 397 |
+
hidden_states = self.dropout(hidden_states)
|
| 398 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 399 |
+
return hidden_states
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
CHINESE_CLIP_TEXT_SELF_ATTENTION_CLASSES = {
|
| 403 |
+
"eager": ChineseCLIPTextSelfAttention,
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
# Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->ChineseCLIPText,BERT->CHINESE_CLIP_TEXT
|
| 408 |
+
class ChineseCLIPTextAttention(nn.Module):
|
| 409 |
+
def __init__(self, config, position_embedding_type=None):
|
| 410 |
+
super().__init__()
|
| 411 |
+
self.self = CHINESE_CLIP_TEXT_SELF_ATTENTION_CLASSES[config._attn_implementation](
|
| 412 |
+
config, position_embedding_type=position_embedding_type
|
| 413 |
+
)
|
| 414 |
+
self.output = ChineseCLIPTextSelfOutput(config)
|
| 415 |
+
self.pruned_heads = set()
|
| 416 |
+
|
| 417 |
+
def prune_heads(self, heads):
|
| 418 |
+
if len(heads) == 0:
|
| 419 |
+
return
|
| 420 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 421 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
# Prune linear layers
|
| 425 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
| 426 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
| 427 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
| 428 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 429 |
+
|
| 430 |
+
# Update hyper params and store pruned heads
|
| 431 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
| 432 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
| 433 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 434 |
+
|
| 435 |
+
def forward(
|
| 436 |
+
self,
|
| 437 |
+
hidden_states: torch.Tensor,
|
| 438 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 439 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 440 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 441 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 442 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 443 |
+
output_attentions: Optional[bool] = False,
|
| 444 |
+
) -> Tuple[torch.Tensor]:
|
| 445 |
+
self_outputs = self.self(
|
| 446 |
+
hidden_states,
|
| 447 |
+
attention_mask,
|
| 448 |
+
head_mask,
|
| 449 |
+
encoder_hidden_states,
|
| 450 |
+
encoder_attention_mask,
|
| 451 |
+
past_key_value,
|
| 452 |
+
output_attentions,
|
| 453 |
+
)
|
| 454 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 455 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 456 |
+
return outputs
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
class ChineseCLIPVisionAttention(nn.Module):
|
| 460 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 461 |
+
|
| 462 |
+
def __init__(self, config):
|
| 463 |
+
super().__init__()
|
| 464 |
+
self.config = config
|
| 465 |
+
self.embed_dim = config.hidden_size
|
| 466 |
+
self.num_heads = config.num_attention_heads
|
| 467 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 468 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 469 |
+
raise ValueError(
|
| 470 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 471 |
+
f" {self.num_heads})."
|
| 472 |
+
)
|
| 473 |
+
self.scale = self.head_dim**-0.5
|
| 474 |
+
self.dropout = config.attention_dropout
|
| 475 |
+
|
| 476 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 477 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 478 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 479 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 480 |
+
|
| 481 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 482 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 483 |
+
|
| 484 |
+
def forward(
|
| 485 |
+
self,
|
| 486 |
+
hidden_states: torch.Tensor,
|
| 487 |
+
output_attentions: Optional[bool] = False,
|
| 488 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 489 |
+
"""Input shape: Batch x Time x Channel"""
|
| 490 |
+
|
| 491 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
| 492 |
+
|
| 493 |
+
# get query proj
|
| 494 |
+
query_states = self.q_proj(hidden_states) * self.scale
|
| 495 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 496 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 497 |
+
|
| 498 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 499 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
| 500 |
+
key_states = key_states.view(*proj_shape)
|
| 501 |
+
value_states = value_states.view(*proj_shape)
|
| 502 |
+
|
| 503 |
+
src_len = key_states.size(1)
|
| 504 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 505 |
+
|
| 506 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
| 507 |
+
raise ValueError(
|
| 508 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 509 |
+
f" {attn_weights.size()}"
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 513 |
+
|
| 514 |
+
if output_attentions:
|
| 515 |
+
# this operation is a bit akward, but it's required to
|
| 516 |
+
# make sure that attn_weights keeps its gradient.
|
| 517 |
+
# In order to do so, attn_weights have to reshaped
|
| 518 |
+
# twice and have to be reused in the following
|
| 519 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 520 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
| 521 |
+
else:
|
| 522 |
+
attn_weights_reshaped = None
|
| 523 |
+
|
| 524 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 525 |
+
|
| 526 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
| 527 |
+
|
| 528 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 529 |
+
raise ValueError(
|
| 530 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 531 |
+
f" {attn_output.size()}"
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
| 535 |
+
attn_output = attn_output.transpose(1, 2)
|
| 536 |
+
attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
|
| 537 |
+
|
| 538 |
+
attn_output = self.out_proj(attn_output)
|
| 539 |
+
|
| 540 |
+
return attn_output, attn_weights_reshaped
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->ChineseCLIPText
|
| 544 |
+
class ChineseCLIPTextIntermediate(nn.Module):
|
| 545 |
+
def __init__(self, config):
|
| 546 |
+
super().__init__()
|
| 547 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 548 |
+
if isinstance(config.hidden_act, str):
|
| 549 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 550 |
+
else:
|
| 551 |
+
self.intermediate_act_fn = config.hidden_act
|
| 552 |
+
|
| 553 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 554 |
+
hidden_states = self.dense(hidden_states)
|
| 555 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 556 |
+
return hidden_states
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->ChineseCLIPText
|
| 560 |
+
class ChineseCLIPTextOutput(nn.Module):
|
| 561 |
+
def __init__(self, config):
|
| 562 |
+
super().__init__()
|
| 563 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 564 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 565 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 566 |
+
|
| 567 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 568 |
+
hidden_states = self.dense(hidden_states)
|
| 569 |
+
hidden_states = self.dropout(hidden_states)
|
| 570 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 571 |
+
return hidden_states
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->ChineseCLIPVision
|
| 575 |
+
class ChineseCLIPVisionMLP(nn.Module):
|
| 576 |
+
def __init__(self, config):
|
| 577 |
+
super().__init__()
|
| 578 |
+
self.config = config
|
| 579 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 580 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 581 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 582 |
+
|
| 583 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 584 |
+
hidden_states = self.fc1(hidden_states)
|
| 585 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 586 |
+
hidden_states = self.fc2(hidden_states)
|
| 587 |
+
return hidden_states
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
# Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->ChineseCLIPText
|
| 591 |
+
class ChineseCLIPTextLayer(nn.Module):
|
| 592 |
+
def __init__(self, config):
|
| 593 |
+
super().__init__()
|
| 594 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 595 |
+
self.seq_len_dim = 1
|
| 596 |
+
self.attention = ChineseCLIPTextAttention(config)
|
| 597 |
+
self.is_decoder = config.is_decoder
|
| 598 |
+
self.add_cross_attention = config.add_cross_attention
|
| 599 |
+
if self.add_cross_attention:
|
| 600 |
+
if not self.is_decoder:
|
| 601 |
+
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
|
| 602 |
+
self.crossattention = ChineseCLIPTextAttention(config, position_embedding_type="absolute")
|
| 603 |
+
self.intermediate = ChineseCLIPTextIntermediate(config)
|
| 604 |
+
self.output = ChineseCLIPTextOutput(config)
|
| 605 |
+
|
| 606 |
+
def forward(
|
| 607 |
+
self,
|
| 608 |
+
hidden_states: torch.Tensor,
|
| 609 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 610 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 611 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 612 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 613 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 614 |
+
output_attentions: Optional[bool] = False,
|
| 615 |
+
) -> Tuple[torch.Tensor]:
|
| 616 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 617 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 618 |
+
self_attention_outputs = self.attention(
|
| 619 |
+
hidden_states,
|
| 620 |
+
attention_mask,
|
| 621 |
+
head_mask,
|
| 622 |
+
output_attentions=output_attentions,
|
| 623 |
+
past_key_value=self_attn_past_key_value,
|
| 624 |
+
)
|
| 625 |
+
attention_output = self_attention_outputs[0]
|
| 626 |
+
|
| 627 |
+
# if decoder, the last output is tuple of self-attn cache
|
| 628 |
+
if self.is_decoder:
|
| 629 |
+
outputs = self_attention_outputs[1:-1]
|
| 630 |
+
present_key_value = self_attention_outputs[-1]
|
| 631 |
+
else:
|
| 632 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 633 |
+
|
| 634 |
+
cross_attn_present_key_value = None
|
| 635 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
| 636 |
+
if not hasattr(self, "crossattention"):
|
| 637 |
+
raise ValueError(
|
| 638 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
| 639 |
+
" by setting `config.add_cross_attention=True`"
|
| 640 |
+
)
|
| 641 |
+
|
| 642 |
+
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
|
| 643 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 644 |
+
cross_attention_outputs = self.crossattention(
|
| 645 |
+
attention_output,
|
| 646 |
+
attention_mask,
|
| 647 |
+
head_mask,
|
| 648 |
+
encoder_hidden_states,
|
| 649 |
+
encoder_attention_mask,
|
| 650 |
+
cross_attn_past_key_value,
|
| 651 |
+
output_attentions,
|
| 652 |
+
)
|
| 653 |
+
attention_output = cross_attention_outputs[0]
|
| 654 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
| 655 |
+
|
| 656 |
+
# add cross-attn cache to positions 3,4 of present_key_value tuple
|
| 657 |
+
cross_attn_present_key_value = cross_attention_outputs[-1]
|
| 658 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 659 |
+
|
| 660 |
+
layer_output = apply_chunking_to_forward(
|
| 661 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 662 |
+
)
|
| 663 |
+
outputs = (layer_output,) + outputs
|
| 664 |
+
|
| 665 |
+
# if decoder, return the attn key/values as the last output
|
| 666 |
+
if self.is_decoder:
|
| 667 |
+
outputs = outputs + (present_key_value,)
|
| 668 |
+
|
| 669 |
+
return outputs
|
| 670 |
+
|
| 671 |
+
def feed_forward_chunk(self, attention_output):
|
| 672 |
+
intermediate_output = self.intermediate(attention_output)
|
| 673 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 674 |
+
return layer_output
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
class ChineseCLIPVisionLayer(nn.Module):
|
| 678 |
+
def __init__(self, config: ChineseCLIPConfig):
|
| 679 |
+
super().__init__()
|
| 680 |
+
self.embed_dim = config.hidden_size
|
| 681 |
+
self.self_attn = ChineseCLIPVisionAttention(config)
|
| 682 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 683 |
+
self.mlp = ChineseCLIPVisionMLP(config)
|
| 684 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 685 |
+
|
| 686 |
+
def forward(
|
| 687 |
+
self,
|
| 688 |
+
hidden_states: torch.Tensor,
|
| 689 |
+
output_attentions: Optional[bool] = False,
|
| 690 |
+
) -> Tuple[torch.FloatTensor]:
|
| 691 |
+
"""
|
| 692 |
+
Args:
|
| 693 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 694 |
+
output_attentions (`bool`, *optional*):
|
| 695 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 696 |
+
returned tensors for more detail.
|
| 697 |
+
"""
|
| 698 |
+
residual = hidden_states
|
| 699 |
+
|
| 700 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 701 |
+
hidden_states, attn_weights = self.self_attn(
|
| 702 |
+
hidden_states=hidden_states,
|
| 703 |
+
output_attentions=output_attentions,
|
| 704 |
+
)
|
| 705 |
+
hidden_states = residual + hidden_states
|
| 706 |
+
|
| 707 |
+
residual = hidden_states
|
| 708 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 709 |
+
hidden_states = self.mlp(hidden_states)
|
| 710 |
+
hidden_states = residual + hidden_states
|
| 711 |
+
|
| 712 |
+
outputs = (hidden_states,)
|
| 713 |
+
|
| 714 |
+
if output_attentions:
|
| 715 |
+
outputs += (attn_weights,)
|
| 716 |
+
|
| 717 |
+
return outputs
|
| 718 |
+
|
| 719 |
+
|
| 720 |
+
# Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->ChineseCLIPText
|
| 721 |
+
class ChineseCLIPTextPooler(nn.Module):
|
| 722 |
+
def __init__(self, config):
|
| 723 |
+
super().__init__()
|
| 724 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 725 |
+
self.activation = nn.Tanh()
|
| 726 |
+
|
| 727 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 728 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 729 |
+
# to the first token.
|
| 730 |
+
first_token_tensor = hidden_states[:, 0]
|
| 731 |
+
pooled_output = self.dense(first_token_tensor)
|
| 732 |
+
pooled_output = self.activation(pooled_output)
|
| 733 |
+
return pooled_output
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
class ChineseCLIPPreTrainedModel(PreTrainedModel):
|
| 737 |
+
"""
|
| 738 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 739 |
+
models.
|
| 740 |
+
"""
|
| 741 |
+
|
| 742 |
+
config_class = ChineseCLIPConfig
|
| 743 |
+
base_model_prefix = "chinese_clip"
|
| 744 |
+
supports_gradient_checkpointing = True
|
| 745 |
+
|
| 746 |
+
def _init_weights(self, module):
|
| 747 |
+
"""Initialize the weights"""
|
| 748 |
+
factor = self.config.initializer_factor
|
| 749 |
+
if isinstance(module, ChineseCLIPVisionEmbeddings):
|
| 750 |
+
factor = self.config.initializer_factor
|
| 751 |
+
nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
|
| 752 |
+
nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
|
| 753 |
+
nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
|
| 754 |
+
elif isinstance(module, ChineseCLIPTextEmbeddings):
|
| 755 |
+
nn.init.normal_(module.word_embeddings.weight, mean=0.0, std=self.config.initializer_range)
|
| 756 |
+
nn.init.normal_(module.position_embeddings.weight, mean=0.0, std=self.config.initializer_range)
|
| 757 |
+
nn.init.normal_(module.token_type_embeddings.weight, mean=0.0, std=self.config.initializer_range)
|
| 758 |
+
for embedding in [module.word_embeddings, module.position_embeddings, module.token_type_embeddings]:
|
| 759 |
+
if embedding.padding_idx is not None:
|
| 760 |
+
embedding.weight.data[embedding.padding_idx].zero_()
|
| 761 |
+
elif isinstance(module, ChineseCLIPVisionAttention):
|
| 762 |
+
factor = self.config.initializer_factor
|
| 763 |
+
in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
| 764 |
+
out_proj_std = (module.embed_dim**-0.5) * factor
|
| 765 |
+
nn.init.normal_(module.q_proj.weight, std=in_proj_std)
|
| 766 |
+
nn.init.normal_(module.k_proj.weight, std=in_proj_std)
|
| 767 |
+
nn.init.normal_(module.v_proj.weight, std=in_proj_std)
|
| 768 |
+
nn.init.normal_(module.out_proj.weight, std=out_proj_std)
|
| 769 |
+
elif isinstance(module, ChineseCLIPVisionMLP):
|
| 770 |
+
factor = self.config.initializer_factor
|
| 771 |
+
in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
| 772 |
+
fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
|
| 773 |
+
nn.init.normal_(module.fc1.weight, std=fc_std)
|
| 774 |
+
nn.init.normal_(module.fc2.weight, std=in_proj_std)
|
| 775 |
+
elif isinstance(module, ChineseCLIPModel):
|
| 776 |
+
nn.init.normal_(
|
| 777 |
+
module.text_projection.weight,
|
| 778 |
+
std=module.text_embed_dim**-0.5 * self.config.initializer_factor,
|
| 779 |
+
)
|
| 780 |
+
nn.init.normal_(
|
| 781 |
+
module.visual_projection.weight,
|
| 782 |
+
std=module.vision_embed_dim**-0.5 * self.config.initializer_factor,
|
| 783 |
+
)
|
| 784 |
+
|
| 785 |
+
if isinstance(module, nn.LayerNorm):
|
| 786 |
+
module.bias.data.zero_()
|
| 787 |
+
module.weight.data.fill_(1.0)
|
| 788 |
+
if isinstance(module, nn.Linear):
|
| 789 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 790 |
+
if module.bias is not None:
|
| 791 |
+
module.bias.data.zero_()
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
CHINESE_CLIP_START_DOCSTRING = r"""
|
| 795 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 796 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 797 |
+
behavior.
|
| 798 |
+
|
| 799 |
+
Parameters:
|
| 800 |
+
config ([`ChineseCLIPConfig`]): Model configuration class with all the parameters of the model.
|
| 801 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 802 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 803 |
+
"""
|
| 804 |
+
|
| 805 |
+
CHINESE_CLIP_TEXT_INPUTS_DOCSTRING = r"""
|
| 806 |
+
Args:
|
| 807 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 808 |
+
Indices of input sequence tokens in the vocabulary.
|
| 809 |
+
|
| 810 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 811 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 812 |
+
|
| 813 |
+
[What are input IDs?](../glossary#input-ids)
|
| 814 |
+
attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 815 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 816 |
+
|
| 817 |
+
- 1 for tokens that are **not masked**,
|
| 818 |
+
- 0 for tokens that are **masked**.
|
| 819 |
+
|
| 820 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 821 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 822 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 823 |
+
1]`:
|
| 824 |
+
|
| 825 |
+
- 0 corresponds to a *sentence A* token,
|
| 826 |
+
- 1 corresponds to a *sentence B* token.
|
| 827 |
+
|
| 828 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 829 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 830 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 831 |
+
config.max_position_embeddings - 1]`.
|
| 832 |
+
|
| 833 |
+
[What are position IDs?](../glossary#position-ids)
|
| 834 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 835 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 836 |
+
|
| 837 |
+
- 1 indicates the head is **not masked**,
|
| 838 |
+
- 0 indicates the head is **masked**.
|
| 839 |
+
|
| 840 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 841 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 842 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 843 |
+
model's internal embedding lookup matrix.
|
| 844 |
+
output_attentions (`bool`, *optional*):
|
| 845 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 846 |
+
tensors for more detail.
|
| 847 |
+
output_hidden_states (`bool`, *optional*):
|
| 848 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 849 |
+
more detail.
|
| 850 |
+
interpolate_pos_encoding (`bool`, *optional*, defaults `False`):
|
| 851 |
+
Whether to interpolate the pre-trained position encodings.
|
| 852 |
+
return_dict (`bool`, *optional*):
|
| 853 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 854 |
+
"""
|
| 855 |
+
|
| 856 |
+
CHINESE_CLIP_VISION_INPUTS_DOCSTRING = r"""
|
| 857 |
+
Args:
|
| 858 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 859 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 860 |
+
[`AutoImageProcessor`]. See [`ChineseCLIPImageProcessor.__call__`] for details.
|
| 861 |
+
output_attentions (`bool`, *optional*):
|
| 862 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 863 |
+
tensors for more detail.
|
| 864 |
+
output_hidden_states (`bool`, *optional*):
|
| 865 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 866 |
+
more detail.
|
| 867 |
+
interpolate_pos_encoding (`bool`, *optional*, defaults `False`):
|
| 868 |
+
Whether to interpolate the pre-trained position encodings.
|
| 869 |
+
return_dict (`bool`, *optional*):
|
| 870 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 871 |
+
"""
|
| 872 |
+
|
| 873 |
+
CHINESE_CLIP_INPUTS_DOCSTRING = r"""
|
| 874 |
+
Args:
|
| 875 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 876 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 877 |
+
it.
|
| 878 |
+
|
| 879 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 880 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 881 |
+
|
| 882 |
+
[What are input IDs?](../glossary#input-ids)
|
| 883 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 884 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 885 |
+
|
| 886 |
+
- 1 for tokens that are **not masked**,
|
| 887 |
+
- 0 for tokens that are **masked**.
|
| 888 |
+
|
| 889 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 890 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 891 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 892 |
+
1]`:
|
| 893 |
+
|
| 894 |
+
- 0 corresponds to a *sentence A* token,
|
| 895 |
+
- 1 corresponds to a *sentence B* token.
|
| 896 |
+
|
| 897 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 898 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 899 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 900 |
+
config.max_position_embeddings - 1]`.
|
| 901 |
+
|
| 902 |
+
[What are position IDs?](../glossary#position-ids)
|
| 903 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 904 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 905 |
+
[`AutoImageProcessor`]. See [`ChineseCLIPImageProcessor.__call__`] for details.
|
| 906 |
+
return_loss (`bool`, *optional*):
|
| 907 |
+
Whether or not to return the contrastive loss.
|
| 908 |
+
output_attentions (`bool`, *optional*):
|
| 909 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 910 |
+
tensors for more detail.
|
| 911 |
+
output_hidden_states (`bool`, *optional*):
|
| 912 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 913 |
+
more detail.
|
| 914 |
+
return_dict (`bool`, *optional*):
|
| 915 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 916 |
+
"""
|
| 917 |
+
|
| 918 |
+
|
| 919 |
+
# Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->ChineseCLIPText
|
| 920 |
+
class ChineseCLIPTextEncoder(nn.Module):
|
| 921 |
+
def __init__(self, config):
|
| 922 |
+
super().__init__()
|
| 923 |
+
self.config = config
|
| 924 |
+
self.layer = nn.ModuleList([ChineseCLIPTextLayer(config) for _ in range(config.num_hidden_layers)])
|
| 925 |
+
self.gradient_checkpointing = False
|
| 926 |
+
|
| 927 |
+
def forward(
|
| 928 |
+
self,
|
| 929 |
+
hidden_states: torch.Tensor,
|
| 930 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 931 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 932 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 933 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 934 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 935 |
+
use_cache: Optional[bool] = None,
|
| 936 |
+
output_attentions: Optional[bool] = False,
|
| 937 |
+
output_hidden_states: Optional[bool] = False,
|
| 938 |
+
return_dict: Optional[bool] = True,
|
| 939 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
| 940 |
+
all_hidden_states = () if output_hidden_states else None
|
| 941 |
+
all_self_attentions = () if output_attentions else None
|
| 942 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
| 943 |
+
|
| 944 |
+
if self.gradient_checkpointing and self.training:
|
| 945 |
+
if use_cache:
|
| 946 |
+
logger.warning_once(
|
| 947 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 948 |
+
)
|
| 949 |
+
use_cache = False
|
| 950 |
+
|
| 951 |
+
next_decoder_cache = () if use_cache else None
|
| 952 |
+
for i, layer_module in enumerate(self.layer):
|
| 953 |
+
if output_hidden_states:
|
| 954 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 955 |
+
|
| 956 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 957 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
| 958 |
+
|
| 959 |
+
if self.gradient_checkpointing and self.training:
|
| 960 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 961 |
+
layer_module.__call__,
|
| 962 |
+
hidden_states,
|
| 963 |
+
attention_mask,
|
| 964 |
+
layer_head_mask,
|
| 965 |
+
encoder_hidden_states,
|
| 966 |
+
encoder_attention_mask,
|
| 967 |
+
past_key_value,
|
| 968 |
+
output_attentions,
|
| 969 |
+
)
|
| 970 |
+
else:
|
| 971 |
+
layer_outputs = layer_module(
|
| 972 |
+
hidden_states,
|
| 973 |
+
attention_mask,
|
| 974 |
+
layer_head_mask,
|
| 975 |
+
encoder_hidden_states,
|
| 976 |
+
encoder_attention_mask,
|
| 977 |
+
past_key_value,
|
| 978 |
+
output_attentions,
|
| 979 |
+
)
|
| 980 |
+
|
| 981 |
+
hidden_states = layer_outputs[0]
|
| 982 |
+
if use_cache:
|
| 983 |
+
next_decoder_cache += (layer_outputs[-1],)
|
| 984 |
+
if output_attentions:
|
| 985 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 986 |
+
if self.config.add_cross_attention:
|
| 987 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
| 988 |
+
|
| 989 |
+
if output_hidden_states:
|
| 990 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 991 |
+
|
| 992 |
+
if not return_dict:
|
| 993 |
+
return tuple(
|
| 994 |
+
v
|
| 995 |
+
for v in [
|
| 996 |
+
hidden_states,
|
| 997 |
+
next_decoder_cache,
|
| 998 |
+
all_hidden_states,
|
| 999 |
+
all_self_attentions,
|
| 1000 |
+
all_cross_attentions,
|
| 1001 |
+
]
|
| 1002 |
+
if v is not None
|
| 1003 |
+
)
|
| 1004 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 1005 |
+
last_hidden_state=hidden_states,
|
| 1006 |
+
past_key_values=next_decoder_cache,
|
| 1007 |
+
hidden_states=all_hidden_states,
|
| 1008 |
+
attentions=all_self_attentions,
|
| 1009 |
+
cross_attentions=all_cross_attentions,
|
| 1010 |
+
)
|
| 1011 |
+
|
| 1012 |
+
|
| 1013 |
+
class ChineseCLIPVisionEncoder(nn.Module):
|
| 1014 |
+
"""
|
| 1015 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 1016 |
+
[`ChineseCLIPVisionEncoderLayer`].
|
| 1017 |
+
|
| 1018 |
+
Args:
|
| 1019 |
+
config: ChineseCLIPConfig
|
| 1020 |
+
"""
|
| 1021 |
+
|
| 1022 |
+
def __init__(self, config: ChineseCLIPConfig):
|
| 1023 |
+
super().__init__()
|
| 1024 |
+
self.config = config
|
| 1025 |
+
self.layers = nn.ModuleList([ChineseCLIPVisionLayer(config) for _ in range(config.num_hidden_layers)])
|
| 1026 |
+
self.gradient_checkpointing = False
|
| 1027 |
+
|
| 1028 |
+
def forward(
|
| 1029 |
+
self,
|
| 1030 |
+
inputs_embeds,
|
| 1031 |
+
output_attentions: Optional[bool] = None,
|
| 1032 |
+
output_hidden_states: Optional[bool] = None,
|
| 1033 |
+
return_dict: Optional[bool] = None,
|
| 1034 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 1035 |
+
r"""
|
| 1036 |
+
Args:
|
| 1037 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 1038 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 1039 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 1040 |
+
than the model's internal embedding lookup matrix.
|
| 1041 |
+
output_attentions (`bool`, *optional*):
|
| 1042 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 1043 |
+
returned tensors for more detail.
|
| 1044 |
+
output_hidden_states (`bool`, *optional*):
|
| 1045 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 1046 |
+
for more detail.
|
| 1047 |
+
return_dict (`bool`, *optional*):
|
| 1048 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 1049 |
+
"""
|
| 1050 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1051 |
+
output_hidden_states = (
|
| 1052 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1053 |
+
)
|
| 1054 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1055 |
+
|
| 1056 |
+
encoder_states = () if output_hidden_states else None
|
| 1057 |
+
all_attentions = () if output_attentions else None
|
| 1058 |
+
|
| 1059 |
+
hidden_states = inputs_embeds
|
| 1060 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 1061 |
+
if output_hidden_states:
|
| 1062 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 1063 |
+
if self.gradient_checkpointing and self.training:
|
| 1064 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 1065 |
+
encoder_layer.__call__,
|
| 1066 |
+
hidden_states,
|
| 1067 |
+
output_attentions,
|
| 1068 |
+
)
|
| 1069 |
+
else:
|
| 1070 |
+
layer_outputs = encoder_layer(
|
| 1071 |
+
hidden_states,
|
| 1072 |
+
output_attentions=output_attentions,
|
| 1073 |
+
)
|
| 1074 |
+
|
| 1075 |
+
hidden_states = layer_outputs[0]
|
| 1076 |
+
|
| 1077 |
+
if output_attentions:
|
| 1078 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 1079 |
+
|
| 1080 |
+
if output_hidden_states:
|
| 1081 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 1082 |
+
|
| 1083 |
+
if not return_dict:
|
| 1084 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 1085 |
+
return BaseModelOutput(
|
| 1086 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 1087 |
+
)
|
| 1088 |
+
|
| 1089 |
+
|
| 1090 |
+
class ChineseCLIPVisionTransformer(nn.Module):
|
| 1091 |
+
def __init__(self, config: ChineseCLIPVisionConfig):
|
| 1092 |
+
super().__init__()
|
| 1093 |
+
self.config = config
|
| 1094 |
+
embed_dim = config.hidden_size
|
| 1095 |
+
|
| 1096 |
+
self.embeddings = ChineseCLIPVisionEmbeddings(config)
|
| 1097 |
+
self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 1098 |
+
self.encoder = ChineseCLIPVisionEncoder(config)
|
| 1099 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 1100 |
+
|
| 1101 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_VISION_INPUTS_DOCSTRING)
|
| 1102 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=ChineseCLIPVisionConfig)
|
| 1103 |
+
def forward(
|
| 1104 |
+
self,
|
| 1105 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1106 |
+
output_attentions: Optional[bool] = None,
|
| 1107 |
+
output_hidden_states: Optional[bool] = None,
|
| 1108 |
+
interpolate_pos_encoding: bool = False,
|
| 1109 |
+
return_dict: Optional[bool] = None,
|
| 1110 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 1111 |
+
r"""
|
| 1112 |
+
Returns:
|
| 1113 |
+
"""
|
| 1114 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1115 |
+
output_hidden_states = (
|
| 1116 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1117 |
+
)
|
| 1118 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1119 |
+
|
| 1120 |
+
if pixel_values is None:
|
| 1121 |
+
raise ValueError("You have to specify pixel_values")
|
| 1122 |
+
|
| 1123 |
+
hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
|
| 1124 |
+
hidden_states = self.pre_layrnorm(hidden_states)
|
| 1125 |
+
|
| 1126 |
+
encoder_outputs = self.encoder(
|
| 1127 |
+
inputs_embeds=hidden_states,
|
| 1128 |
+
output_attentions=output_attentions,
|
| 1129 |
+
output_hidden_states=output_hidden_states,
|
| 1130 |
+
return_dict=return_dict,
|
| 1131 |
+
)
|
| 1132 |
+
|
| 1133 |
+
last_hidden_state = encoder_outputs[0]
|
| 1134 |
+
pooled_output = last_hidden_state[:, 0, :]
|
| 1135 |
+
pooled_output = self.post_layernorm(pooled_output)
|
| 1136 |
+
|
| 1137 |
+
if not return_dict:
|
| 1138 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 1139 |
+
|
| 1140 |
+
return BaseModelOutputWithPooling(
|
| 1141 |
+
last_hidden_state=last_hidden_state,
|
| 1142 |
+
pooler_output=pooled_output,
|
| 1143 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 1144 |
+
attentions=encoder_outputs.attentions,
|
| 1145 |
+
)
|
| 1146 |
+
|
| 1147 |
+
|
| 1148 |
+
@add_start_docstrings(
|
| 1149 |
+
"The text model from CHINESE_CLIP without any head or projection on top.",
|
| 1150 |
+
CHINESE_CLIP_START_DOCSTRING,
|
| 1151 |
+
)
|
| 1152 |
+
class ChineseCLIPTextModel(ChineseCLIPPreTrainedModel):
|
| 1153 |
+
"""
|
| 1154 |
+
|
| 1155 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
| 1156 |
+
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
|
| 1157 |
+
all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
|
| 1158 |
+
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
|
| 1159 |
+
|
| 1160 |
+
To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
|
| 1161 |
+
to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
|
| 1162 |
+
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
|
| 1163 |
+
"""
|
| 1164 |
+
|
| 1165 |
+
config_class = ChineseCLIPTextConfig
|
| 1166 |
+
_no_split_modules = ["ChineseCLIPTextEmbeddings"]
|
| 1167 |
+
|
| 1168 |
+
def __init__(self, config, add_pooling_layer=True):
|
| 1169 |
+
super().__init__(config)
|
| 1170 |
+
self.config = config
|
| 1171 |
+
|
| 1172 |
+
self.embeddings = ChineseCLIPTextEmbeddings(config)
|
| 1173 |
+
self.encoder = ChineseCLIPTextEncoder(config)
|
| 1174 |
+
|
| 1175 |
+
self.pooler = ChineseCLIPTextPooler(config) if add_pooling_layer else None
|
| 1176 |
+
|
| 1177 |
+
# Initialize weights and apply final processing
|
| 1178 |
+
self.post_init()
|
| 1179 |
+
|
| 1180 |
+
def get_input_embeddings(self):
|
| 1181 |
+
return self.embeddings.word_embeddings
|
| 1182 |
+
|
| 1183 |
+
def set_input_embeddings(self, value):
|
| 1184 |
+
self.embeddings.word_embeddings = value
|
| 1185 |
+
|
| 1186 |
+
def _prune_heads(self, heads_to_prune):
|
| 1187 |
+
"""
|
| 1188 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 1189 |
+
class PreTrainedModel
|
| 1190 |
+
"""
|
| 1191 |
+
for layer, heads in heads_to_prune.items():
|
| 1192 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 1193 |
+
|
| 1194 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1195 |
+
@add_code_sample_docstrings(
|
| 1196 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1197 |
+
output_type=BaseModelOutputWithPoolingAndCrossAttentions,
|
| 1198 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1199 |
+
)
|
| 1200 |
+
def forward(
|
| 1201 |
+
self,
|
| 1202 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1203 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1204 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1205 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1206 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1207 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1208 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 1209 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 1210 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1211 |
+
use_cache: Optional[bool] = None,
|
| 1212 |
+
output_attentions: Optional[bool] = None,
|
| 1213 |
+
output_hidden_states: Optional[bool] = None,
|
| 1214 |
+
return_dict: Optional[bool] = None,
|
| 1215 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
|
| 1216 |
+
r"""
|
| 1217 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 1218 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 1219 |
+
the model is configured as a decoder.
|
| 1220 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1221 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 1222 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 1223 |
+
|
| 1224 |
+
- 1 for tokens that are **not masked**,
|
| 1225 |
+
- 0 for tokens that are **masked**.
|
| 1226 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
| 1227 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 1228 |
+
|
| 1229 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 1230 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 1231 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 1232 |
+
use_cache (`bool`, *optional*):
|
| 1233 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 1234 |
+
`past_key_values`).
|
| 1235 |
+
"""
|
| 1236 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1237 |
+
output_hidden_states = (
|
| 1238 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1239 |
+
)
|
| 1240 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1241 |
+
|
| 1242 |
+
if self.config.is_decoder:
|
| 1243 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1244 |
+
else:
|
| 1245 |
+
use_cache = False
|
| 1246 |
+
|
| 1247 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 1248 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 1249 |
+
elif input_ids is not None:
|
| 1250 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 1251 |
+
input_shape = input_ids.size()
|
| 1252 |
+
elif inputs_embeds is not None:
|
| 1253 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1254 |
+
else:
|
| 1255 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 1256 |
+
|
| 1257 |
+
batch_size, seq_length = input_shape
|
| 1258 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 1259 |
+
|
| 1260 |
+
# past_key_values_length
|
| 1261 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
| 1262 |
+
|
| 1263 |
+
if attention_mask is None:
|
| 1264 |
+
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
|
| 1265 |
+
|
| 1266 |
+
if token_type_ids is None:
|
| 1267 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
| 1268 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
| 1269 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
| 1270 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 1271 |
+
else:
|
| 1272 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 1273 |
+
|
| 1274 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
| 1275 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
| 1276 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
|
| 1277 |
+
|
| 1278 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
| 1279 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
| 1280 |
+
if self.config.is_decoder and encoder_hidden_states is not None:
|
| 1281 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
| 1282 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
| 1283 |
+
if encoder_attention_mask is None:
|
| 1284 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
| 1285 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
| 1286 |
+
else:
|
| 1287 |
+
encoder_extended_attention_mask = None
|
| 1288 |
+
|
| 1289 |
+
# Prepare head mask if needed
|
| 1290 |
+
# 1.0 in head_mask indicate we keep the head
|
| 1291 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 1292 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 1293 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 1294 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 1295 |
+
|
| 1296 |
+
embedding_output = self.embeddings(
|
| 1297 |
+
input_ids=input_ids,
|
| 1298 |
+
position_ids=position_ids,
|
| 1299 |
+
token_type_ids=token_type_ids,
|
| 1300 |
+
inputs_embeds=inputs_embeds,
|
| 1301 |
+
past_key_values_length=past_key_values_length,
|
| 1302 |
+
)
|
| 1303 |
+
encoder_outputs = self.encoder(
|
| 1304 |
+
embedding_output,
|
| 1305 |
+
attention_mask=extended_attention_mask,
|
| 1306 |
+
head_mask=head_mask,
|
| 1307 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1308 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
| 1309 |
+
past_key_values=past_key_values,
|
| 1310 |
+
use_cache=use_cache,
|
| 1311 |
+
output_attentions=output_attentions,
|
| 1312 |
+
output_hidden_states=output_hidden_states,
|
| 1313 |
+
return_dict=return_dict,
|
| 1314 |
+
)
|
| 1315 |
+
sequence_output = encoder_outputs[0]
|
| 1316 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 1317 |
+
|
| 1318 |
+
if not return_dict:
|
| 1319 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
| 1320 |
+
|
| 1321 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
| 1322 |
+
last_hidden_state=sequence_output,
|
| 1323 |
+
pooler_output=pooled_output,
|
| 1324 |
+
past_key_values=encoder_outputs.past_key_values,
|
| 1325 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 1326 |
+
attentions=encoder_outputs.attentions,
|
| 1327 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
| 1328 |
+
)
|
| 1329 |
+
|
| 1330 |
+
|
| 1331 |
+
@add_start_docstrings(
|
| 1332 |
+
"""The vision model from CHINESE_CLIP without any head or projection on top.""",
|
| 1333 |
+
CHINESE_CLIP_START_DOCSTRING,
|
| 1334 |
+
)
|
| 1335 |
+
class ChineseCLIPVisionModel(ChineseCLIPPreTrainedModel):
|
| 1336 |
+
config_class = ChineseCLIPVisionConfig
|
| 1337 |
+
main_input_name = "pixel_values"
|
| 1338 |
+
_no_split_modules = ["ChineseCLIPVisionEmbeddings", "ChineseCLIPVisionAttention"]
|
| 1339 |
+
|
| 1340 |
+
def __init__(self, config: ChineseCLIPVisionConfig):
|
| 1341 |
+
super().__init__(config)
|
| 1342 |
+
self.vision_model = ChineseCLIPVisionTransformer(config)
|
| 1343 |
+
# Initialize weights and apply final processing
|
| 1344 |
+
self.post_init()
|
| 1345 |
+
|
| 1346 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1347 |
+
return self.vision_model.embeddings.patch_embedding
|
| 1348 |
+
|
| 1349 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_VISION_INPUTS_DOCSTRING)
|
| 1350 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=ChineseCLIPVisionConfig)
|
| 1351 |
+
def forward(
|
| 1352 |
+
self,
|
| 1353 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1354 |
+
output_attentions: Optional[bool] = None,
|
| 1355 |
+
output_hidden_states: Optional[bool] = None,
|
| 1356 |
+
interpolate_pos_encoding: bool = False,
|
| 1357 |
+
return_dict: Optional[bool] = None,
|
| 1358 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 1359 |
+
r"""
|
| 1360 |
+
Returns:
|
| 1361 |
+
|
| 1362 |
+
Examples:
|
| 1363 |
+
|
| 1364 |
+
```python
|
| 1365 |
+
>>> from PIL import Image
|
| 1366 |
+
>>> import requests
|
| 1367 |
+
>>> from transformers import CLIPProcessor, ChineseCLIPVisionModel
|
| 1368 |
+
|
| 1369 |
+
>>> model = ChineseCLIPVisionModel.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
| 1370 |
+
>>> processor = CLIPProcessor.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
| 1371 |
+
|
| 1372 |
+
>>> url = "https://clip-cn-beijing.oss-cn-beijing.aliyuncs.com/pokemon.jpeg"
|
| 1373 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1374 |
+
|
| 1375 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1376 |
+
|
| 1377 |
+
>>> outputs = model(**inputs)
|
| 1378 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 1379 |
+
>>> pooled_output = outputs.pooler_output # pooled CLS states
|
| 1380 |
+
```"""
|
| 1381 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1382 |
+
|
| 1383 |
+
return self.vision_model(
|
| 1384 |
+
pixel_values=pixel_values,
|
| 1385 |
+
output_attentions=output_attentions,
|
| 1386 |
+
output_hidden_states=output_hidden_states,
|
| 1387 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1388 |
+
return_dict=return_dict,
|
| 1389 |
+
)
|
| 1390 |
+
|
| 1391 |
+
|
| 1392 |
+
@add_start_docstrings(CHINESE_CLIP_START_DOCSTRING)
|
| 1393 |
+
class ChineseCLIPModel(ChineseCLIPPreTrainedModel):
|
| 1394 |
+
config_class = ChineseCLIPConfig
|
| 1395 |
+
|
| 1396 |
+
def __init__(self, config: ChineseCLIPConfig):
|
| 1397 |
+
super().__init__(config)
|
| 1398 |
+
|
| 1399 |
+
if not isinstance(config.text_config, ChineseCLIPTextConfig):
|
| 1400 |
+
raise TypeError(
|
| 1401 |
+
"config.text_config is expected to be of type ChineseCLIPTextConfig but is of type"
|
| 1402 |
+
f" {type(config.text_config)}."
|
| 1403 |
+
)
|
| 1404 |
+
|
| 1405 |
+
if not isinstance(config.vision_config, ChineseCLIPVisionConfig):
|
| 1406 |
+
raise TypeError(
|
| 1407 |
+
"config.vision_config is expected to be of type ChineseCLIPVisionConfig but is of type"
|
| 1408 |
+
f" {type(config.vision_config)}."
|
| 1409 |
+
)
|
| 1410 |
+
|
| 1411 |
+
text_config = config.text_config
|
| 1412 |
+
vision_config = config.vision_config
|
| 1413 |
+
|
| 1414 |
+
self.projection_dim = config.projection_dim
|
| 1415 |
+
self.text_embed_dim = text_config.hidden_size
|
| 1416 |
+
self.vision_embed_dim = vision_config.hidden_size
|
| 1417 |
+
|
| 1418 |
+
self.text_model = ChineseCLIPTextModel(text_config, add_pooling_layer=False)
|
| 1419 |
+
self.vision_model = ChineseCLIPVisionTransformer(vision_config)
|
| 1420 |
+
|
| 1421 |
+
self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
|
| 1422 |
+
self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
|
| 1423 |
+
self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
|
| 1424 |
+
|
| 1425 |
+
# Initialize weights and apply final processing
|
| 1426 |
+
self.post_init()
|
| 1427 |
+
|
| 1428 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_TEXT_INPUTS_DOCSTRING)
|
| 1429 |
+
def get_text_features(
|
| 1430 |
+
self,
|
| 1431 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1432 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1433 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1434 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1435 |
+
output_attentions: Optional[bool] = None,
|
| 1436 |
+
output_hidden_states: Optional[bool] = None,
|
| 1437 |
+
return_dict: Optional[bool] = None,
|
| 1438 |
+
) -> torch.FloatTensor:
|
| 1439 |
+
r"""
|
| 1440 |
+
Returns:
|
| 1441 |
+
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
|
| 1442 |
+
applying the projection layer to the final [CLS] hidden state of Text-Transformer.
|
| 1443 |
+
|
| 1444 |
+
Examples:
|
| 1445 |
+
|
| 1446 |
+
```python
|
| 1447 |
+
>>> from transformers import AutoTokenizer, ChineseCLIPModel
|
| 1448 |
+
|
| 1449 |
+
>>> model = ChineseCLIPModel.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
| 1450 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
| 1451 |
+
|
| 1452 |
+
>>> inputs = tokenizer(["杰尼龟", "妙蛙种子", "小火龙", "皮卡丘"], padding=True, return_tensors="pt")
|
| 1453 |
+
>>> text_features = model.get_text_features(**inputs)
|
| 1454 |
+
>>> text_features = text_features / text_features.norm(p=2, dim=-1, keepdim=True)
|
| 1455 |
+
```"""
|
| 1456 |
+
# Use CHINESE_CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1457 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1458 |
+
output_hidden_states = (
|
| 1459 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1460 |
+
)
|
| 1461 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1462 |
+
|
| 1463 |
+
text_outputs = self.text_model(
|
| 1464 |
+
input_ids=input_ids,
|
| 1465 |
+
attention_mask=attention_mask,
|
| 1466 |
+
token_type_ids=token_type_ids,
|
| 1467 |
+
position_ids=position_ids,
|
| 1468 |
+
output_attentions=output_attentions,
|
| 1469 |
+
output_hidden_states=output_hidden_states,
|
| 1470 |
+
return_dict=return_dict,
|
| 1471 |
+
)
|
| 1472 |
+
|
| 1473 |
+
pooled_output = text_outputs[0][:, 0, :]
|
| 1474 |
+
text_features = self.text_projection(pooled_output)
|
| 1475 |
+
|
| 1476 |
+
return text_features
|
| 1477 |
+
|
| 1478 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_VISION_INPUTS_DOCSTRING)
|
| 1479 |
+
def get_image_features(
|
| 1480 |
+
self,
|
| 1481 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1482 |
+
output_attentions: Optional[bool] = None,
|
| 1483 |
+
output_hidden_states: Optional[bool] = None,
|
| 1484 |
+
interpolate_pos_encoding: bool = False,
|
| 1485 |
+
return_dict: Optional[bool] = None,
|
| 1486 |
+
) -> torch.FloatTensor:
|
| 1487 |
+
r"""
|
| 1488 |
+
Returns:
|
| 1489 |
+
image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
|
| 1490 |
+
applying the projection layer to the final [CLS] hidden state of Vision-Transformer.
|
| 1491 |
+
|
| 1492 |
+
Examples:
|
| 1493 |
+
|
| 1494 |
+
```python
|
| 1495 |
+
>>> from PIL import Image
|
| 1496 |
+
>>> import requests
|
| 1497 |
+
>>> from transformers import AutoProcessor, ChineseCLIPModel
|
| 1498 |
+
|
| 1499 |
+
>>> model = ChineseCLIPModel.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
| 1500 |
+
>>> processor = AutoProcessor.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
| 1501 |
+
|
| 1502 |
+
>>> url = "https://clip-cn-beijing.oss-cn-beijing.aliyuncs.com/pokemon.jpeg"
|
| 1503 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1504 |
+
|
| 1505 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1506 |
+
|
| 1507 |
+
>>> image_features = model.get_image_features(**inputs)
|
| 1508 |
+
>>> image_features = image_features / image_features.norm(p=2, dim=-1, keepdim=True)
|
| 1509 |
+
```"""
|
| 1510 |
+
# Use CHINESE_CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1511 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1512 |
+
output_hidden_states = (
|
| 1513 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1514 |
+
)
|
| 1515 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1516 |
+
|
| 1517 |
+
vision_outputs = self.vision_model(
|
| 1518 |
+
pixel_values=pixel_values,
|
| 1519 |
+
output_attentions=output_attentions,
|
| 1520 |
+
output_hidden_states=output_hidden_states,
|
| 1521 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1522 |
+
return_dict=return_dict,
|
| 1523 |
+
)
|
| 1524 |
+
|
| 1525 |
+
pooled_output = vision_outputs[1] # pooled_output
|
| 1526 |
+
image_features = self.visual_projection(pooled_output)
|
| 1527 |
+
|
| 1528 |
+
return image_features
|
| 1529 |
+
|
| 1530 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_INPUTS_DOCSTRING)
|
| 1531 |
+
@replace_return_docstrings(output_type=ChineseCLIPOutput, config_class=ChineseCLIPConfig)
|
| 1532 |
+
def forward(
|
| 1533 |
+
self,
|
| 1534 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1535 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1536 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1537 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1538 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1539 |
+
return_loss: Optional[bool] = None,
|
| 1540 |
+
output_attentions: Optional[bool] = None,
|
| 1541 |
+
output_hidden_states: Optional[bool] = None,
|
| 1542 |
+
interpolate_pos_encoding: bool = False,
|
| 1543 |
+
return_dict: Optional[bool] = None,
|
| 1544 |
+
) -> Union[Tuple, ChineseCLIPOutput]:
|
| 1545 |
+
r"""
|
| 1546 |
+
Returns:
|
| 1547 |
+
|
| 1548 |
+
Examples:
|
| 1549 |
+
|
| 1550 |
+
```python
|
| 1551 |
+
>>> from PIL import Image
|
| 1552 |
+
>>> import requests
|
| 1553 |
+
>>> from transformers import AutoProcessor, ChineseCLIPModel
|
| 1554 |
+
|
| 1555 |
+
>>> model = ChineseCLIPModel.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
| 1556 |
+
>>> processor = AutoProcessor.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
| 1557 |
+
|
| 1558 |
+
>>> url = "https://clip-cn-beijing.oss-cn-beijing.aliyuncs.com/pokemon.jpeg"
|
| 1559 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1560 |
+
|
| 1561 |
+
>>> inputs = processor(text=["杰尼龟", "妙蛙种子", "小火龙", "皮卡丘"], images=image, return_tensors="pt", padding=True)
|
| 1562 |
+
|
| 1563 |
+
>>> outputs = model(**inputs)
|
| 1564 |
+
>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
|
| 1565 |
+
>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
|
| 1566 |
+
```"""
|
| 1567 |
+
# Use CHINESE_CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1568 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1569 |
+
output_hidden_states = (
|
| 1570 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1571 |
+
)
|
| 1572 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1573 |
+
|
| 1574 |
+
vision_outputs = self.vision_model(
|
| 1575 |
+
pixel_values=pixel_values,
|
| 1576 |
+
output_attentions=output_attentions,
|
| 1577 |
+
output_hidden_states=output_hidden_states,
|
| 1578 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1579 |
+
return_dict=return_dict,
|
| 1580 |
+
)
|
| 1581 |
+
|
| 1582 |
+
text_outputs = self.text_model(
|
| 1583 |
+
input_ids=input_ids,
|
| 1584 |
+
attention_mask=attention_mask,
|
| 1585 |
+
token_type_ids=token_type_ids,
|
| 1586 |
+
position_ids=position_ids,
|
| 1587 |
+
output_attentions=output_attentions,
|
| 1588 |
+
output_hidden_states=output_hidden_states,
|
| 1589 |
+
return_dict=return_dict,
|
| 1590 |
+
)
|
| 1591 |
+
|
| 1592 |
+
image_embeds = vision_outputs[1]
|
| 1593 |
+
image_embeds = self.visual_projection(image_embeds)
|
| 1594 |
+
|
| 1595 |
+
text_embeds = text_outputs[0][:, 0, :]
|
| 1596 |
+
text_embeds = self.text_projection(text_embeds)
|
| 1597 |
+
|
| 1598 |
+
# normalized features
|
| 1599 |
+
image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1600 |
+
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1601 |
+
|
| 1602 |
+
# cosine similarity as logits
|
| 1603 |
+
logit_scale = self.logit_scale.exp()
|
| 1604 |
+
logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
|
| 1605 |
+
logits_per_image = logits_per_text.t()
|
| 1606 |
+
|
| 1607 |
+
loss = None
|
| 1608 |
+
if return_loss:
|
| 1609 |
+
loss = chinese_clip_loss(logits_per_text)
|
| 1610 |
+
|
| 1611 |
+
if not return_dict:
|
| 1612 |
+
# fix the None pooled_output of text_outputs to conform with dict_output
|
| 1613 |
+
pooled_output = text_outputs[1]
|
| 1614 |
+
if pooled_output is None:
|
| 1615 |
+
text_outputs = (text_outputs[0],) + text_outputs[2:]
|
| 1616 |
+
output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
|
| 1617 |
+
return ((loss,) + output) if loss is not None else output
|
| 1618 |
+
|
| 1619 |
+
return ChineseCLIPOutput(
|
| 1620 |
+
loss=loss,
|
| 1621 |
+
logits_per_image=logits_per_image,
|
| 1622 |
+
logits_per_text=logits_per_text,
|
| 1623 |
+
text_embeds=text_embeds,
|
| 1624 |
+
image_embeds=image_embeds,
|
| 1625 |
+
text_model_output=text_outputs,
|
| 1626 |
+
vision_model_output=vision_outputs,
|
| 1627 |
+
)
|
| 1628 |
+
|
| 1629 |
+
|
| 1630 |
+
__all__ = ["ChineseCLIPModel", "ChineseCLIPPreTrainedModel", "ChineseCLIPTextModel", "ChineseCLIPVisionModel"]
|
janus/lib/python3.10/site-packages/transformers/models/chinese_clip/processing_chinese_clip.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The OFA-Sys Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Image/Text processor class for Chinese-CLIP
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import warnings
|
| 20 |
+
from typing import List, Union
|
| 21 |
+
|
| 22 |
+
from ...image_utils import ImageInput
|
| 23 |
+
from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
|
| 24 |
+
from ...tokenization_utils_base import BatchEncoding, PreTokenizedInput, TextInput
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class ChineseClipProcessorKwargs(ProcessingKwargs, total=False):
|
| 28 |
+
_defaults = {}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ChineseCLIPProcessor(ProcessorMixin):
|
| 32 |
+
r"""
|
| 33 |
+
Constructs a Chinese-CLIP processor which wraps a Chinese-CLIP image processor and a Chinese-CLIP tokenizer into a
|
| 34 |
+
single processor.
|
| 35 |
+
|
| 36 |
+
[`ChineseCLIPProcessor`] offers all the functionalities of [`ChineseCLIPImageProcessor`] and [`BertTokenizerFast`].
|
| 37 |
+
See the [`~ChineseCLIPProcessor.__call__`] and [`~ChineseCLIPProcessor.decode`] for more information.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
image_processor ([`ChineseCLIPImageProcessor`], *optional*):
|
| 41 |
+
The image processor is a required input.
|
| 42 |
+
tokenizer ([`BertTokenizerFast`], *optional*):
|
| 43 |
+
The tokenizer is a required input.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
attributes = ["image_processor", "tokenizer"]
|
| 47 |
+
image_processor_class = "ChineseCLIPImageProcessor"
|
| 48 |
+
tokenizer_class = ("BertTokenizer", "BertTokenizerFast")
|
| 49 |
+
|
| 50 |
+
def __init__(self, image_processor=None, tokenizer=None, **kwargs):
|
| 51 |
+
feature_extractor = None
|
| 52 |
+
if "feature_extractor" in kwargs:
|
| 53 |
+
warnings.warn(
|
| 54 |
+
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
|
| 55 |
+
" instead.",
|
| 56 |
+
FutureWarning,
|
| 57 |
+
)
|
| 58 |
+
feature_extractor = kwargs.pop("feature_extractor")
|
| 59 |
+
|
| 60 |
+
image_processor = image_processor if image_processor is not None else feature_extractor
|
| 61 |
+
if image_processor is None:
|
| 62 |
+
raise ValueError("You need to specify an `image_processor`.")
|
| 63 |
+
if tokenizer is None:
|
| 64 |
+
raise ValueError("You need to specify a `tokenizer`.")
|
| 65 |
+
|
| 66 |
+
super().__init__(image_processor, tokenizer)
|
| 67 |
+
self.current_processor = self.image_processor
|
| 68 |
+
|
| 69 |
+
def __call__(
|
| 70 |
+
self,
|
| 71 |
+
text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
|
| 72 |
+
images: ImageInput = None,
|
| 73 |
+
audio=None,
|
| 74 |
+
videos=None,
|
| 75 |
+
**kwargs: Unpack[ChineseClipProcessorKwargs],
|
| 76 |
+
) -> BatchEncoding:
|
| 77 |
+
"""
|
| 78 |
+
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
|
| 79 |
+
and `kwargs` arguments to BertTokenizerFast's [`~BertTokenizerFast.__call__`] if `text` is not `None` to encode
|
| 80 |
+
the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
|
| 81 |
+
CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
|
| 82 |
+
of the above two methods for more information.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
text (`str`, `List[str]`, `List[List[str]]`):
|
| 86 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 87 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 88 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 89 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
| 90 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 91 |
+
tensor. Both channels-first and channels-last formats are supported.
|
| 92 |
+
|
| 93 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 94 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 95 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 96 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 97 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 98 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 99 |
+
Returns:
|
| 100 |
+
[`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
|
| 101 |
+
|
| 102 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
| 103 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 104 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 105 |
+
`None`).
|
| 106 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
if text is None and images is None:
|
| 110 |
+
raise ValueError("You have to specify either text or images. Both cannot be none.")
|
| 111 |
+
output_kwargs = self._merge_kwargs(
|
| 112 |
+
ChineseClipProcessorKwargs,
|
| 113 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 114 |
+
**kwargs,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
if text is not None:
|
| 118 |
+
encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
|
| 119 |
+
if images is not None:
|
| 120 |
+
image_features = self.image_processor(images, **output_kwargs["images_kwargs"])
|
| 121 |
+
|
| 122 |
+
# BC for explicit return_tensors
|
| 123 |
+
if "return_tensors" in output_kwargs["common_kwargs"]:
|
| 124 |
+
return_tensors = output_kwargs["common_kwargs"].pop("return_tensors", None)
|
| 125 |
+
|
| 126 |
+
if text is not None and images is not None:
|
| 127 |
+
encoding["pixel_values"] = image_features.pixel_values
|
| 128 |
+
return encoding
|
| 129 |
+
elif text is not None:
|
| 130 |
+
return encoding
|
| 131 |
+
else:
|
| 132 |
+
return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)
|
| 133 |
+
|
| 134 |
+
def batch_decode(self, *args, **kwargs):
|
| 135 |
+
"""
|
| 136 |
+
This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
|
| 137 |
+
refer to the docstring of this method for more information.
|
| 138 |
+
"""
|
| 139 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
| 140 |
+
|
| 141 |
+
def decode(self, *args, **kwargs):
|
| 142 |
+
"""
|
| 143 |
+
This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
|
| 144 |
+
the docstring of this method for more information.
|
| 145 |
+
"""
|
| 146 |
+
return self.tokenizer.decode(*args, **kwargs)
|
| 147 |
+
|
| 148 |
+
@property
|
| 149 |
+
def model_input_names(self):
|
| 150 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
| 151 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 152 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
| 153 |
+
|
| 154 |
+
@property
|
| 155 |
+
def feature_extractor_class(self):
|
| 156 |
+
warnings.warn(
|
| 157 |
+
"`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
|
| 158 |
+
FutureWarning,
|
| 159 |
+
)
|
| 160 |
+
return self.image_processor_class
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
__all__ = ["ChineseCLIPProcessor"]
|
janus/lib/python3.10/site-packages/transformers/models/cvt/__pycache__/modeling_tf_cvt.cpython-310.pyc
ADDED
|
Binary file (34.2 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/diffllama/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 |
+
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_diffllama import *
|
| 22 |
+
from .modeling_diffllama 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__)
|
janus/lib/python3.10/site-packages/transformers/models/diffllama/__pycache__/configuration_diffllama.cpython-310.pyc
ADDED
|
Binary file (9.22 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/diffllama/__pycache__/modular_diffllama.cpython-310.pyc
ADDED
|
Binary file (12 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/diffllama/modeling_diffllama.py
ADDED
|
@@ -0,0 +1,1420 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/diffllama/modular_diffllama.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_diffllama.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2024 weak-kajuma and the HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
# This code is based on Llama implementations in this library and Microsoft's
|
| 11 |
+
# Differential Transformer implementations.
|
| 12 |
+
|
| 13 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 14 |
+
# you may not use this file except in compliance with the License.
|
| 15 |
+
# You may obtain a copy of the License at
|
| 16 |
+
#
|
| 17 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 18 |
+
#
|
| 19 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 20 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 21 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 22 |
+
# See the License for the specific language governing permissions and
|
| 23 |
+
# limitations under the License.
|
| 24 |
+
import math
|
| 25 |
+
from typing import List, Optional, Tuple, Union
|
| 26 |
+
|
| 27 |
+
import torch
|
| 28 |
+
from torch import nn
|
| 29 |
+
|
| 30 |
+
from ...activations import ACT2FN
|
| 31 |
+
from ...cache_utils import Cache, DynamicCache, StaticCache
|
| 32 |
+
from ...generation import GenerationMixin
|
| 33 |
+
from ...modeling_attn_mask_utils import AttentionMaskConverter
|
| 34 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs, _flash_attention_forward
|
| 35 |
+
from ...modeling_outputs import (
|
| 36 |
+
BaseModelOutputWithPast,
|
| 37 |
+
CausalLMOutputWithPast,
|
| 38 |
+
QuestionAnsweringModelOutput,
|
| 39 |
+
SequenceClassifierOutputWithPast,
|
| 40 |
+
TokenClassifierOutput,
|
| 41 |
+
)
|
| 42 |
+
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
| 43 |
+
from ...modeling_utils import PreTrainedModel
|
| 44 |
+
from ...processing_utils import Unpack
|
| 45 |
+
from ...utils import (
|
| 46 |
+
LossKwargs,
|
| 47 |
+
add_code_sample_docstrings,
|
| 48 |
+
add_start_docstrings,
|
| 49 |
+
add_start_docstrings_to_model_forward,
|
| 50 |
+
is_flash_attn_greater_or_equal_2_10,
|
| 51 |
+
logging,
|
| 52 |
+
replace_return_docstrings,
|
| 53 |
+
)
|
| 54 |
+
from .configuration_diffllama import DiffLlamaConfig
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
logger = logging.get_logger(__name__)
|
| 58 |
+
|
| 59 |
+
_CHECKPOINT_FOR_DOC = "kajuma/DiffLlama-0.3B-handcut"
|
| 60 |
+
_CONFIG_FOR_DOC = "DiffLlamaConfig"
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class DiffLlamaMLP(nn.Module):
|
| 64 |
+
def __init__(self, config):
|
| 65 |
+
super().__init__()
|
| 66 |
+
self.config = config
|
| 67 |
+
self.hidden_size = config.hidden_size
|
| 68 |
+
self.intermediate_size = config.intermediate_size
|
| 69 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 70 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 71 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 72 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 73 |
+
|
| 74 |
+
def forward(self, x):
|
| 75 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 76 |
+
return down_proj
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def rotate_half(x):
|
| 80 |
+
"""Rotates half the hidden dims of the input."""
|
| 81 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 82 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 83 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 87 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
q (`torch.Tensor`): The query tensor.
|
| 91 |
+
k (`torch.Tensor`): The key tensor.
|
| 92 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 93 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 94 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 95 |
+
Deprecated and unused.
|
| 96 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 97 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 98 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 99 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 100 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 101 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 102 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 103 |
+
Returns:
|
| 104 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 105 |
+
"""
|
| 106 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 107 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 108 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 109 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 110 |
+
return q_embed, k_embed
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 114 |
+
"""
|
| 115 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 116 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 117 |
+
"""
|
| 118 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 119 |
+
if n_rep == 1:
|
| 120 |
+
return hidden_states
|
| 121 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 122 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def lambda_init_fn(layer_idx):
|
| 126 |
+
return 0.8 - 0.6 * math.exp(-0.3 * layer_idx)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class DiffLlamaAttention(nn.Module):
|
| 130 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 131 |
+
|
| 132 |
+
def __init__(self, config: DiffLlamaConfig, layer_idx: Optional[int] = None):
|
| 133 |
+
super().__init__()
|
| 134 |
+
self.config = config
|
| 135 |
+
self.layer_idx = layer_idx
|
| 136 |
+
if layer_idx is None:
|
| 137 |
+
logger.warning_once(
|
| 138 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
| 139 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
| 140 |
+
"when creating this class."
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
self.attention_dropout = config.attention_dropout
|
| 144 |
+
self.hidden_size = config.hidden_size
|
| 145 |
+
self.num_heads = config.num_attention_heads
|
| 146 |
+
self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
|
| 147 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 148 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 149 |
+
# under this are not used
|
| 150 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 151 |
+
self.rope_theta = config.rope_theta
|
| 152 |
+
self.is_causal = True
|
| 153 |
+
|
| 154 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
|
| 155 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
| 156 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
| 157 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
|
| 158 |
+
|
| 159 |
+
self.lambda_init = lambda_init_fn(layer_idx)
|
| 160 |
+
self.lambda_q1 = nn.Parameter(torch.normal(0, config.lambda_std_dev, size=(self.head_dim,)))
|
| 161 |
+
self.lambda_k1 = nn.Parameter(torch.normal(0, config.lambda_std_dev, size=(self.head_dim,)))
|
| 162 |
+
self.lambda_q2 = nn.Parameter(torch.normal(0, config.lambda_std_dev, size=(self.head_dim,)))
|
| 163 |
+
self.lambda_k2 = nn.Parameter(torch.normal(0, config.lambda_std_dev, size=(self.head_dim,)))
|
| 164 |
+
self.groupnorm = nn.RMSNorm(2 * self.head_dim, eps=config.rms_norm_eps, elementwise_affine=False)
|
| 165 |
+
|
| 166 |
+
def forward(
|
| 167 |
+
self,
|
| 168 |
+
hidden_states: torch.Tensor,
|
| 169 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
| 170 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 171 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 172 |
+
past_key_value: Optional[Cache] = None,
|
| 173 |
+
output_attentions: bool = False,
|
| 174 |
+
use_cache: bool = False,
|
| 175 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 176 |
+
**kwargs,
|
| 177 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 178 |
+
bsz, target_len, _ = hidden_states.size()
|
| 179 |
+
q_len = target_len
|
| 180 |
+
|
| 181 |
+
query_states = self.q_proj(hidden_states)
|
| 182 |
+
key_states = self.k_proj(hidden_states)
|
| 183 |
+
value_states = self.v_proj(hidden_states)
|
| 184 |
+
|
| 185 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 186 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 187 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 188 |
+
|
| 189 |
+
cos, sin = position_embeddings
|
| 190 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 191 |
+
|
| 192 |
+
if past_key_value is not None:
|
| 193 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 194 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 195 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 196 |
+
|
| 197 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 198 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 199 |
+
value_states = torch.cat(torch.chunk(value_states, 2, dim=1), dim=-1)
|
| 200 |
+
value_states = value_states.repeat(1, 2, 1, 1)
|
| 201 |
+
|
| 202 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 203 |
+
|
| 204 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
| 205 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 206 |
+
attn_weights = attn_weights + causal_mask
|
| 207 |
+
|
| 208 |
+
# upcast attention to fp32
|
| 209 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 210 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
| 211 |
+
lambda_1 = torch.exp(torch.sum(self.lambda_q1 * self.lambda_k1, dim=-1, dtype=torch.float32)).to(
|
| 212 |
+
query_states.dtype
|
| 213 |
+
)
|
| 214 |
+
lambda_2 = torch.exp(torch.sum(self.lambda_q2 * self.lambda_k2, dim=-1, dtype=torch.float32)).to(
|
| 215 |
+
query_states.dtype
|
| 216 |
+
)
|
| 217 |
+
lambda_full = lambda_1 - lambda_2 + self.lambda_init
|
| 218 |
+
|
| 219 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 220 |
+
attn_output1, attn_output2 = torch.chunk(attn_output, 2, dim=1)
|
| 221 |
+
|
| 222 |
+
attn_output = attn_output1 - lambda_full * attn_output2
|
| 223 |
+
attn_output = (1 - self.lambda_init) * self.groupnorm(attn_output)
|
| 224 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 225 |
+
attn_output = attn_output.reshape(bsz, q_len, -1)
|
| 226 |
+
|
| 227 |
+
attn_output = self.o_proj(attn_output)
|
| 228 |
+
|
| 229 |
+
if not output_attentions:
|
| 230 |
+
attn_weights = None
|
| 231 |
+
|
| 232 |
+
return attn_output, attn_weights
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
class DiffLlamaFlashAttention2(DiffLlamaAttention):
|
| 236 |
+
"""
|
| 237 |
+
DiffLlama flash attention module. This module inherits from `DiffLlamaAttention` as the weights of the module stays
|
| 238 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
| 239 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
| 240 |
+
"""
|
| 241 |
+
|
| 242 |
+
def __init__(self, *args, **kwargs):
|
| 243 |
+
super().__init__(*args, **kwargs)
|
| 244 |
+
|
| 245 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
| 246 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
| 247 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
| 248 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
| 249 |
+
|
| 250 |
+
def forward(
|
| 251 |
+
self,
|
| 252 |
+
hidden_states: torch.Tensor,
|
| 253 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
| 254 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 255 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 256 |
+
past_key_value: Optional[Cache] = None,
|
| 257 |
+
output_attentions: bool = False,
|
| 258 |
+
use_cache: bool = False,
|
| 259 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 260 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 261 |
+
if isinstance(past_key_value, StaticCache):
|
| 262 |
+
raise ValueError(
|
| 263 |
+
"`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
|
| 264 |
+
"make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
output_attentions = False
|
| 268 |
+
|
| 269 |
+
bsz, q_len, _ = hidden_states.size()
|
| 270 |
+
|
| 271 |
+
query_states = self.q_proj(hidden_states)
|
| 272 |
+
key_states = self.k_proj(hidden_states)
|
| 273 |
+
value_states = self.v_proj(hidden_states)
|
| 274 |
+
|
| 275 |
+
# Flash attention requires the input to have the shape
|
| 276 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
| 277 |
+
# therefore we just need to keep the original shape
|
| 278 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 279 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 280 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 281 |
+
|
| 282 |
+
if position_embeddings is None:
|
| 283 |
+
logger.warning_once(
|
| 284 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
| 285 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
| 286 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
|
| 287 |
+
"removed and `position_embeddings` will be mandatory."
|
| 288 |
+
)
|
| 289 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 290 |
+
else:
|
| 291 |
+
cos, sin = position_embeddings
|
| 292 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 293 |
+
|
| 294 |
+
if past_key_value is not None:
|
| 295 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 296 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 297 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 298 |
+
|
| 299 |
+
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
|
| 300 |
+
# to be able to avoid many of these transpose/reshape/view.
|
| 301 |
+
query_states = query_states.transpose(1, 2)
|
| 302 |
+
key_states = key_states.transpose(1, 2)
|
| 303 |
+
value_states = value_states.transpose(1, 2)
|
| 304 |
+
|
| 305 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
| 306 |
+
|
| 307 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
| 308 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
| 309 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
| 310 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
| 311 |
+
# in fp32. (DiffLlamaRMSNorm handles it correctly)
|
| 312 |
+
|
| 313 |
+
input_dtype = query_states.dtype
|
| 314 |
+
if input_dtype == torch.float32:
|
| 315 |
+
if torch.is_autocast_enabled():
|
| 316 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
| 317 |
+
# Handle the case where the model is quantized
|
| 318 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
| 319 |
+
target_dtype = self.config._pre_quantization_dtype
|
| 320 |
+
else:
|
| 321 |
+
target_dtype = self.q_proj.weight.dtype
|
| 322 |
+
|
| 323 |
+
logger.warning_once(
|
| 324 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
| 325 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
| 326 |
+
f" {target_dtype}."
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
query_states = query_states.to(target_dtype)
|
| 330 |
+
key_states = key_states.to(target_dtype)
|
| 331 |
+
value_states = value_states.to(target_dtype)
|
| 332 |
+
|
| 333 |
+
value_states1, value_states2 = torch.chunk(value_states, 2, dim=2)
|
| 334 |
+
value_states1 = value_states1.repeat(1, 1, 2, 1)
|
| 335 |
+
value_states2 = value_states2.repeat(1, 1, 2, 1)
|
| 336 |
+
|
| 337 |
+
attn_output1 = _flash_attention_forward(
|
| 338 |
+
query_states,
|
| 339 |
+
key_states,
|
| 340 |
+
value_states1,
|
| 341 |
+
attention_mask,
|
| 342 |
+
q_len,
|
| 343 |
+
position_ids=position_ids,
|
| 344 |
+
dropout=dropout_rate,
|
| 345 |
+
sliding_window=getattr(self, "sliding_window", None),
|
| 346 |
+
use_top_left_mask=self._flash_attn_uses_top_left_mask,
|
| 347 |
+
is_causal=self.is_causal,
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
attn_output2 = _flash_attention_forward(
|
| 351 |
+
query_states,
|
| 352 |
+
key_states,
|
| 353 |
+
value_states2,
|
| 354 |
+
attention_mask,
|
| 355 |
+
q_len,
|
| 356 |
+
position_ids=position_ids,
|
| 357 |
+
dropout=dropout_rate,
|
| 358 |
+
sliding_window=getattr(self, "sliding_window", None),
|
| 359 |
+
use_top_left_mask=self._flash_attn_uses_top_left_mask,
|
| 360 |
+
is_causal=self.is_causal,
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
attn_output = torch.cat([attn_output1, attn_output2], dim=-1)
|
| 364 |
+
attn_output1, attn_output2 = torch.chunk(attn_output, 2, dim=2)
|
| 365 |
+
|
| 366 |
+
lambda_1 = torch.exp(torch.sum(self.lambda_q1 * self.lambda_k1, dim=-1, dtype=torch.float32)).to(
|
| 367 |
+
query_states.dtype
|
| 368 |
+
)
|
| 369 |
+
lambda_2 = torch.exp(torch.sum(self.lambda_q2 * self.lambda_k2, dim=-1, dtype=torch.float32)).to(
|
| 370 |
+
query_states.dtype
|
| 371 |
+
)
|
| 372 |
+
lambda_full = lambda_1 - lambda_2 + self.lambda_init
|
| 373 |
+
|
| 374 |
+
attn_output = attn_output1 - lambda_full * attn_output2
|
| 375 |
+
attn_output = (1 - self.lambda_init) * self.groupnorm(attn_output)
|
| 376 |
+
attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
|
| 377 |
+
attn_output = self.o_proj(attn_output)
|
| 378 |
+
|
| 379 |
+
if not output_attentions:
|
| 380 |
+
attn_weights = None
|
| 381 |
+
|
| 382 |
+
return attn_output, attn_weights
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
class DiffLlamaSdpaAttention(DiffLlamaAttention):
|
| 386 |
+
"""
|
| 387 |
+
DiffLlama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
| 388 |
+
`DiffLlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
| 389 |
+
SDPA API.
|
| 390 |
+
"""
|
| 391 |
+
|
| 392 |
+
# Adapted from DiffLlamaAttention.forward
|
| 393 |
+
def forward(
|
| 394 |
+
self,
|
| 395 |
+
hidden_states: torch.Tensor,
|
| 396 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
| 397 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 398 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 399 |
+
past_key_value: Optional[Cache] = None,
|
| 400 |
+
output_attentions: bool = False,
|
| 401 |
+
use_cache: bool = False,
|
| 402 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 403 |
+
**kwargs,
|
| 404 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 405 |
+
if output_attentions:
|
| 406 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
| 407 |
+
logger.warning_once(
|
| 408 |
+
"DiffLlamaModel is using DiffLlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
| 409 |
+
'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 410 |
+
)
|
| 411 |
+
return super().forward(
|
| 412 |
+
hidden_states=hidden_states,
|
| 413 |
+
attention_mask=attention_mask,
|
| 414 |
+
position_ids=position_ids,
|
| 415 |
+
past_key_value=past_key_value,
|
| 416 |
+
output_attentions=output_attentions,
|
| 417 |
+
use_cache=use_cache,
|
| 418 |
+
cache_position=cache_position,
|
| 419 |
+
position_embeddings=position_embeddings,
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
bsz, q_len, _ = hidden_states.size()
|
| 423 |
+
|
| 424 |
+
query_states = self.q_proj(hidden_states)
|
| 425 |
+
key_states = self.k_proj(hidden_states)
|
| 426 |
+
value_states = self.v_proj(hidden_states)
|
| 427 |
+
|
| 428 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 429 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 430 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 431 |
+
|
| 432 |
+
cos, sin = position_embeddings
|
| 433 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 434 |
+
|
| 435 |
+
if past_key_value is not None:
|
| 436 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 437 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 438 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 439 |
+
|
| 440 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 441 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 442 |
+
value_states = torch.cat(torch.chunk(value_states, 2, dim=1), dim=-1)
|
| 443 |
+
value_states = value_states.repeat(1, 2, 1, 1)
|
| 444 |
+
|
| 445 |
+
causal_mask = attention_mask
|
| 446 |
+
if attention_mask is not None:
|
| 447 |
+
causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
|
| 448 |
+
|
| 449 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
| 450 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
| 451 |
+
if query_states.device.type == "cuda" and causal_mask is not None:
|
| 452 |
+
query_states = query_states.contiguous()
|
| 453 |
+
key_states = key_states.contiguous()
|
| 454 |
+
value_states = value_states.contiguous()
|
| 455 |
+
|
| 456 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
|
| 457 |
+
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
|
| 458 |
+
is_causal = True if causal_mask is None and q_len > 1 else False
|
| 459 |
+
|
| 460 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
| 461 |
+
query_states,
|
| 462 |
+
key_states,
|
| 463 |
+
value_states,
|
| 464 |
+
attn_mask=causal_mask,
|
| 465 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
| 466 |
+
is_causal=is_causal,
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
attn_output1, attn_output2 = torch.chunk(attn_output, 2, dim=1)
|
| 470 |
+
|
| 471 |
+
lambda_1 = torch.exp(torch.sum(self.lambda_q1 * self.lambda_k1, dim=-1, dtype=torch.float32)).to(
|
| 472 |
+
query_states.dtype
|
| 473 |
+
)
|
| 474 |
+
lambda_2 = torch.exp(torch.sum(self.lambda_q2 * self.lambda_k2, dim=-1, dtype=torch.float32)).to(
|
| 475 |
+
query_states.dtype
|
| 476 |
+
)
|
| 477 |
+
lambda_full = lambda_1 - lambda_2 + self.lambda_init
|
| 478 |
+
|
| 479 |
+
attn_output = attn_output1 - lambda_full * attn_output2
|
| 480 |
+
attn_output = (1 - self.lambda_init) * self.groupnorm(attn_output)
|
| 481 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 482 |
+
attn_output = attn_output.view(bsz, q_len, -1)
|
| 483 |
+
attn_output = self.o_proj(attn_output)
|
| 484 |
+
|
| 485 |
+
return attn_output, None
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
class DiffLlamaRMSNorm(nn.Module):
|
| 489 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 490 |
+
"""
|
| 491 |
+
DiffLlamaRMSNorm is equivalent to T5LayerNorm
|
| 492 |
+
"""
|
| 493 |
+
super().__init__()
|
| 494 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 495 |
+
self.variance_epsilon = eps
|
| 496 |
+
|
| 497 |
+
def forward(self, hidden_states):
|
| 498 |
+
input_dtype = hidden_states.dtype
|
| 499 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 500 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 501 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 502 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 503 |
+
|
| 504 |
+
def extra_repr(self):
|
| 505 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
DIFFLLAMA_ATTENTION_CLASSES = {
|
| 509 |
+
"eager": DiffLlamaAttention,
|
| 510 |
+
"flash_attention_2": DiffLlamaFlashAttention2,
|
| 511 |
+
"sdpa": DiffLlamaSdpaAttention,
|
| 512 |
+
}
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
class DiffLlamaDecoderLayer(nn.Module):
|
| 516 |
+
def __init__(self, config: DiffLlamaConfig, layer_idx: int):
|
| 517 |
+
super().__init__()
|
| 518 |
+
self.hidden_size = config.hidden_size
|
| 519 |
+
|
| 520 |
+
self.self_attn = DIFFLLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
|
| 521 |
+
|
| 522 |
+
self.mlp = DiffLlamaMLP(config)
|
| 523 |
+
self.input_layernorm = DiffLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 524 |
+
self.post_attention_layernorm = DiffLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 525 |
+
|
| 526 |
+
def forward(
|
| 527 |
+
self,
|
| 528 |
+
hidden_states: torch.Tensor,
|
| 529 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 530 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 531 |
+
past_key_value: Optional[Cache] = None,
|
| 532 |
+
output_attentions: Optional[bool] = False,
|
| 533 |
+
use_cache: Optional[bool] = False,
|
| 534 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 535 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
| 536 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 537 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 538 |
+
residual = hidden_states
|
| 539 |
+
|
| 540 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 541 |
+
|
| 542 |
+
# Self Attention
|
| 543 |
+
hidden_states, self_attn_weights = self.self_attn(
|
| 544 |
+
hidden_states=hidden_states,
|
| 545 |
+
attention_mask=attention_mask,
|
| 546 |
+
position_ids=position_ids,
|
| 547 |
+
past_key_value=past_key_value,
|
| 548 |
+
output_attentions=output_attentions,
|
| 549 |
+
use_cache=use_cache,
|
| 550 |
+
cache_position=cache_position,
|
| 551 |
+
position_embeddings=position_embeddings,
|
| 552 |
+
**kwargs,
|
| 553 |
+
)
|
| 554 |
+
hidden_states = residual + hidden_states
|
| 555 |
+
|
| 556 |
+
# Fully Connected
|
| 557 |
+
residual = hidden_states
|
| 558 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 559 |
+
hidden_states = self.mlp(hidden_states)
|
| 560 |
+
hidden_states = residual + hidden_states
|
| 561 |
+
|
| 562 |
+
outputs = (hidden_states,)
|
| 563 |
+
if output_attentions:
|
| 564 |
+
outputs += (self_attn_weights,)
|
| 565 |
+
|
| 566 |
+
return outputs
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
DIFFLLAMA_START_DOCSTRING = r"""
|
| 570 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 571 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 572 |
+
etc.)
|
| 573 |
+
|
| 574 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 575 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 576 |
+
and behavior.
|
| 577 |
+
|
| 578 |
+
Parameters:
|
| 579 |
+
config ([`DiffLlamaConfig`]):
|
| 580 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 581 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 582 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 583 |
+
"""
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
@add_start_docstrings(
|
| 587 |
+
"The bare DiffLlama Model outputting raw hidden-states without any specific head on top.",
|
| 588 |
+
DIFFLLAMA_START_DOCSTRING,
|
| 589 |
+
)
|
| 590 |
+
class DiffLlamaPreTrainedModel(PreTrainedModel):
|
| 591 |
+
config_class = DiffLlamaConfig
|
| 592 |
+
base_model_prefix = "model"
|
| 593 |
+
supports_gradient_checkpointing = True
|
| 594 |
+
_no_split_modules = ["DiffLlamaDecoderLayer"]
|
| 595 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 596 |
+
_supports_flash_attn_2 = True
|
| 597 |
+
_supports_sdpa = True
|
| 598 |
+
_supports_flex_attn = True
|
| 599 |
+
_supports_cache_class = True
|
| 600 |
+
_supports_quantized_cache = True
|
| 601 |
+
_supports_static_cache = True
|
| 602 |
+
|
| 603 |
+
def _init_weights(self, module):
|
| 604 |
+
std = self.config.initializer_range
|
| 605 |
+
if isinstance(module, nn.Linear):
|
| 606 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 607 |
+
if module.bias is not None:
|
| 608 |
+
module.bias.data.zero_()
|
| 609 |
+
elif isinstance(module, nn.Embedding):
|
| 610 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 611 |
+
if module.padding_idx is not None:
|
| 612 |
+
module.weight.data[module.padding_idx].zero_()
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
class DiffLlamaRotaryEmbedding(nn.Module):
|
| 616 |
+
def __init__(self, config: DiffLlamaConfig, device=None):
|
| 617 |
+
super().__init__()
|
| 618 |
+
# BC: "rope_type" was originally "type"
|
| 619 |
+
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
| 620 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
| 621 |
+
else:
|
| 622 |
+
self.rope_type = "default"
|
| 623 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 624 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 625 |
+
|
| 626 |
+
self.config = config
|
| 627 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 628 |
+
|
| 629 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
| 630 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 631 |
+
self.original_inv_freq = self.inv_freq
|
| 632 |
+
|
| 633 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
| 634 |
+
"""
|
| 635 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
| 636 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
| 637 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
| 638 |
+
"""
|
| 639 |
+
seq_len = torch.max(position_ids) + 1
|
| 640 |
+
if seq_len > self.max_seq_len_cached: # growth
|
| 641 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
|
| 642 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
| 643 |
+
self.max_seq_len_cached = seq_len
|
| 644 |
+
|
| 645 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
| 646 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
| 647 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
| 648 |
+
|
| 649 |
+
@torch.no_grad()
|
| 650 |
+
def forward(self, x, position_ids):
|
| 651 |
+
if "dynamic" in self.rope_type:
|
| 652 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
| 653 |
+
|
| 654 |
+
# Core RoPE block
|
| 655 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
| 656 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 657 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
| 658 |
+
device_type = x.device.type
|
| 659 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
| 660 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
| 661 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 662 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 663 |
+
cos = emb.cos()
|
| 664 |
+
sin = emb.sin()
|
| 665 |
+
|
| 666 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
| 667 |
+
cos = cos * self.attention_scaling
|
| 668 |
+
sin = sin * self.attention_scaling
|
| 669 |
+
|
| 670 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
DIFFLLAMA_INPUTS_DOCSTRING = r"""
|
| 674 |
+
Args:
|
| 675 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 676 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 677 |
+
it.
|
| 678 |
+
|
| 679 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 680 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 681 |
+
|
| 682 |
+
[What are input IDs?](../glossary#input-ids)
|
| 683 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 684 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 685 |
+
|
| 686 |
+
- 1 for tokens that are **not masked**,
|
| 687 |
+
- 0 for tokens that are **masked**.
|
| 688 |
+
|
| 689 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 690 |
+
|
| 691 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 692 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 693 |
+
|
| 694 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
| 695 |
+
`past_key_values`).
|
| 696 |
+
|
| 697 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
| 698 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
| 699 |
+
information on the default strategy.
|
| 700 |
+
|
| 701 |
+
- 1 indicates the head is **not masked**,
|
| 702 |
+
- 0 indicates the head is **masked**.
|
| 703 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 704 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 705 |
+
config.n_positions - 1]`.
|
| 706 |
+
|
| 707 |
+
[What are position IDs?](../glossary#position-ids)
|
| 708 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
| 709 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 710 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
| 711 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
| 712 |
+
|
| 713 |
+
Two formats are allowed:
|
| 714 |
+
- a [`~cache_utils.Cache`] instance, see our
|
| 715 |
+
[kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
|
| 716 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 717 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
| 718 |
+
cache format.
|
| 719 |
+
|
| 720 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
| 721 |
+
legacy cache format will be returned.
|
| 722 |
+
|
| 723 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
| 724 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
| 725 |
+
of shape `(batch_size, sequence_length)`.
|
| 726 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 727 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 728 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 729 |
+
model's internal embedding lookup matrix.
|
| 730 |
+
use_cache (`bool`, *optional*):
|
| 731 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 732 |
+
`past_key_values`).
|
| 733 |
+
output_attentions (`bool`, *optional*):
|
| 734 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 735 |
+
tensors for more detail.
|
| 736 |
+
output_hidden_states (`bool`, *optional*):
|
| 737 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 738 |
+
more detail.
|
| 739 |
+
return_dict (`bool`, *optional*):
|
| 740 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 741 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 742 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
| 743 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
| 744 |
+
the complete sequence length.
|
| 745 |
+
"""
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
@add_start_docstrings(
|
| 749 |
+
"The bare DiffLlama Model outputting raw hidden-states without any specific head on top.",
|
| 750 |
+
DIFFLLAMA_START_DOCSTRING,
|
| 751 |
+
)
|
| 752 |
+
class DiffLlamaModel(DiffLlamaPreTrainedModel):
|
| 753 |
+
"""
|
| 754 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DiffLlamaDecoderLayer`]
|
| 755 |
+
|
| 756 |
+
Args:
|
| 757 |
+
config: DiffLlamaConfig
|
| 758 |
+
"""
|
| 759 |
+
|
| 760 |
+
def __init__(self, config: DiffLlamaConfig):
|
| 761 |
+
super().__init__(config)
|
| 762 |
+
self.padding_idx = config.pad_token_id
|
| 763 |
+
self.vocab_size = config.vocab_size
|
| 764 |
+
|
| 765 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 766 |
+
self.layers = nn.ModuleList(
|
| 767 |
+
[DiffLlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 768 |
+
)
|
| 769 |
+
self.norm = DiffLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 770 |
+
self.rotary_emb = DiffLlamaRotaryEmbedding(config=config)
|
| 771 |
+
self.gradient_checkpointing = False
|
| 772 |
+
|
| 773 |
+
# Initialize weights and apply final processing
|
| 774 |
+
self.post_init()
|
| 775 |
+
|
| 776 |
+
def get_input_embeddings(self):
|
| 777 |
+
return self.embed_tokens
|
| 778 |
+
|
| 779 |
+
def set_input_embeddings(self, value):
|
| 780 |
+
self.embed_tokens = value
|
| 781 |
+
|
| 782 |
+
@add_start_docstrings_to_model_forward(DIFFLLAMA_INPUTS_DOCSTRING)
|
| 783 |
+
def forward(
|
| 784 |
+
self,
|
| 785 |
+
input_ids: torch.LongTensor = None,
|
| 786 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 787 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 788 |
+
past_key_values: Optional[Cache] = None,
|
| 789 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 790 |
+
use_cache: Optional[bool] = None,
|
| 791 |
+
output_attentions: Optional[bool] = None,
|
| 792 |
+
output_hidden_states: Optional[bool] = None,
|
| 793 |
+
return_dict: Optional[bool] = None,
|
| 794 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 795 |
+
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
|
| 796 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 797 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 798 |
+
output_hidden_states = (
|
| 799 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 800 |
+
)
|
| 801 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 802 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 803 |
+
|
| 804 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 805 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 806 |
+
|
| 807 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
| 808 |
+
logger.warning_once(
|
| 809 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
| 810 |
+
)
|
| 811 |
+
use_cache = False
|
| 812 |
+
|
| 813 |
+
if inputs_embeds is None:
|
| 814 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 815 |
+
|
| 816 |
+
if use_cache and past_key_values is None:
|
| 817 |
+
past_key_values = DynamicCache()
|
| 818 |
+
|
| 819 |
+
if cache_position is None:
|
| 820 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 821 |
+
cache_position = torch.arange(
|
| 822 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
| 823 |
+
)
|
| 824 |
+
|
| 825 |
+
if position_ids is None:
|
| 826 |
+
position_ids = cache_position.unsqueeze(0)
|
| 827 |
+
|
| 828 |
+
causal_mask = self._update_causal_mask(
|
| 829 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
| 830 |
+
)
|
| 831 |
+
|
| 832 |
+
hidden_states = inputs_embeds
|
| 833 |
+
|
| 834 |
+
# create position embeddings to be shared across the decoder layers
|
| 835 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 836 |
+
|
| 837 |
+
# decoder layers
|
| 838 |
+
all_hidden_states = () if output_hidden_states else None
|
| 839 |
+
all_self_attns = () if output_attentions else None
|
| 840 |
+
|
| 841 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
| 842 |
+
if output_hidden_states:
|
| 843 |
+
all_hidden_states += (hidden_states,)
|
| 844 |
+
|
| 845 |
+
if self.gradient_checkpointing and self.training:
|
| 846 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 847 |
+
decoder_layer.__call__,
|
| 848 |
+
hidden_states,
|
| 849 |
+
causal_mask,
|
| 850 |
+
position_ids,
|
| 851 |
+
past_key_values,
|
| 852 |
+
output_attentions,
|
| 853 |
+
use_cache,
|
| 854 |
+
cache_position,
|
| 855 |
+
position_embeddings,
|
| 856 |
+
)
|
| 857 |
+
else:
|
| 858 |
+
layer_outputs = decoder_layer(
|
| 859 |
+
hidden_states,
|
| 860 |
+
attention_mask=causal_mask,
|
| 861 |
+
position_ids=position_ids,
|
| 862 |
+
past_key_value=past_key_values,
|
| 863 |
+
output_attentions=output_attentions,
|
| 864 |
+
use_cache=use_cache,
|
| 865 |
+
cache_position=cache_position,
|
| 866 |
+
position_embeddings=position_embeddings,
|
| 867 |
+
**flash_attn_kwargs,
|
| 868 |
+
)
|
| 869 |
+
|
| 870 |
+
hidden_states = layer_outputs[0]
|
| 871 |
+
|
| 872 |
+
if output_attentions:
|
| 873 |
+
all_self_attns += (layer_outputs[1],)
|
| 874 |
+
|
| 875 |
+
hidden_states = self.norm(hidden_states)
|
| 876 |
+
|
| 877 |
+
# add hidden states from the last decoder layer
|
| 878 |
+
if output_hidden_states:
|
| 879 |
+
all_hidden_states += (hidden_states,)
|
| 880 |
+
|
| 881 |
+
output = BaseModelOutputWithPast(
|
| 882 |
+
last_hidden_state=hidden_states,
|
| 883 |
+
past_key_values=past_key_values if use_cache else None,
|
| 884 |
+
hidden_states=all_hidden_states,
|
| 885 |
+
attentions=all_self_attns,
|
| 886 |
+
)
|
| 887 |
+
return output if return_dict else output.to_tuple()
|
| 888 |
+
|
| 889 |
+
def _update_causal_mask(
|
| 890 |
+
self,
|
| 891 |
+
attention_mask: torch.Tensor,
|
| 892 |
+
input_tensor: torch.Tensor,
|
| 893 |
+
cache_position: torch.Tensor,
|
| 894 |
+
past_key_values: Cache,
|
| 895 |
+
output_attentions: bool,
|
| 896 |
+
):
|
| 897 |
+
if self.config._attn_implementation == "flash_attention_2":
|
| 898 |
+
if attention_mask is not None and (attention_mask == 0.0).any():
|
| 899 |
+
return attention_mask
|
| 900 |
+
return None
|
| 901 |
+
|
| 902 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
| 903 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
| 904 |
+
# to infer the attention mask.
|
| 905 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 906 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
| 907 |
+
|
| 908 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
| 909 |
+
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
| 910 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
| 911 |
+
attention_mask,
|
| 912 |
+
inputs_embeds=input_tensor,
|
| 913 |
+
past_key_values_length=past_seen_tokens,
|
| 914 |
+
is_training=self.training,
|
| 915 |
+
):
|
| 916 |
+
return None
|
| 917 |
+
|
| 918 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
| 919 |
+
sequence_length = input_tensor.shape[1]
|
| 920 |
+
if using_static_cache:
|
| 921 |
+
target_length = past_key_values.get_max_cache_shape()
|
| 922 |
+
else:
|
| 923 |
+
target_length = (
|
| 924 |
+
attention_mask.shape[-1]
|
| 925 |
+
if isinstance(attention_mask, torch.Tensor)
|
| 926 |
+
else past_seen_tokens + sequence_length + 1
|
| 927 |
+
)
|
| 928 |
+
|
| 929 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
| 930 |
+
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
|
| 931 |
+
attention_mask,
|
| 932 |
+
sequence_length=sequence_length,
|
| 933 |
+
target_length=target_length,
|
| 934 |
+
dtype=dtype,
|
| 935 |
+
device=device,
|
| 936 |
+
cache_position=cache_position,
|
| 937 |
+
batch_size=input_tensor.shape[0],
|
| 938 |
+
)
|
| 939 |
+
|
| 940 |
+
if (
|
| 941 |
+
self.config._attn_implementation == "sdpa"
|
| 942 |
+
and attention_mask is not None
|
| 943 |
+
and attention_mask.device.type == "cuda"
|
| 944 |
+
and not output_attentions
|
| 945 |
+
):
|
| 946 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
| 947 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
| 948 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
| 949 |
+
min_dtype = torch.finfo(dtype).min
|
| 950 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
| 951 |
+
|
| 952 |
+
return causal_mask
|
| 953 |
+
|
| 954 |
+
@staticmethod
|
| 955 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
| 956 |
+
attention_mask: torch.Tensor,
|
| 957 |
+
sequence_length: int,
|
| 958 |
+
target_length: int,
|
| 959 |
+
dtype: torch.dtype,
|
| 960 |
+
device: torch.device,
|
| 961 |
+
cache_position: torch.Tensor,
|
| 962 |
+
batch_size: int,
|
| 963 |
+
**kwargs,
|
| 964 |
+
):
|
| 965 |
+
"""
|
| 966 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
| 967 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
| 968 |
+
|
| 969 |
+
Args:
|
| 970 |
+
attention_mask (`torch.Tensor`):
|
| 971 |
+
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
|
| 972 |
+
`(batch_size, 1, query_length, key_value_length)`.
|
| 973 |
+
sequence_length (`int`):
|
| 974 |
+
The sequence length being processed.
|
| 975 |
+
target_length (`int`):
|
| 976 |
+
The target length: when generating with static cache, the mask should be as long as the static cache,
|
| 977 |
+
to account for the 0 padding, the part of the cache that is not filled yet.
|
| 978 |
+
dtype (`torch.dtype`):
|
| 979 |
+
The dtype to use for the 4D attention mask.
|
| 980 |
+
device (`torch.device`):
|
| 981 |
+
The device to plcae the 4D attention mask on.
|
| 982 |
+
cache_position (`torch.Tensor`):
|
| 983 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
| 984 |
+
batch_size (`torch.Tensor`):
|
| 985 |
+
Batch size.
|
| 986 |
+
"""
|
| 987 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
| 988 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
| 989 |
+
causal_mask = attention_mask
|
| 990 |
+
else:
|
| 991 |
+
min_dtype = torch.finfo(dtype).min
|
| 992 |
+
causal_mask = torch.full(
|
| 993 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
| 994 |
+
)
|
| 995 |
+
if sequence_length != 1:
|
| 996 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
| 997 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
| 998 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
| 999 |
+
if attention_mask is not None:
|
| 1000 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
| 1001 |
+
mask_length = attention_mask.shape[-1]
|
| 1002 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
| 1003 |
+
padding_mask = padding_mask == 0
|
| 1004 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
| 1005 |
+
padding_mask, min_dtype
|
| 1006 |
+
)
|
| 1007 |
+
|
| 1008 |
+
return causal_mask
|
| 1009 |
+
|
| 1010 |
+
|
| 1011 |
+
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
|
| 1012 |
+
|
| 1013 |
+
|
| 1014 |
+
class DiffLlamaForCausalLM(DiffLlamaPreTrainedModel, GenerationMixin):
|
| 1015 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 1016 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
| 1017 |
+
|
| 1018 |
+
def __init__(self, config):
|
| 1019 |
+
super().__init__(config)
|
| 1020 |
+
self.model = DiffLlamaModel(config)
|
| 1021 |
+
self.vocab_size = config.vocab_size
|
| 1022 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1023 |
+
|
| 1024 |
+
# Initialize weights and apply final processing
|
| 1025 |
+
self.post_init()
|
| 1026 |
+
|
| 1027 |
+
def get_input_embeddings(self):
|
| 1028 |
+
return self.model.embed_tokens
|
| 1029 |
+
|
| 1030 |
+
def set_input_embeddings(self, value):
|
| 1031 |
+
self.model.embed_tokens = value
|
| 1032 |
+
|
| 1033 |
+
def get_output_embeddings(self):
|
| 1034 |
+
return self.lm_head
|
| 1035 |
+
|
| 1036 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1037 |
+
self.lm_head = new_embeddings
|
| 1038 |
+
|
| 1039 |
+
def set_decoder(self, decoder):
|
| 1040 |
+
self.model = decoder
|
| 1041 |
+
|
| 1042 |
+
def get_decoder(self):
|
| 1043 |
+
return self.model
|
| 1044 |
+
|
| 1045 |
+
@add_start_docstrings_to_model_forward(DIFFLLAMA_INPUTS_DOCSTRING)
|
| 1046 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
| 1047 |
+
def forward(
|
| 1048 |
+
self,
|
| 1049 |
+
input_ids: torch.LongTensor = None,
|
| 1050 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1051 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1052 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 1053 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1054 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1055 |
+
use_cache: Optional[bool] = None,
|
| 1056 |
+
output_attentions: Optional[bool] = None,
|
| 1057 |
+
output_hidden_states: Optional[bool] = None,
|
| 1058 |
+
return_dict: Optional[bool] = None,
|
| 1059 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 1060 |
+
num_logits_to_keep: int = 0,
|
| 1061 |
+
**kwargs: Unpack[KwargsForCausalLM],
|
| 1062 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 1063 |
+
r"""
|
| 1064 |
+
Args:
|
| 1065 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1066 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1067 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1068 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1069 |
+
|
| 1070 |
+
num_logits_to_keep (`int`, *optional*):
|
| 1071 |
+
Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
|
| 1072 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
| 1073 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
| 1074 |
+
|
| 1075 |
+
Returns:
|
| 1076 |
+
|
| 1077 |
+
Example:
|
| 1078 |
+
|
| 1079 |
+
```python
|
| 1080 |
+
>>> from transformers import AutoTokenizer, DiffLlamaForCausalLM
|
| 1081 |
+
|
| 1082 |
+
>>> model = DiffLlamaForCausalLM.from_pretrained("google/diffllama-7b")
|
| 1083 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/diffllama-7b")
|
| 1084 |
+
|
| 1085 |
+
>>> prompt = "What is your favorite condiment?"
|
| 1086 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 1087 |
+
|
| 1088 |
+
>>> # Generate
|
| 1089 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 1090 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 1091 |
+
"What is your favorite condiment?"
|
| 1092 |
+
```"""
|
| 1093 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1094 |
+
output_hidden_states = (
|
| 1095 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1096 |
+
)
|
| 1097 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1098 |
+
|
| 1099 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 1100 |
+
outputs = self.model(
|
| 1101 |
+
input_ids=input_ids,
|
| 1102 |
+
attention_mask=attention_mask,
|
| 1103 |
+
position_ids=position_ids,
|
| 1104 |
+
past_key_values=past_key_values,
|
| 1105 |
+
inputs_embeds=inputs_embeds,
|
| 1106 |
+
use_cache=use_cache,
|
| 1107 |
+
output_attentions=output_attentions,
|
| 1108 |
+
output_hidden_states=output_hidden_states,
|
| 1109 |
+
return_dict=return_dict,
|
| 1110 |
+
cache_position=cache_position,
|
| 1111 |
+
**kwargs,
|
| 1112 |
+
)
|
| 1113 |
+
|
| 1114 |
+
hidden_states = outputs[0]
|
| 1115 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 1116 |
+
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|
| 1117 |
+
|
| 1118 |
+
loss = None
|
| 1119 |
+
if labels is not None:
|
| 1120 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 1121 |
+
|
| 1122 |
+
if not return_dict:
|
| 1123 |
+
output = (logits,) + outputs[1:]
|
| 1124 |
+
return (loss,) + output if loss is not None else output
|
| 1125 |
+
|
| 1126 |
+
return CausalLMOutputWithPast(
|
| 1127 |
+
loss=loss,
|
| 1128 |
+
logits=logits,
|
| 1129 |
+
past_key_values=outputs.past_key_values,
|
| 1130 |
+
hidden_states=outputs.hidden_states,
|
| 1131 |
+
attentions=outputs.attentions,
|
| 1132 |
+
)
|
| 1133 |
+
|
| 1134 |
+
|
| 1135 |
+
@add_start_docstrings(
|
| 1136 |
+
"""
|
| 1137 |
+
The DiffLlama Model transformer with a sequence classification head on top (linear layer).
|
| 1138 |
+
|
| 1139 |
+
[`DiffLlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
| 1140 |
+
(e.g. GPT-2) do.
|
| 1141 |
+
|
| 1142 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
| 1143 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
| 1144 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
| 1145 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
| 1146 |
+
each row of the batch).
|
| 1147 |
+
""",
|
| 1148 |
+
DIFFLLAMA_START_DOCSTRING,
|
| 1149 |
+
)
|
| 1150 |
+
class DiffLlamaForSequenceClassification(DiffLlamaPreTrainedModel):
|
| 1151 |
+
def __init__(self, config):
|
| 1152 |
+
super().__init__(config)
|
| 1153 |
+
self.num_labels = config.num_labels
|
| 1154 |
+
self.model = DiffLlamaModel(config)
|
| 1155 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
| 1156 |
+
|
| 1157 |
+
# Initialize weights and apply final processing
|
| 1158 |
+
self.post_init()
|
| 1159 |
+
|
| 1160 |
+
def get_input_embeddings(self):
|
| 1161 |
+
return self.model.embed_tokens
|
| 1162 |
+
|
| 1163 |
+
def set_input_embeddings(self, value):
|
| 1164 |
+
self.model.embed_tokens = value
|
| 1165 |
+
|
| 1166 |
+
@add_start_docstrings_to_model_forward(DIFFLLAMA_INPUTS_DOCSTRING)
|
| 1167 |
+
def forward(
|
| 1168 |
+
self,
|
| 1169 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1170 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1171 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1172 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 1173 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1174 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1175 |
+
use_cache: Optional[bool] = None,
|
| 1176 |
+
output_attentions: Optional[bool] = None,
|
| 1177 |
+
output_hidden_states: Optional[bool] = None,
|
| 1178 |
+
return_dict: Optional[bool] = None,
|
| 1179 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
| 1180 |
+
r"""
|
| 1181 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1182 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1183 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1184 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1185 |
+
"""
|
| 1186 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1187 |
+
|
| 1188 |
+
transformer_outputs = self.model(
|
| 1189 |
+
input_ids,
|
| 1190 |
+
attention_mask=attention_mask,
|
| 1191 |
+
position_ids=position_ids,
|
| 1192 |
+
past_key_values=past_key_values,
|
| 1193 |
+
inputs_embeds=inputs_embeds,
|
| 1194 |
+
use_cache=use_cache,
|
| 1195 |
+
output_attentions=output_attentions,
|
| 1196 |
+
output_hidden_states=output_hidden_states,
|
| 1197 |
+
return_dict=return_dict,
|
| 1198 |
+
)
|
| 1199 |
+
hidden_states = transformer_outputs[0]
|
| 1200 |
+
logits = self.score(hidden_states)
|
| 1201 |
+
|
| 1202 |
+
if input_ids is not None:
|
| 1203 |
+
batch_size = input_ids.shape[0]
|
| 1204 |
+
else:
|
| 1205 |
+
batch_size = inputs_embeds.shape[0]
|
| 1206 |
+
|
| 1207 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
| 1208 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
| 1209 |
+
if self.config.pad_token_id is None:
|
| 1210 |
+
sequence_lengths = -1
|
| 1211 |
+
else:
|
| 1212 |
+
if input_ids is not None:
|
| 1213 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
| 1214 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
| 1215 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
| 1216 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
| 1217 |
+
else:
|
| 1218 |
+
sequence_lengths = -1
|
| 1219 |
+
|
| 1220 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
| 1221 |
+
|
| 1222 |
+
loss = None
|
| 1223 |
+
if labels is not None:
|
| 1224 |
+
loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
|
| 1225 |
+
|
| 1226 |
+
if not return_dict:
|
| 1227 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
| 1228 |
+
return ((loss,) + output) if loss is not None else output
|
| 1229 |
+
|
| 1230 |
+
return SequenceClassifierOutputWithPast(
|
| 1231 |
+
loss=loss,
|
| 1232 |
+
logits=pooled_logits,
|
| 1233 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 1234 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1235 |
+
attentions=transformer_outputs.attentions,
|
| 1236 |
+
)
|
| 1237 |
+
|
| 1238 |
+
|
| 1239 |
+
@add_start_docstrings(
|
| 1240 |
+
"""
|
| 1241 |
+
The DiffLlama Model transformer with a span classification head on top for extractive question-answering tasks like
|
| 1242 |
+
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1243 |
+
""",
|
| 1244 |
+
DIFFLLAMA_START_DOCSTRING,
|
| 1245 |
+
)
|
| 1246 |
+
class DiffLlamaForQuestionAnswering(DiffLlamaPreTrainedModel):
|
| 1247 |
+
base_model_prefix = "transformer"
|
| 1248 |
+
|
| 1249 |
+
def __init__(self, config):
|
| 1250 |
+
super().__init__(config)
|
| 1251 |
+
self.transformer = DiffLlamaModel(config)
|
| 1252 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
| 1253 |
+
|
| 1254 |
+
# Initialize weights and apply final processing
|
| 1255 |
+
self.post_init()
|
| 1256 |
+
|
| 1257 |
+
def get_input_embeddings(self):
|
| 1258 |
+
return self.transformer.embed_tokens
|
| 1259 |
+
|
| 1260 |
+
def set_input_embeddings(self, value):
|
| 1261 |
+
self.transformer.embed_tokens = value
|
| 1262 |
+
|
| 1263 |
+
@add_start_docstrings_to_model_forward(DIFFLLAMA_INPUTS_DOCSTRING)
|
| 1264 |
+
def forward(
|
| 1265 |
+
self,
|
| 1266 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1267 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1268 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1269 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 1270 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1271 |
+
start_positions: Optional[torch.LongTensor] = None,
|
| 1272 |
+
end_positions: Optional[torch.LongTensor] = None,
|
| 1273 |
+
output_attentions: Optional[bool] = None,
|
| 1274 |
+
output_hidden_states: Optional[bool] = None,
|
| 1275 |
+
return_dict: Optional[bool] = None,
|
| 1276 |
+
**kwargs,
|
| 1277 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
| 1278 |
+
r"""
|
| 1279 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1280 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1281 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1282 |
+
are not taken into account for computing the loss.
|
| 1283 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1284 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1285 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1286 |
+
are not taken into account for computing the loss.
|
| 1287 |
+
"""
|
| 1288 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1289 |
+
|
| 1290 |
+
outputs = self.transformer(
|
| 1291 |
+
input_ids,
|
| 1292 |
+
attention_mask=attention_mask,
|
| 1293 |
+
position_ids=position_ids,
|
| 1294 |
+
past_key_values=past_key_values,
|
| 1295 |
+
inputs_embeds=inputs_embeds,
|
| 1296 |
+
output_attentions=output_attentions,
|
| 1297 |
+
output_hidden_states=output_hidden_states,
|
| 1298 |
+
return_dict=return_dict,
|
| 1299 |
+
)
|
| 1300 |
+
|
| 1301 |
+
sequence_output = outputs[0]
|
| 1302 |
+
|
| 1303 |
+
logits = self.qa_outputs(sequence_output)
|
| 1304 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1305 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 1306 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 1307 |
+
|
| 1308 |
+
loss = None
|
| 1309 |
+
if start_positions is not None and end_positions is not None:
|
| 1310 |
+
loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
|
| 1311 |
+
|
| 1312 |
+
if not return_dict:
|
| 1313 |
+
output = (start_logits, end_logits) + outputs[2:]
|
| 1314 |
+
return ((loss,) + output) if loss is not None else output
|
| 1315 |
+
|
| 1316 |
+
return QuestionAnsweringModelOutput(
|
| 1317 |
+
loss=loss,
|
| 1318 |
+
start_logits=start_logits,
|
| 1319 |
+
end_logits=end_logits,
|
| 1320 |
+
hidden_states=outputs.hidden_states,
|
| 1321 |
+
attentions=outputs.attentions,
|
| 1322 |
+
)
|
| 1323 |
+
|
| 1324 |
+
|
| 1325 |
+
@add_start_docstrings(
|
| 1326 |
+
"""
|
| 1327 |
+
The DiffLlama Model transformer with a token classification head on top (a linear layer on top of the hidden-states
|
| 1328 |
+
output) e.g. for Named-Entity-Recognition (NER) tasks.
|
| 1329 |
+
""",
|
| 1330 |
+
DIFFLLAMA_START_DOCSTRING,
|
| 1331 |
+
)
|
| 1332 |
+
class DiffLlamaForTokenClassification(DiffLlamaPreTrainedModel):
|
| 1333 |
+
def __init__(self, config):
|
| 1334 |
+
super().__init__(config)
|
| 1335 |
+
self.num_labels = config.num_labels
|
| 1336 |
+
self.model = DiffLlamaModel(config)
|
| 1337 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
| 1338 |
+
classifier_dropout = config.classifier_dropout
|
| 1339 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
| 1340 |
+
classifier_dropout = config.hidden_dropout
|
| 1341 |
+
else:
|
| 1342 |
+
classifier_dropout = 0.1
|
| 1343 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 1344 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels)
|
| 1345 |
+
|
| 1346 |
+
# Initialize weights and apply final processing
|
| 1347 |
+
self.post_init()
|
| 1348 |
+
|
| 1349 |
+
def get_input_embeddings(self):
|
| 1350 |
+
return self.model.embed_tokens
|
| 1351 |
+
|
| 1352 |
+
def set_input_embeddings(self, value):
|
| 1353 |
+
self.model.embed_tokens = value
|
| 1354 |
+
|
| 1355 |
+
@add_start_docstrings_to_model_forward(DIFFLLAMA_INPUTS_DOCSTRING)
|
| 1356 |
+
@add_code_sample_docstrings(
|
| 1357 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1358 |
+
output_type=TokenClassifierOutput,
|
| 1359 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1360 |
+
)
|
| 1361 |
+
def forward(
|
| 1362 |
+
self,
|
| 1363 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1364 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1365 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1366 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1367 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1368 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1369 |
+
use_cache: Optional[bool] = None,
|
| 1370 |
+
output_attentions: Optional[bool] = None,
|
| 1371 |
+
output_hidden_states: Optional[bool] = None,
|
| 1372 |
+
return_dict: Optional[bool] = None,
|
| 1373 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
| 1374 |
+
r"""
|
| 1375 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1376 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1377 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1378 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1379 |
+
"""
|
| 1380 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1381 |
+
|
| 1382 |
+
outputs = self.model(
|
| 1383 |
+
input_ids,
|
| 1384 |
+
attention_mask=attention_mask,
|
| 1385 |
+
position_ids=position_ids,
|
| 1386 |
+
past_key_values=past_key_values,
|
| 1387 |
+
inputs_embeds=inputs_embeds,
|
| 1388 |
+
use_cache=use_cache,
|
| 1389 |
+
output_attentions=output_attentions,
|
| 1390 |
+
output_hidden_states=output_hidden_states,
|
| 1391 |
+
return_dict=return_dict,
|
| 1392 |
+
)
|
| 1393 |
+
sequence_output = outputs[0]
|
| 1394 |
+
sequence_output = self.dropout(sequence_output)
|
| 1395 |
+
logits = self.score(sequence_output)
|
| 1396 |
+
|
| 1397 |
+
loss = None
|
| 1398 |
+
if labels is not None:
|
| 1399 |
+
loss = self.loss_function(logits, labels, self.config)
|
| 1400 |
+
|
| 1401 |
+
if not return_dict:
|
| 1402 |
+
output = (logits,) + outputs[2:]
|
| 1403 |
+
return ((loss,) + output) if loss is not None else output
|
| 1404 |
+
|
| 1405 |
+
return TokenClassifierOutput(
|
| 1406 |
+
loss=loss,
|
| 1407 |
+
logits=logits,
|
| 1408 |
+
hidden_states=outputs.hidden_states,
|
| 1409 |
+
attentions=outputs.attentions,
|
| 1410 |
+
)
|
| 1411 |
+
|
| 1412 |
+
|
| 1413 |
+
__all__ = [
|
| 1414 |
+
"DiffLlamaPreTrainedModel",
|
| 1415 |
+
"DiffLlamaModel",
|
| 1416 |
+
"DiffLlamaForCausalLM",
|
| 1417 |
+
"DiffLlamaForSequenceClassification",
|
| 1418 |
+
"DiffLlamaForQuestionAnswering",
|
| 1419 |
+
"DiffLlamaForTokenClassification",
|
| 1420 |
+
]
|
janus/lib/python3.10/site-packages/transformers/models/diffllama/modular_diffllama.py
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 weak-kajuma and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on Llama implementations in this library and Microsoft's
|
| 5 |
+
# Differential Transformer implementations.
|
| 6 |
+
|
| 7 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 8 |
+
# you may not use this file except in compliance with the License.
|
| 9 |
+
# You may obtain a copy of the License at
|
| 10 |
+
#
|
| 11 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 12 |
+
#
|
| 13 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 14 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 15 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 16 |
+
# See the License for the specific language governing permissions and
|
| 17 |
+
# limitations under the License.
|
| 18 |
+
import math
|
| 19 |
+
from typing import Optional, Tuple
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.utils.checkpoint
|
| 23 |
+
from torch import nn
|
| 24 |
+
|
| 25 |
+
from ...cache_utils import Cache, StaticCache
|
| 26 |
+
from ...modeling_flash_attention_utils import _flash_attention_forward
|
| 27 |
+
from ...utils import (
|
| 28 |
+
is_flash_attn_greater_or_equal_2_10,
|
| 29 |
+
logging,
|
| 30 |
+
)
|
| 31 |
+
from ..gemma.modeling_gemma import GemmaForCausalLM
|
| 32 |
+
from ..llama.modeling_llama import (
|
| 33 |
+
LlamaDecoderLayer,
|
| 34 |
+
LlamaForQuestionAnswering,
|
| 35 |
+
LlamaForSequenceClassification,
|
| 36 |
+
LlamaForTokenClassification,
|
| 37 |
+
LlamaModel,
|
| 38 |
+
LlamaPreTrainedModel,
|
| 39 |
+
apply_rotary_pos_emb,
|
| 40 |
+
repeat_kv,
|
| 41 |
+
)
|
| 42 |
+
from ..mistral.modeling_mistral import MistralMLP
|
| 43 |
+
from .configuration_diffllama import DiffLlamaConfig
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__)
|
| 47 |
+
|
| 48 |
+
_CHECKPOINT_FOR_DOC = "kajuma/DiffLlama-0.3B-handcut"
|
| 49 |
+
_CONFIG_FOR_DOC = "DiffLlamaConfig"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class DiffLlamaMLP(MistralMLP):
|
| 53 |
+
pass
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def lambda_init_fn(layer_idx):
|
| 57 |
+
return 0.8 - 0.6 * math.exp(-0.3 * layer_idx)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class DiffLlamaAttention(nn.Module):
|
| 61 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 62 |
+
|
| 63 |
+
def __init__(self, config: DiffLlamaConfig, layer_idx: Optional[int] = None):
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.config = config
|
| 66 |
+
self.layer_idx = layer_idx
|
| 67 |
+
if layer_idx is None:
|
| 68 |
+
logger.warning_once(
|
| 69 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
| 70 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
| 71 |
+
"when creating this class."
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
self.attention_dropout = config.attention_dropout
|
| 75 |
+
self.hidden_size = config.hidden_size
|
| 76 |
+
self.num_heads = config.num_attention_heads
|
| 77 |
+
self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
|
| 78 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 79 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 80 |
+
# under this are not used
|
| 81 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 82 |
+
self.rope_theta = config.rope_theta
|
| 83 |
+
self.is_causal = True
|
| 84 |
+
|
| 85 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
|
| 86 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
| 87 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
| 88 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
|
| 89 |
+
|
| 90 |
+
self.lambda_init = lambda_init_fn(layer_idx)
|
| 91 |
+
self.lambda_q1 = nn.Parameter(torch.normal(0, config.lambda_std_dev, size=(self.head_dim,)))
|
| 92 |
+
self.lambda_k1 = nn.Parameter(torch.normal(0, config.lambda_std_dev, size=(self.head_dim,)))
|
| 93 |
+
self.lambda_q2 = nn.Parameter(torch.normal(0, config.lambda_std_dev, size=(self.head_dim,)))
|
| 94 |
+
self.lambda_k2 = nn.Parameter(torch.normal(0, config.lambda_std_dev, size=(self.head_dim,)))
|
| 95 |
+
self.groupnorm = nn.RMSNorm(2 * self.head_dim, eps=config.rms_norm_eps, elementwise_affine=False)
|
| 96 |
+
|
| 97 |
+
def forward(
|
| 98 |
+
self,
|
| 99 |
+
hidden_states: torch.Tensor,
|
| 100 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
| 101 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 102 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 103 |
+
past_key_value: Optional[Cache] = None,
|
| 104 |
+
output_attentions: bool = False,
|
| 105 |
+
use_cache: bool = False,
|
| 106 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 107 |
+
**kwargs,
|
| 108 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 109 |
+
bsz, target_len, _ = hidden_states.size()
|
| 110 |
+
q_len = target_len
|
| 111 |
+
|
| 112 |
+
query_states = self.q_proj(hidden_states)
|
| 113 |
+
key_states = self.k_proj(hidden_states)
|
| 114 |
+
value_states = self.v_proj(hidden_states)
|
| 115 |
+
|
| 116 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 117 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 118 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 119 |
+
|
| 120 |
+
cos, sin = position_embeddings
|
| 121 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 122 |
+
|
| 123 |
+
if past_key_value is not None:
|
| 124 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 125 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 126 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 127 |
+
|
| 128 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 129 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 130 |
+
value_states = torch.cat(torch.chunk(value_states, 2, dim=1), dim=-1)
|
| 131 |
+
value_states = value_states.repeat(1, 2, 1, 1)
|
| 132 |
+
|
| 133 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 134 |
+
|
| 135 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
| 136 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 137 |
+
attn_weights = attn_weights + causal_mask
|
| 138 |
+
|
| 139 |
+
# upcast attention to fp32
|
| 140 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 141 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
| 142 |
+
lambda_1 = torch.exp(torch.sum(self.lambda_q1 * self.lambda_k1, dim=-1, dtype=torch.float32)).to(
|
| 143 |
+
query_states.dtype
|
| 144 |
+
)
|
| 145 |
+
lambda_2 = torch.exp(torch.sum(self.lambda_q2 * self.lambda_k2, dim=-1, dtype=torch.float32)).to(
|
| 146 |
+
query_states.dtype
|
| 147 |
+
)
|
| 148 |
+
lambda_full = lambda_1 - lambda_2 + self.lambda_init
|
| 149 |
+
|
| 150 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 151 |
+
attn_output1, attn_output2 = torch.chunk(attn_output, 2, dim=1)
|
| 152 |
+
|
| 153 |
+
attn_output = attn_output1 - lambda_full * attn_output2
|
| 154 |
+
attn_output = (1 - self.lambda_init) * self.groupnorm(attn_output)
|
| 155 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 156 |
+
attn_output = attn_output.reshape(bsz, q_len, -1)
|
| 157 |
+
|
| 158 |
+
attn_output = self.o_proj(attn_output)
|
| 159 |
+
|
| 160 |
+
if not output_attentions:
|
| 161 |
+
attn_weights = None
|
| 162 |
+
|
| 163 |
+
return attn_output, attn_weights
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class DiffLlamaFlashAttention2(DiffLlamaAttention):
|
| 167 |
+
"""
|
| 168 |
+
DiffLlama flash attention module. This module inherits from `DiffLlamaAttention` as the weights of the module stays
|
| 169 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
| 170 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
def __init__(self, *args, **kwargs):
|
| 174 |
+
super().__init__(*args, **kwargs)
|
| 175 |
+
|
| 176 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
| 177 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
| 178 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
| 179 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
| 180 |
+
|
| 181 |
+
def forward(
|
| 182 |
+
self,
|
| 183 |
+
hidden_states: torch.Tensor,
|
| 184 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
| 185 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 186 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 187 |
+
past_key_value: Optional[Cache] = None,
|
| 188 |
+
output_attentions: bool = False,
|
| 189 |
+
use_cache: bool = False,
|
| 190 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 191 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 192 |
+
if isinstance(past_key_value, StaticCache):
|
| 193 |
+
raise ValueError(
|
| 194 |
+
"`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
|
| 195 |
+
"make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
output_attentions = False
|
| 199 |
+
|
| 200 |
+
bsz, q_len, _ = hidden_states.size()
|
| 201 |
+
|
| 202 |
+
query_states = self.q_proj(hidden_states)
|
| 203 |
+
key_states = self.k_proj(hidden_states)
|
| 204 |
+
value_states = self.v_proj(hidden_states)
|
| 205 |
+
|
| 206 |
+
# Flash attention requires the input to have the shape
|
| 207 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
| 208 |
+
# therefore we just need to keep the original shape
|
| 209 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 210 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 211 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 212 |
+
|
| 213 |
+
if position_embeddings is None:
|
| 214 |
+
logger.warning_once(
|
| 215 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
| 216 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
| 217 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
|
| 218 |
+
"removed and `position_embeddings` will be mandatory."
|
| 219 |
+
)
|
| 220 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 221 |
+
else:
|
| 222 |
+
cos, sin = position_embeddings
|
| 223 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 224 |
+
|
| 225 |
+
if past_key_value is not None:
|
| 226 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 227 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 228 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 229 |
+
|
| 230 |
+
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
|
| 231 |
+
# to be able to avoid many of these transpose/reshape/view.
|
| 232 |
+
query_states = query_states.transpose(1, 2)
|
| 233 |
+
key_states = key_states.transpose(1, 2)
|
| 234 |
+
value_states = value_states.transpose(1, 2)
|
| 235 |
+
|
| 236 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
| 237 |
+
|
| 238 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
| 239 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
| 240 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
| 241 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
| 242 |
+
# in fp32. (DiffLlamaRMSNorm handles it correctly)
|
| 243 |
+
|
| 244 |
+
input_dtype = query_states.dtype
|
| 245 |
+
if input_dtype == torch.float32:
|
| 246 |
+
if torch.is_autocast_enabled():
|
| 247 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
| 248 |
+
# Handle the case where the model is quantized
|
| 249 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
| 250 |
+
target_dtype = self.config._pre_quantization_dtype
|
| 251 |
+
else:
|
| 252 |
+
target_dtype = self.q_proj.weight.dtype
|
| 253 |
+
|
| 254 |
+
logger.warning_once(
|
| 255 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
| 256 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
| 257 |
+
f" {target_dtype}."
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
query_states = query_states.to(target_dtype)
|
| 261 |
+
key_states = key_states.to(target_dtype)
|
| 262 |
+
value_states = value_states.to(target_dtype)
|
| 263 |
+
|
| 264 |
+
value_states1, value_states2 = torch.chunk(value_states, 2, dim=2)
|
| 265 |
+
value_states1 = value_states1.repeat(1, 1, 2, 1)
|
| 266 |
+
value_states2 = value_states2.repeat(1, 1, 2, 1)
|
| 267 |
+
|
| 268 |
+
attn_output1 = _flash_attention_forward(
|
| 269 |
+
query_states,
|
| 270 |
+
key_states,
|
| 271 |
+
value_states1,
|
| 272 |
+
attention_mask,
|
| 273 |
+
q_len,
|
| 274 |
+
position_ids=position_ids,
|
| 275 |
+
dropout=dropout_rate,
|
| 276 |
+
sliding_window=getattr(self, "sliding_window", None),
|
| 277 |
+
use_top_left_mask=self._flash_attn_uses_top_left_mask,
|
| 278 |
+
is_causal=self.is_causal,
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
attn_output2 = _flash_attention_forward(
|
| 282 |
+
query_states,
|
| 283 |
+
key_states,
|
| 284 |
+
value_states2,
|
| 285 |
+
attention_mask,
|
| 286 |
+
q_len,
|
| 287 |
+
position_ids=position_ids,
|
| 288 |
+
dropout=dropout_rate,
|
| 289 |
+
sliding_window=getattr(self, "sliding_window", None),
|
| 290 |
+
use_top_left_mask=self._flash_attn_uses_top_left_mask,
|
| 291 |
+
is_causal=self.is_causal,
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
attn_output = torch.cat([attn_output1, attn_output2], dim=-1)
|
| 295 |
+
attn_output1, attn_output2 = torch.chunk(attn_output, 2, dim=2)
|
| 296 |
+
|
| 297 |
+
lambda_1 = torch.exp(torch.sum(self.lambda_q1 * self.lambda_k1, dim=-1, dtype=torch.float32)).to(
|
| 298 |
+
query_states.dtype
|
| 299 |
+
)
|
| 300 |
+
lambda_2 = torch.exp(torch.sum(self.lambda_q2 * self.lambda_k2, dim=-1, dtype=torch.float32)).to(
|
| 301 |
+
query_states.dtype
|
| 302 |
+
)
|
| 303 |
+
lambda_full = lambda_1 - lambda_2 + self.lambda_init
|
| 304 |
+
|
| 305 |
+
attn_output = attn_output1 - lambda_full * attn_output2
|
| 306 |
+
attn_output = (1 - self.lambda_init) * self.groupnorm(attn_output)
|
| 307 |
+
attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
|
| 308 |
+
attn_output = self.o_proj(attn_output)
|
| 309 |
+
|
| 310 |
+
if not output_attentions:
|
| 311 |
+
attn_weights = None
|
| 312 |
+
|
| 313 |
+
return attn_output, attn_weights
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class DiffLlamaSdpaAttention(DiffLlamaAttention):
|
| 317 |
+
"""
|
| 318 |
+
DiffLlama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
| 319 |
+
`DiffLlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
| 320 |
+
SDPA API.
|
| 321 |
+
"""
|
| 322 |
+
|
| 323 |
+
# Adapted from DiffLlamaAttention.forward
|
| 324 |
+
def forward(
|
| 325 |
+
self,
|
| 326 |
+
hidden_states: torch.Tensor,
|
| 327 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
| 328 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 329 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 330 |
+
past_key_value: Optional[Cache] = None,
|
| 331 |
+
output_attentions: bool = False,
|
| 332 |
+
use_cache: bool = False,
|
| 333 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 334 |
+
**kwargs,
|
| 335 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 336 |
+
if output_attentions:
|
| 337 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
| 338 |
+
logger.warning_once(
|
| 339 |
+
"DiffLlamaModel is using DiffLlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
| 340 |
+
'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 341 |
+
)
|
| 342 |
+
return super().forward(
|
| 343 |
+
hidden_states=hidden_states,
|
| 344 |
+
attention_mask=attention_mask,
|
| 345 |
+
position_ids=position_ids,
|
| 346 |
+
past_key_value=past_key_value,
|
| 347 |
+
output_attentions=output_attentions,
|
| 348 |
+
use_cache=use_cache,
|
| 349 |
+
cache_position=cache_position,
|
| 350 |
+
position_embeddings=position_embeddings,
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
bsz, q_len, _ = hidden_states.size()
|
| 354 |
+
|
| 355 |
+
query_states = self.q_proj(hidden_states)
|
| 356 |
+
key_states = self.k_proj(hidden_states)
|
| 357 |
+
value_states = self.v_proj(hidden_states)
|
| 358 |
+
|
| 359 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 360 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 361 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 362 |
+
|
| 363 |
+
cos, sin = position_embeddings
|
| 364 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 365 |
+
|
| 366 |
+
if past_key_value is not None:
|
| 367 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 368 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 369 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 370 |
+
|
| 371 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 372 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 373 |
+
value_states = torch.cat(torch.chunk(value_states, 2, dim=1), dim=-1)
|
| 374 |
+
value_states = value_states.repeat(1, 2, 1, 1)
|
| 375 |
+
|
| 376 |
+
causal_mask = attention_mask
|
| 377 |
+
if attention_mask is not None:
|
| 378 |
+
causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
|
| 379 |
+
|
| 380 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
| 381 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
| 382 |
+
if query_states.device.type == "cuda" and causal_mask is not None:
|
| 383 |
+
query_states = query_states.contiguous()
|
| 384 |
+
key_states = key_states.contiguous()
|
| 385 |
+
value_states = value_states.contiguous()
|
| 386 |
+
|
| 387 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
|
| 388 |
+
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
|
| 389 |
+
is_causal = True if causal_mask is None and q_len > 1 else False
|
| 390 |
+
|
| 391 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
| 392 |
+
query_states,
|
| 393 |
+
key_states,
|
| 394 |
+
value_states,
|
| 395 |
+
attn_mask=causal_mask,
|
| 396 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
| 397 |
+
is_causal=is_causal,
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
attn_output1, attn_output2 = torch.chunk(attn_output, 2, dim=1)
|
| 401 |
+
|
| 402 |
+
lambda_1 = torch.exp(torch.sum(self.lambda_q1 * self.lambda_k1, dim=-1, dtype=torch.float32)).to(
|
| 403 |
+
query_states.dtype
|
| 404 |
+
)
|
| 405 |
+
lambda_2 = torch.exp(torch.sum(self.lambda_q2 * self.lambda_k2, dim=-1, dtype=torch.float32)).to(
|
| 406 |
+
query_states.dtype
|
| 407 |
+
)
|
| 408 |
+
lambda_full = lambda_1 - lambda_2 + self.lambda_init
|
| 409 |
+
|
| 410 |
+
attn_output = attn_output1 - lambda_full * attn_output2
|
| 411 |
+
attn_output = (1 - self.lambda_init) * self.groupnorm(attn_output)
|
| 412 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 413 |
+
attn_output = attn_output.view(bsz, q_len, -1)
|
| 414 |
+
attn_output = self.o_proj(attn_output)
|
| 415 |
+
|
| 416 |
+
return attn_output, None
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
DIFFLLAMA_ATTENTION_CLASSES = {
|
| 420 |
+
"eager": DiffLlamaAttention,
|
| 421 |
+
"flash_attention_2": DiffLlamaFlashAttention2,
|
| 422 |
+
"sdpa": DiffLlamaSdpaAttention,
|
| 423 |
+
}
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
class DiffLlamaDecoderLayer(LlamaDecoderLayer):
|
| 427 |
+
def __init__(self, config: DiffLlamaConfig, layer_idx: int):
|
| 428 |
+
super().__init__(config, layer_idx)
|
| 429 |
+
|
| 430 |
+
self.self_attn = DIFFLLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
class DiffLlamaPreTrainedModel(LlamaPreTrainedModel):
|
| 434 |
+
pass
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
class DiffLlamaModel(LlamaModel):
|
| 438 |
+
pass
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
class DiffLlamaForCausalLM(GemmaForCausalLM):
|
| 442 |
+
pass
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
class DiffLlamaForSequenceClassification(LlamaForSequenceClassification):
|
| 446 |
+
pass
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
class DiffLlamaForQuestionAnswering(LlamaForQuestionAnswering):
|
| 450 |
+
pass
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
class DiffLlamaForTokenClassification(LlamaForTokenClassification):
|
| 454 |
+
pass
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
__all__ = [
|
| 458 |
+
"DiffLlamaPreTrainedModel",
|
| 459 |
+
"DiffLlamaModel", # noqa: F822
|
| 460 |
+
"DiffLlamaForCausalLM",
|
| 461 |
+
"DiffLlamaForSequenceClassification",
|
| 462 |
+
"DiffLlamaForQuestionAnswering",
|
| 463 |
+
"DiffLlamaForTokenClassification",
|
| 464 |
+
]
|
janus/lib/python3.10/site-packages/transformers/models/granite/__pycache__/configuration_granite.cpython-310.pyc
ADDED
|
Binary file (7.44 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/granite/__pycache__/modeling_granite.cpython-310.pyc
ADDED
|
Binary file (30.3 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/granite/__pycache__/modular_granite.cpython-310.pyc
ADDED
|
Binary file (8.25 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/maskformer/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (706 Bytes). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/maskformer/__pycache__/configuration_maskformer.cpython-310.pyc
ADDED
|
Binary file (8.02 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/maskformer/__pycache__/configuration_maskformer_swin.cpython-310.pyc
ADDED
|
Binary file (6.34 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/maskformer/__pycache__/feature_extraction_maskformer.cpython-310.pyc
ADDED
|
Binary file (1.05 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/pegasus_x/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (546 Bytes). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/pegasus_x/__pycache__/configuration_pegasus_x.cpython-310.pyc
ADDED
|
Binary file (7 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/pegasus_x/__pycache__/modeling_pegasus_x.cpython-310.pyc
ADDED
|
Binary file (50.2 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/pegasus_x/configuration_pegasus_x.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022, Google and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PEGASUS-X model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class PegasusXConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`PegasusXModel`]. It is used to instantiate a
|
| 27 |
+
PEGASUS-X model according to the specified arguments, defining the model architecture. Instantiating a
|
| 28 |
+
configuration with the defaults will yield a similar configuration to that of the PEGASUS-X
|
| 29 |
+
[google/pegasus-x-large](https://huggingface.co/google/pegasus-x-large) architecture.
|
| 30 |
+
|
| 31 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 32 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
vocab_size (`int`, *optional*, defaults to 96103):
|
| 37 |
+
Vocabulary size of the PEGASUS-X model. Defines the number of different tokens that can be represented by
|
| 38 |
+
the `inputs_ids` passed when calling [`PegasusXModel`].
|
| 39 |
+
d_model (`int`, *optional*, defaults to 1024):
|
| 40 |
+
Dimension of the layers and the pooler layer.
|
| 41 |
+
encoder_layers (`int`, *optional*, defaults to 16):
|
| 42 |
+
Number of encoder layers.
|
| 43 |
+
decoder_layers (`int`, *optional*, defaults to 16):
|
| 44 |
+
Number of decoder layers.
|
| 45 |
+
encoder_attention_heads (`int`, *optional*, defaults to 16):
|
| 46 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 47 |
+
decoder_attention_heads (`int`, *optional*, defaults to 16):
|
| 48 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 49 |
+
decoder_ffn_dim (`int`, *optional*, defaults to 4096):
|
| 50 |
+
Dimension of the "intermediate" (often named feed-forward) layer in decoder.
|
| 51 |
+
encoder_ffn_dim (`int`, *optional*, defaults to 4096):
|
| 52 |
+
Dimension of the "intermediate" (often named feed-forward) layer in decoder.
|
| 53 |
+
activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 54 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 55 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 56 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 57 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 58 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 59 |
+
The dropout ratio for the attention probabilities.
|
| 60 |
+
activation_dropout (`float`, *optional*, defaults to 0.0):
|
| 61 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 62 |
+
max_position_embeddings (`int`, *optional*, defaults to 16384):
|
| 63 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 64 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 65 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 66 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 67 |
+
encoder_layerdrop (`float`, *optional*, defaults to 0.0):
|
| 68 |
+
The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
|
| 69 |
+
for more details.
|
| 70 |
+
decoder_layerdrop (`float`, *optional*, defaults to 0.0):
|
| 71 |
+
The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
|
| 72 |
+
for more details.
|
| 73 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 74 |
+
Whether or not the model should return the last key/values attentions (not used by all models)
|
| 75 |
+
forced_eos_token_id (`int`, *optional*, defaults to 1):
|
| 76 |
+
The id of the token to force as the last generated token when `max_length` is reached. Usually set to
|
| 77 |
+
`eos_token_id`.
|
| 78 |
+
num_global_tokens (`int`, *optional*, defaults to 128):
|
| 79 |
+
Number of global tokens to use for the encoder
|
| 80 |
+
block_size (`int`, *optional*, defaults to 512):
|
| 81 |
+
Block size for encoder local attention. Sequence length should be an exact multiple of block size.
|
| 82 |
+
block_size must be a multiple of 2 if stagger_local_block is True
|
| 83 |
+
stagger_local_block (`bool`, *optional*, defaults to `True`):
|
| 84 |
+
Whether to stagger every other local attention by half a block
|
| 85 |
+
|
| 86 |
+
Example:
|
| 87 |
+
|
| 88 |
+
```python
|
| 89 |
+
>>> from transformers import PegasusXConfig, PegasusXModel
|
| 90 |
+
|
| 91 |
+
>>> # Initializing a PEGASUS google/pegasus-x-large style configuration
|
| 92 |
+
>>> configuration = PegasusXConfig()
|
| 93 |
+
|
| 94 |
+
>>> # Initializing a model (with random weights) from the google/pegasus-x-large style configuration
|
| 95 |
+
>>> model = PegasusXModel(configuration)
|
| 96 |
+
|
| 97 |
+
>>> # Accessing the model configuration
|
| 98 |
+
>>> configuration = model.config
|
| 99 |
+
```"""
|
| 100 |
+
|
| 101 |
+
model_type = "pegasus_x"
|
| 102 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 103 |
+
attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
|
| 104 |
+
|
| 105 |
+
def __init__(
|
| 106 |
+
self,
|
| 107 |
+
vocab_size=96103,
|
| 108 |
+
max_position_embeddings=16384,
|
| 109 |
+
encoder_layers=16,
|
| 110 |
+
encoder_ffn_dim=4096,
|
| 111 |
+
encoder_attention_heads=16,
|
| 112 |
+
decoder_layers=16,
|
| 113 |
+
decoder_ffn_dim=4096,
|
| 114 |
+
decoder_attention_heads=16,
|
| 115 |
+
encoder_layerdrop=0.0,
|
| 116 |
+
decoder_layerdrop=0.0,
|
| 117 |
+
use_cache=True,
|
| 118 |
+
is_encoder_decoder=True,
|
| 119 |
+
activation_function="gelu",
|
| 120 |
+
d_model=1024,
|
| 121 |
+
dropout=0.1,
|
| 122 |
+
attention_dropout=0.0,
|
| 123 |
+
activation_dropout=0.0,
|
| 124 |
+
init_std=0.02,
|
| 125 |
+
decoder_start_token_id=0,
|
| 126 |
+
scale_embedding=True,
|
| 127 |
+
pad_token_id=0,
|
| 128 |
+
eos_token_id=1,
|
| 129 |
+
forced_eos_token_id=1,
|
| 130 |
+
num_global_tokens=32,
|
| 131 |
+
block_size=512,
|
| 132 |
+
stagger_local_blocks=True,
|
| 133 |
+
**kwargs,
|
| 134 |
+
):
|
| 135 |
+
self.vocab_size = vocab_size
|
| 136 |
+
self.max_position_embeddings = max_position_embeddings
|
| 137 |
+
self.d_model = d_model
|
| 138 |
+
self.encoder_ffn_dim = encoder_ffn_dim
|
| 139 |
+
self.encoder_layers = encoder_layers
|
| 140 |
+
self.encoder_attention_heads = encoder_attention_heads
|
| 141 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 142 |
+
self.decoder_layers = decoder_layers
|
| 143 |
+
self.decoder_attention_heads = decoder_attention_heads
|
| 144 |
+
self.dropout = dropout
|
| 145 |
+
self.attention_dropout = attention_dropout
|
| 146 |
+
self.activation_dropout = activation_dropout
|
| 147 |
+
self.activation_function = activation_function
|
| 148 |
+
self.init_std = init_std
|
| 149 |
+
self.encoder_layerdrop = encoder_layerdrop
|
| 150 |
+
self.decoder_layerdrop = decoder_layerdrop
|
| 151 |
+
self.use_cache = use_cache
|
| 152 |
+
self.num_hidden_layers = encoder_layers
|
| 153 |
+
self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
|
| 154 |
+
|
| 155 |
+
self.num_global_tokens = num_global_tokens
|
| 156 |
+
self.block_size = block_size
|
| 157 |
+
self.stagger_local_blocks = stagger_local_blocks
|
| 158 |
+
|
| 159 |
+
super().__init__(
|
| 160 |
+
pad_token_id=pad_token_id,
|
| 161 |
+
eos_token_id=eos_token_id,
|
| 162 |
+
is_encoder_decoder=is_encoder_decoder,
|
| 163 |
+
decoder_start_token_id=decoder_start_token_id,
|
| 164 |
+
forced_eos_token_id=forced_eos_token_id,
|
| 165 |
+
**kwargs,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
@property
|
| 169 |
+
def num_attention_heads(self) -> int:
|
| 170 |
+
return self.encoder_attention_heads
|
| 171 |
+
|
| 172 |
+
@property
|
| 173 |
+
def hidden_size(self) -> int:
|
| 174 |
+
return self.d_model
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
__all__ = ["PegasusXConfig"]
|
janus/lib/python3.10/site-packages/transformers/models/pegasus_x/modeling_pegasus_x.py
ADDED
|
@@ -0,0 +1,1621 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ed 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 PEGASUS-X model."""
|
| 16 |
+
|
| 17 |
+
import dataclasses
|
| 18 |
+
import math
|
| 19 |
+
from typing import Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
import torch.utils.checkpoint
|
| 24 |
+
from torch import nn
|
| 25 |
+
from torch.nn import CrossEntropyLoss
|
| 26 |
+
|
| 27 |
+
from ...activations import ACT2FN
|
| 28 |
+
from ...generation import GenerationMixin
|
| 29 |
+
from ...modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask
|
| 30 |
+
from ...modeling_outputs import (
|
| 31 |
+
BaseModelOutput,
|
| 32 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 33 |
+
Seq2SeqLMOutput,
|
| 34 |
+
Seq2SeqModelOutput,
|
| 35 |
+
)
|
| 36 |
+
from ...modeling_utils import PreTrainedModel
|
| 37 |
+
from ...utils import (
|
| 38 |
+
add_end_docstrings,
|
| 39 |
+
add_start_docstrings,
|
| 40 |
+
add_start_docstrings_to_model_forward,
|
| 41 |
+
logging,
|
| 42 |
+
replace_return_docstrings,
|
| 43 |
+
)
|
| 44 |
+
from .configuration_pegasus_x import PegasusXConfig
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
logger = logging.get_logger(__name__)
|
| 48 |
+
|
| 49 |
+
_CHECKPOINT_FOR_DOC = "google/pegasus-x-base"
|
| 50 |
+
_CONFIG_FOR_DOC = "PegasusXConfig"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@dataclasses.dataclass
|
| 54 |
+
class DimensionInfo:
|
| 55 |
+
"""Wrapper for dimension info."""
|
| 56 |
+
|
| 57 |
+
batch_size: int # batch size
|
| 58 |
+
seq_len: int # token length
|
| 59 |
+
block_size: int # block size
|
| 60 |
+
num_heads: int # num heads
|
| 61 |
+
hidden_dim: int # hidden dim
|
| 62 |
+
dim_per_head: int # dim per head
|
| 63 |
+
num_blocks: int # num blocks
|
| 64 |
+
global_len: int # global length
|
| 65 |
+
padded_seq_len: int # padded token seq length
|
| 66 |
+
|
| 67 |
+
# Note: Compared to the original Flax implementation, we will pad the token representations to
|
| 68 |
+
# a multiple of block size at the start of the encoder layers, so T=P always.
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# Copied from transformers.models.bart.modeling_bart.shift_tokens_right
|
| 72 |
+
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
|
| 73 |
+
"""
|
| 74 |
+
Shift input ids one token to the right.
|
| 75 |
+
"""
|
| 76 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 77 |
+
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
|
| 78 |
+
shifted_input_ids[:, 0] = decoder_start_token_id
|
| 79 |
+
|
| 80 |
+
if pad_token_id is None:
|
| 81 |
+
raise ValueError("self.model.config.pad_token_id has to be defined.")
|
| 82 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 83 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
|
| 84 |
+
|
| 85 |
+
return shifted_input_ids
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# Copied from transformers.models.bart.modeling_bart.BartScaledWordEmbedding with Bart->PegasusX
|
| 89 |
+
class PegasusXScaledWordEmbedding(nn.Embedding):
|
| 90 |
+
"""
|
| 91 |
+
This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: Optional[float] = 1.0):
|
| 95 |
+
super().__init__(num_embeddings, embedding_dim, padding_idx)
|
| 96 |
+
self.embed_scale = embed_scale
|
| 97 |
+
|
| 98 |
+
def forward(self, input_ids: torch.Tensor):
|
| 99 |
+
return super().forward(input_ids) * self.embed_scale
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class PegasusXSinusoidalPositionalEmbedding(nn.Module):
|
| 103 |
+
"""This module produces sinusoidal positional embeddings of any length."""
|
| 104 |
+
|
| 105 |
+
def __init__(self, embed_dim, max_scale: int = 10000.0):
|
| 106 |
+
super().__init__()
|
| 107 |
+
self.embed_dim = embed_dim
|
| 108 |
+
self.max_scale = max_scale
|
| 109 |
+
|
| 110 |
+
@torch.no_grad()
|
| 111 |
+
def forward(self, input_embeds: torch.Tensor, past_key_values_length: int = 0) -> torch.Tensor:
|
| 112 |
+
"""`input_ids_shape` is expected to be [bsz x seqlen]."""
|
| 113 |
+
batch_size, seq_len = input_embeds.shape[:2]
|
| 114 |
+
positions = torch.arange(
|
| 115 |
+
past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=input_embeds.device
|
| 116 |
+
)[:, None]
|
| 117 |
+
pe = torch.zeros((seq_len, self.embed_dim), device=input_embeds.device, dtype=input_embeds.dtype)
|
| 118 |
+
half_d_feature = self.embed_dim // 2
|
| 119 |
+
div_term = torch.exp(
|
| 120 |
+
torch.arange(half_d_feature, device=input_embeds.device, dtype=torch.int64).type_as(input_embeds)
|
| 121 |
+
* -(np.log(float(self.max_scale)) / (half_d_feature - 1))
|
| 122 |
+
)
|
| 123 |
+
pe[:, :half_d_feature] = torch.sin(positions * div_term)
|
| 124 |
+
pe[:, half_d_feature:] = torch.cos(positions * div_term)
|
| 125 |
+
return pe[None].expand(batch_size, -1, -1)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->PegasusX
|
| 129 |
+
class PegasusXAttention(nn.Module):
|
| 130 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 131 |
+
|
| 132 |
+
def __init__(
|
| 133 |
+
self,
|
| 134 |
+
embed_dim: int,
|
| 135 |
+
num_heads: int,
|
| 136 |
+
dropout: float = 0.0,
|
| 137 |
+
is_decoder: bool = False,
|
| 138 |
+
bias: bool = True,
|
| 139 |
+
is_causal: bool = False,
|
| 140 |
+
config: Optional[PegasusXConfig] = None,
|
| 141 |
+
):
|
| 142 |
+
super().__init__()
|
| 143 |
+
self.embed_dim = embed_dim
|
| 144 |
+
self.num_heads = num_heads
|
| 145 |
+
self.dropout = dropout
|
| 146 |
+
self.head_dim = embed_dim // num_heads
|
| 147 |
+
self.config = config
|
| 148 |
+
|
| 149 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 150 |
+
raise ValueError(
|
| 151 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 152 |
+
f" and `num_heads`: {num_heads})."
|
| 153 |
+
)
|
| 154 |
+
self.scaling = self.head_dim**-0.5
|
| 155 |
+
self.is_decoder = is_decoder
|
| 156 |
+
self.is_causal = is_causal
|
| 157 |
+
|
| 158 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 159 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 160 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 161 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 162 |
+
|
| 163 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 164 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 165 |
+
|
| 166 |
+
def forward(
|
| 167 |
+
self,
|
| 168 |
+
hidden_states: torch.Tensor,
|
| 169 |
+
key_value_states: Optional[torch.Tensor] = None,
|
| 170 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 171 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 172 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 173 |
+
output_attentions: bool = False,
|
| 174 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 175 |
+
"""Input shape: Batch x Time x Channel"""
|
| 176 |
+
|
| 177 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 178 |
+
# for the decoder
|
| 179 |
+
is_cross_attention = key_value_states is not None
|
| 180 |
+
|
| 181 |
+
bsz, tgt_len, _ = hidden_states.size()
|
| 182 |
+
|
| 183 |
+
# get query proj
|
| 184 |
+
query_states = self.q_proj(hidden_states) * self.scaling
|
| 185 |
+
# get key, value proj
|
| 186 |
+
# `past_key_value[0].shape[2] == key_value_states.shape[1]`
|
| 187 |
+
# is checking that the `sequence_length` of the `past_key_value` is the same as
|
| 188 |
+
# the provided `key_value_states` to support prefix tuning
|
| 189 |
+
if (
|
| 190 |
+
is_cross_attention
|
| 191 |
+
and past_key_value is not None
|
| 192 |
+
and past_key_value[0].shape[2] == key_value_states.shape[1]
|
| 193 |
+
):
|
| 194 |
+
# reuse k,v, cross_attentions
|
| 195 |
+
key_states = past_key_value[0]
|
| 196 |
+
value_states = past_key_value[1]
|
| 197 |
+
elif is_cross_attention:
|
| 198 |
+
# cross_attentions
|
| 199 |
+
key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
|
| 200 |
+
value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
|
| 201 |
+
elif past_key_value is not None:
|
| 202 |
+
# reuse k, v, self_attention
|
| 203 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 204 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 205 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 206 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 207 |
+
else:
|
| 208 |
+
# self_attention
|
| 209 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 210 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 211 |
+
|
| 212 |
+
if self.is_decoder:
|
| 213 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 214 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 215 |
+
# key/value_states (first "if" case)
|
| 216 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 217 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 218 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 219 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 220 |
+
past_key_value = (key_states, value_states)
|
| 221 |
+
|
| 222 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 223 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
| 224 |
+
key_states = key_states.reshape(*proj_shape)
|
| 225 |
+
value_states = value_states.reshape(*proj_shape)
|
| 226 |
+
|
| 227 |
+
src_len = key_states.size(1)
|
| 228 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 229 |
+
|
| 230 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
| 231 |
+
raise ValueError(
|
| 232 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 233 |
+
f" {attn_weights.size()}"
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
if attention_mask is not None:
|
| 237 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 238 |
+
raise ValueError(
|
| 239 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
| 240 |
+
)
|
| 241 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
| 242 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 243 |
+
|
| 244 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 245 |
+
|
| 246 |
+
if layer_head_mask is not None:
|
| 247 |
+
if layer_head_mask.size() != (self.num_heads,):
|
| 248 |
+
raise ValueError(
|
| 249 |
+
f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
|
| 250 |
+
f" {layer_head_mask.size()}"
|
| 251 |
+
)
|
| 252 |
+
attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 253 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 254 |
+
|
| 255 |
+
if output_attentions:
|
| 256 |
+
# this operation is a bit awkward, but it's required to
|
| 257 |
+
# make sure that attn_weights keeps its gradient.
|
| 258 |
+
# In order to do so, attn_weights have to be reshaped
|
| 259 |
+
# twice and have to be reused in the following
|
| 260 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 261 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
| 262 |
+
else:
|
| 263 |
+
attn_weights_reshaped = None
|
| 264 |
+
|
| 265 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 266 |
+
|
| 267 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
| 268 |
+
|
| 269 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 270 |
+
raise ValueError(
|
| 271 |
+
f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 272 |
+
f" {attn_output.size()}"
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
| 276 |
+
attn_output = attn_output.transpose(1, 2)
|
| 277 |
+
|
| 278 |
+
# Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
|
| 279 |
+
# partitioned across GPUs when using tensor-parallelism.
|
| 280 |
+
attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
|
| 281 |
+
|
| 282 |
+
attn_output = self.out_proj(attn_output)
|
| 283 |
+
|
| 284 |
+
return attn_output, attn_weights_reshaped, past_key_value
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class PegasusXGlobalLocalAttention(nn.Module):
|
| 288 |
+
"""Global + Local attention. For use with Encoder only."""
|
| 289 |
+
|
| 290 |
+
def __init__(
|
| 291 |
+
self,
|
| 292 |
+
embed_dim: int,
|
| 293 |
+
num_heads: int,
|
| 294 |
+
block_size: int,
|
| 295 |
+
dropout: float = 0.0,
|
| 296 |
+
is_decoder: bool = False,
|
| 297 |
+
):
|
| 298 |
+
super().__init__()
|
| 299 |
+
self.embed_dim = embed_dim
|
| 300 |
+
self.num_heads = num_heads
|
| 301 |
+
self.block_size = block_size
|
| 302 |
+
self.dropout = dropout
|
| 303 |
+
self.head_dim = embed_dim // num_heads
|
| 304 |
+
|
| 305 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 306 |
+
raise ValueError(
|
| 307 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 308 |
+
f" and `num_heads`: {num_heads})."
|
| 309 |
+
)
|
| 310 |
+
self.scaling = self.head_dim**-0.5
|
| 311 |
+
self.is_decoder = is_decoder
|
| 312 |
+
|
| 313 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=False)
|
| 314 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=False)
|
| 315 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=False)
|
| 316 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=False)
|
| 317 |
+
|
| 318 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 319 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 320 |
+
|
| 321 |
+
def forward(
|
| 322 |
+
self,
|
| 323 |
+
token_hidden_states: torch.Tensor,
|
| 324 |
+
global_hidden_states: torch.Tensor,
|
| 325 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 326 |
+
output_attentions: bool = False,
|
| 327 |
+
) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
|
| 328 |
+
"""Input shape: Batch x Time x Channel"""
|
| 329 |
+
dim = DimensionInfo(
|
| 330 |
+
batch_size=token_hidden_states.shape[0],
|
| 331 |
+
seq_len=token_hidden_states.shape[1],
|
| 332 |
+
block_size=self.block_size,
|
| 333 |
+
num_heads=self.num_heads,
|
| 334 |
+
hidden_dim=token_hidden_states.shape[2],
|
| 335 |
+
dim_per_head=self.head_dim,
|
| 336 |
+
num_blocks=token_hidden_states.shape[1] // self.block_size,
|
| 337 |
+
global_len=global_hidden_states.shape[1],
|
| 338 |
+
padded_seq_len=token_hidden_states.shape[1],
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
# [batch_size, num_heads, padded_seq_len, dim_per_head]
|
| 342 |
+
local_q = self._shape(
|
| 343 |
+
self.q_proj(token_hidden_states) * self.scaling,
|
| 344 |
+
seq_len=dim.padded_seq_len,
|
| 345 |
+
bsz=dim.batch_size,
|
| 346 |
+
)
|
| 347 |
+
local_k = self._shape(
|
| 348 |
+
self.k_proj(token_hidden_states),
|
| 349 |
+
seq_len=dim.padded_seq_len,
|
| 350 |
+
bsz=dim.batch_size,
|
| 351 |
+
)
|
| 352 |
+
local_v = self._shape(
|
| 353 |
+
self.v_proj(token_hidden_states),
|
| 354 |
+
seq_len=dim.padded_seq_len,
|
| 355 |
+
bsz=dim.batch_size,
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
# [batch_size, num_heads, global_len, dim_per_head]
|
| 359 |
+
global_q = self._shape(
|
| 360 |
+
self.q_proj(global_hidden_states) * self.scaling,
|
| 361 |
+
seq_len=dim.global_len,
|
| 362 |
+
bsz=dim.batch_size,
|
| 363 |
+
)
|
| 364 |
+
global_k = self._shape(
|
| 365 |
+
self.k_proj(global_hidden_states),
|
| 366 |
+
seq_len=dim.global_len,
|
| 367 |
+
bsz=dim.batch_size,
|
| 368 |
+
)
|
| 369 |
+
global_v = self._shape(
|
| 370 |
+
self.v_proj(global_hidden_states),
|
| 371 |
+
seq_len=dim.global_len,
|
| 372 |
+
bsz=dim.batch_size,
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
global_attn_output, global_attn_probs = self.compute_global_attention_representations(
|
| 376 |
+
global_q=global_q,
|
| 377 |
+
global_k=global_k,
|
| 378 |
+
global_v=global_v,
|
| 379 |
+
local_k=local_k,
|
| 380 |
+
local_v=local_v,
|
| 381 |
+
mask=attention_mask,
|
| 382 |
+
dim=dim,
|
| 383 |
+
)
|
| 384 |
+
local_attn_output, local_attn_probs = self.compute_local_attention_representations(
|
| 385 |
+
global_k=global_k,
|
| 386 |
+
global_v=global_v,
|
| 387 |
+
local_q=local_q,
|
| 388 |
+
local_k=local_k,
|
| 389 |
+
local_v=local_v,
|
| 390 |
+
mask=attention_mask,
|
| 391 |
+
dim=dim,
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
# [batch_size, global_len, hidden_dim]
|
| 395 |
+
global_attn_output = (
|
| 396 |
+
global_attn_output.transpose(1, 2).contiguous().view(dim.batch_size, dim.global_len, dim.hidden_dim)
|
| 397 |
+
)
|
| 398 |
+
# [batch_size, global_len, hidden_dim]
|
| 399 |
+
global_attn_output = self.out_proj(global_attn_output)
|
| 400 |
+
# [batch_size, num_heads, block_size, num_heads, dim_per_head]
|
| 401 |
+
local_attn_output = local_attn_output.permute(0, 2, 3, 1, 4).contiguous()
|
| 402 |
+
# [batch_size, padded_seq_len, hidden_dim]
|
| 403 |
+
local_attn_output = local_attn_output.view(dim.batch_size, dim.padded_seq_len, dim.hidden_dim)
|
| 404 |
+
# [batch_size, padded_seq_len, hidden_dim]
|
| 405 |
+
local_attn_output = self.out_proj(local_attn_output)
|
| 406 |
+
|
| 407 |
+
if output_attentions:
|
| 408 |
+
attn_probs = {"global": global_attn_probs, "local": local_attn_probs}
|
| 409 |
+
else:
|
| 410 |
+
attn_probs = None
|
| 411 |
+
|
| 412 |
+
return local_attn_output, global_attn_output, attn_probs
|
| 413 |
+
|
| 414 |
+
def compute_global_attention_representations(
|
| 415 |
+
self, global_q, global_k, global_v, local_k, local_v, mask, dim: DimensionInfo
|
| 416 |
+
):
|
| 417 |
+
"""Compute attention representations for global tokens.
|
| 418 |
+
|
| 419 |
+
Global tokens will attend to both global tokens as well as all input sequence tokens. Because the input
|
| 420 |
+
sequence tokens are arranged in blocks for local attention, we unblock them and compute attention.
|
| 421 |
+
|
| 422 |
+
Args:
|
| 423 |
+
global_q (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:
|
| 424 |
+
query vectors from global tokens
|
| 425 |
+
global_k (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:
|
| 426 |
+
key vectors from global tokens
|
| 427 |
+
global_v (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:
|
| 428 |
+
value vectors from global tokens
|
| 429 |
+
local_k (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:
|
| 430 |
+
key vectors from local tokens
|
| 431 |
+
local_v (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:
|
| 432 |
+
value vectors from local tokens
|
| 433 |
+
mask (`torch.FloatTensor`) of shape [batch_size, padded_seq_len]: attention mask
|
| 434 |
+
dim (DimensionInfo): DimensionInfo wrapper for dimensions
|
| 435 |
+
|
| 436 |
+
Returns:
|
| 437 |
+
output of shape `[batch_sizes, length, features]`. where length will be padded to a multiple of block_size
|
| 438 |
+
"""
|
| 439 |
+
# [batch_size, num_heads, global_len+padded_seq_len, dim_per_head]
|
| 440 |
+
global_and_local_k = torch.cat([global_k, local_k], dim=2)
|
| 441 |
+
# [batch_size, num_heads, global_len+padded_seq_len, dim_per_head]
|
| 442 |
+
global_and_local_v = torch.cat([global_v, local_v], dim=2)
|
| 443 |
+
|
| 444 |
+
# [batch_size, global_len+padded_seq_len]
|
| 445 |
+
extended_mask = nn.functional.pad(mask, pad=(dim.global_len, 0), value=0)
|
| 446 |
+
|
| 447 |
+
# [batch_size, num_heads, global_len, global_len+padded_seq_len]
|
| 448 |
+
attn_weights = torch.einsum("BHGF,BHXF->BHGX", global_q, global_and_local_k)
|
| 449 |
+
attn_weights = attn_weights + extended_mask[:, None, None, :]
|
| 450 |
+
attn_probs = nn.functional.softmax(attn_weights, dim=-1)
|
| 451 |
+
attn_probs = nn.functional.dropout(attn_probs, p=self.dropout, training=self.training)
|
| 452 |
+
|
| 453 |
+
# [batch_size, num_heads, global_len, F]
|
| 454 |
+
attn_output = torch.einsum("BHGX,BHXF->BHGF", attn_probs, global_and_local_v)
|
| 455 |
+
return attn_output, attn_probs
|
| 456 |
+
|
| 457 |
+
def compute_local_attention_representations(
|
| 458 |
+
self, global_k, global_v, local_q, local_k, local_v, mask, dim: DimensionInfo
|
| 459 |
+
):
|
| 460 |
+
"""Compute attention representations for local tokens.
|
| 461 |
+
|
| 462 |
+
Local tokens will attend to both global tokens as well as all other tokens within the same local block. Hence,
|
| 463 |
+
we need to tile and concatenate the global tokens to every local block
|
| 464 |
+
|
| 465 |
+
Args:
|
| 466 |
+
global_k (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:
|
| 467 |
+
key vectors from global tokens
|
| 468 |
+
global_v (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:
|
| 469 |
+
value vectors from global tokens
|
| 470 |
+
local_q (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:
|
| 471 |
+
query vectors from local tokens
|
| 472 |
+
local_k (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:
|
| 473 |
+
key vectors from local tokens
|
| 474 |
+
local_v (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:
|
| 475 |
+
value vectors from local tokens
|
| 476 |
+
mask (`torch.FloatTensor`) of shape [batch_size, padded_seq_len]: attention mask
|
| 477 |
+
dim (DimensionInfo): DimensionInfo wrapper for dimensions
|
| 478 |
+
|
| 479 |
+
Returns:
|
| 480 |
+
output of shape `[batch_sizes, length, features]`. where length will be padded to a multiple of block_size
|
| 481 |
+
"""
|
| 482 |
+
# [batch_size, num_heads, num_blocks, block_size, dim_per_head]
|
| 483 |
+
blocked_local_q = local_q.view(dim.batch_size, dim.num_heads, dim.num_blocks, dim.block_size, dim.dim_per_head)
|
| 484 |
+
# [batch_size, num_heads, num_blocks, block_size, dim_per_head]
|
| 485 |
+
blocked_local_k = local_k.view(dim.batch_size, dim.num_heads, dim.num_blocks, dim.block_size, dim.dim_per_head)
|
| 486 |
+
# [batch_size, num_heads, num_blocks, block_size, dim_per_head]
|
| 487 |
+
blocked_local_v = local_v.view(dim.batch_size, dim.num_heads, dim.num_blocks, dim.block_size, dim.dim_per_head)
|
| 488 |
+
|
| 489 |
+
# [batch_size, num_blocks, global_len+block_size]
|
| 490 |
+
extended_mask = nn.functional.pad(
|
| 491 |
+
mask.view(dim.batch_size, dim.num_blocks, dim.block_size),
|
| 492 |
+
pad=(dim.global_len, 0),
|
| 493 |
+
value=0,
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
# [batch_size, num_heads, num_blocks, block_size, global_len]
|
| 497 |
+
blocked_local2global = torch.einsum("BHNKF,BHGF->BHNKG", blocked_local_q, global_k)
|
| 498 |
+
# [batch_size, num_heads, num_blocks, block_size, block_size]
|
| 499 |
+
blocked_local2local = torch.einsum("BHNKF,BHNXF->BHNKX", blocked_local_q, blocked_local_k)
|
| 500 |
+
|
| 501 |
+
# [batch_size, num_heads, num_blocks, block_size, global_len+block_size]
|
| 502 |
+
attn_weights = torch.cat([blocked_local2global, blocked_local2local], dim=-1)
|
| 503 |
+
attn_weights = attn_weights + extended_mask[:, None, :, None, :]
|
| 504 |
+
attn_probs = nn.functional.softmax(attn_weights, dim=-1)
|
| 505 |
+
attn_probs = nn.functional.dropout(attn_probs, p=self.dropout, training=self.training)
|
| 506 |
+
|
| 507 |
+
# [batch_size, num_heads, num_blocks, block_size, global_len]
|
| 508 |
+
local2global_attn_probs = attn_probs[:, :, :, :, : dim.global_len]
|
| 509 |
+
# [batch_size, num_heads, num_blocks, block_size, block_size]
|
| 510 |
+
local2local_attn_probs = attn_probs[:, :, :, :, dim.global_len :]
|
| 511 |
+
|
| 512 |
+
# [batch_size, num_heads, num_blocks, block_size, dim_per_head]
|
| 513 |
+
local2global_attn_output = torch.einsum("BHNKG,BHGF->BHNKF", local2global_attn_probs, global_v)
|
| 514 |
+
# [batch_size, num_heads, num_blocks, block_size, dim_per_head]
|
| 515 |
+
local2local_attn_output = torch.einsum("BHNKX,BHNXF->BHNKF", local2local_attn_probs, blocked_local_v)
|
| 516 |
+
# [batch_size, num_heads, num_blocks, block_size, dim_per_head]
|
| 517 |
+
attn_output = local2global_attn_output + local2local_attn_output
|
| 518 |
+
return attn_output, attn_probs
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
class PegasusXEncoderLayer(nn.Module):
|
| 522 |
+
def __init__(self, stagger_blocks_this_layer: bool, config: PegasusXConfig):
|
| 523 |
+
super().__init__()
|
| 524 |
+
self.embed_dim = config.d_model
|
| 525 |
+
self.self_attn = PegasusXGlobalLocalAttention(
|
| 526 |
+
embed_dim=self.embed_dim,
|
| 527 |
+
num_heads=config.encoder_attention_heads,
|
| 528 |
+
block_size=config.block_size,
|
| 529 |
+
dropout=config.attention_dropout,
|
| 530 |
+
)
|
| 531 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 532 |
+
self.global_self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 533 |
+
self.dropout = config.dropout
|
| 534 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 535 |
+
self.activation_dropout = config.activation_dropout
|
| 536 |
+
self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
|
| 537 |
+
self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
|
| 538 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 539 |
+
self.stagger_blocks_this_layer = stagger_blocks_this_layer
|
| 540 |
+
self.block_size = config.block_size
|
| 541 |
+
|
| 542 |
+
def forward(
|
| 543 |
+
self,
|
| 544 |
+
hidden_states: torch.Tensor,
|
| 545 |
+
global_hidden_states: torch.Tensor,
|
| 546 |
+
attention_mask: torch.Tensor,
|
| 547 |
+
output_attentions: bool = False,
|
| 548 |
+
) -> torch.Tensor:
|
| 549 |
+
"""
|
| 550 |
+
Args:
|
| 551 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape *(seq_len, batch, embed_dim)*
|
| 552 |
+
global_hidden_states (`torch.FloatTensor`): global token hidden states
|
| 553 |
+
*(seq_len, num_global_tokens, embed_dim)*
|
| 554 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 555 |
+
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
|
| 556 |
+
output_attentions (`bool`, *optional*):
|
| 557 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 558 |
+
returned tensors for more detail.
|
| 559 |
+
"""
|
| 560 |
+
residual = hidden_states
|
| 561 |
+
global_residual = global_hidden_states
|
| 562 |
+
|
| 563 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 564 |
+
global_hidden_states = self.global_self_attn_layer_norm(global_hidden_states)
|
| 565 |
+
|
| 566 |
+
if self.stagger_blocks_this_layer:
|
| 567 |
+
# Pad the blocks to simulate staggering
|
| 568 |
+
hidden_states, attention_mask = self.pad_local_tokens(
|
| 569 |
+
hidden_states=hidden_states, attention_mask=attention_mask, block_size=self.block_size
|
| 570 |
+
)
|
| 571 |
+
|
| 572 |
+
hidden_states, global_hidden_states, attn_weights = self.self_attn(
|
| 573 |
+
token_hidden_states=hidden_states,
|
| 574 |
+
global_hidden_states=global_hidden_states,
|
| 575 |
+
attention_mask=attention_mask,
|
| 576 |
+
output_attentions=output_attentions,
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
if self.stagger_blocks_this_layer:
|
| 580 |
+
# Undo the padding
|
| 581 |
+
hidden_states = self.unpad_local_tokens(padded_hidden_states=hidden_states, block_size=self.block_size)
|
| 582 |
+
|
| 583 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 584 |
+
hidden_states = residual + hidden_states
|
| 585 |
+
|
| 586 |
+
global_hidden_states = nn.functional.dropout(global_hidden_states, p=self.dropout, training=self.training)
|
| 587 |
+
global_hidden_states = global_residual + global_hidden_states
|
| 588 |
+
|
| 589 |
+
residual = hidden_states
|
| 590 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 591 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 592 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 593 |
+
hidden_states = self.fc2(hidden_states)
|
| 594 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 595 |
+
hidden_states = residual + hidden_states
|
| 596 |
+
|
| 597 |
+
global_residual = global_hidden_states
|
| 598 |
+
global_hidden_states = self.final_layer_norm(global_hidden_states)
|
| 599 |
+
global_hidden_states = self.activation_fn(self.fc1(global_hidden_states))
|
| 600 |
+
global_hidden_states = nn.functional.dropout(
|
| 601 |
+
global_hidden_states, p=self.activation_dropout, training=self.training
|
| 602 |
+
)
|
| 603 |
+
global_hidden_states = self.fc2(global_hidden_states)
|
| 604 |
+
global_hidden_states = nn.functional.dropout(global_hidden_states, p=self.dropout, training=self.training)
|
| 605 |
+
global_hidden_states = global_residual + global_hidden_states
|
| 606 |
+
outputs = (hidden_states, global_hidden_states)
|
| 607 |
+
|
| 608 |
+
if output_attentions:
|
| 609 |
+
outputs += (attn_weights,)
|
| 610 |
+
|
| 611 |
+
return outputs
|
| 612 |
+
|
| 613 |
+
@classmethod
|
| 614 |
+
def pad_local_tokens(cls, hidden_states, attention_mask, block_size):
|
| 615 |
+
# hidden_states: [batch_size, seq_len, hidden_dim]
|
| 616 |
+
pad_size = block_size // 2
|
| 617 |
+
mask_min_value = torch.finfo(hidden_states.dtype).min
|
| 618 |
+
padded_hidden_states = torch.nn.functional.pad(
|
| 619 |
+
hidden_states,
|
| 620 |
+
pad=(0, 0, pad_size, pad_size),
|
| 621 |
+
)
|
| 622 |
+
padded_mask = torch.nn.functional.pad(
|
| 623 |
+
attention_mask,
|
| 624 |
+
pad=(pad_size, pad_size),
|
| 625 |
+
value=mask_min_value,
|
| 626 |
+
)
|
| 627 |
+
return padded_hidden_states, padded_mask
|
| 628 |
+
|
| 629 |
+
@classmethod
|
| 630 |
+
def unpad_local_tokens(cls, padded_hidden_states, block_size):
|
| 631 |
+
# padded_hidden_states: [batch_size, padded seq_len, hidden_dim]
|
| 632 |
+
pad_size = block_size // 2
|
| 633 |
+
return padded_hidden_states[:, pad_size:-pad_size, :]
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
class PegasusXDecoderLayer(nn.Module):
|
| 637 |
+
def __init__(self, config: PegasusXConfig):
|
| 638 |
+
super().__init__()
|
| 639 |
+
self.embed_dim = config.d_model
|
| 640 |
+
|
| 641 |
+
self.self_attn = PegasusXAttention(
|
| 642 |
+
embed_dim=self.embed_dim,
|
| 643 |
+
num_heads=config.decoder_attention_heads,
|
| 644 |
+
dropout=config.attention_dropout,
|
| 645 |
+
is_decoder=True,
|
| 646 |
+
bias=False,
|
| 647 |
+
)
|
| 648 |
+
self.dropout = config.dropout
|
| 649 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 650 |
+
self.activation_dropout = config.activation_dropout
|
| 651 |
+
|
| 652 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 653 |
+
self.encoder_attn = PegasusXAttention(
|
| 654 |
+
self.embed_dim,
|
| 655 |
+
config.decoder_attention_heads,
|
| 656 |
+
dropout=config.attention_dropout,
|
| 657 |
+
is_decoder=True,
|
| 658 |
+
bias=False,
|
| 659 |
+
)
|
| 660 |
+
self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 661 |
+
self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
|
| 662 |
+
self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
|
| 663 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 664 |
+
|
| 665 |
+
def forward(
|
| 666 |
+
self,
|
| 667 |
+
hidden_states: torch.Tensor,
|
| 668 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 669 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 670 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 671 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 672 |
+
output_attentions: Optional[bool] = False,
|
| 673 |
+
use_cache: Optional[bool] = True,
|
| 674 |
+
) -> torch.Tensor:
|
| 675 |
+
"""
|
| 676 |
+
Args:
|
| 677 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape *(seq_len, batch, embed_dim)*
|
| 678 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 679 |
+
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
|
| 680 |
+
encoder_hidden_states (`torch.FloatTensor`):
|
| 681 |
+
cross attention input to the layer of shape *(seq_len, batch, embed_dim)*
|
| 682 |
+
encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
|
| 683 |
+
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
|
| 684 |
+
past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
|
| 685 |
+
output_attentions (`bool`, *optional*):
|
| 686 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 687 |
+
returned tensors for more detail.
|
| 688 |
+
use_cache: Whether to us KV cache for decoding
|
| 689 |
+
"""
|
| 690 |
+
residual = hidden_states
|
| 691 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 692 |
+
|
| 693 |
+
# Self Attention
|
| 694 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 695 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 696 |
+
# add present self-attn cache to positions 1,2 of present_key_value tuple
|
| 697 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 698 |
+
hidden_states=hidden_states,
|
| 699 |
+
past_key_value=self_attn_past_key_value,
|
| 700 |
+
attention_mask=attention_mask,
|
| 701 |
+
output_attentions=output_attentions,
|
| 702 |
+
)
|
| 703 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 704 |
+
hidden_states = residual + hidden_states
|
| 705 |
+
|
| 706 |
+
# Cross-Attention Block
|
| 707 |
+
cross_attn_present_key_value = None
|
| 708 |
+
cross_attn_weights = None
|
| 709 |
+
if encoder_hidden_states is not None:
|
| 710 |
+
residual = hidden_states
|
| 711 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 712 |
+
|
| 713 |
+
# cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
|
| 714 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 715 |
+
hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
|
| 716 |
+
hidden_states=hidden_states,
|
| 717 |
+
key_value_states=encoder_hidden_states,
|
| 718 |
+
attention_mask=encoder_attention_mask,
|
| 719 |
+
past_key_value=cross_attn_past_key_value,
|
| 720 |
+
output_attentions=output_attentions,
|
| 721 |
+
)
|
| 722 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 723 |
+
hidden_states = residual + hidden_states
|
| 724 |
+
|
| 725 |
+
# add cross-attn to positions 3,4 of present_key_value tuple
|
| 726 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 727 |
+
|
| 728 |
+
# Fully Connected
|
| 729 |
+
residual = hidden_states
|
| 730 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 731 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 732 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 733 |
+
hidden_states = self.fc2(hidden_states)
|
| 734 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 735 |
+
hidden_states = residual + hidden_states
|
| 736 |
+
|
| 737 |
+
outputs = (hidden_states,)
|
| 738 |
+
|
| 739 |
+
if output_attentions:
|
| 740 |
+
outputs += (self_attn_weights, cross_attn_weights)
|
| 741 |
+
|
| 742 |
+
if use_cache:
|
| 743 |
+
outputs += (present_key_value,)
|
| 744 |
+
|
| 745 |
+
return outputs
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
class PegasusXPreTrainedModel(PreTrainedModel):
|
| 749 |
+
config_class = PegasusXConfig
|
| 750 |
+
base_model_prefix = "model"
|
| 751 |
+
supports_gradient_checkpointing = True
|
| 752 |
+
_no_split_modules = [r"PegasusXEncoderLayer", r"PegasusXDecoderLayer"]
|
| 753 |
+
|
| 754 |
+
def _init_weights(self, module):
|
| 755 |
+
std = self.config.init_std
|
| 756 |
+
if isinstance(module, nn.Linear):
|
| 757 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 758 |
+
if module.bias is not None:
|
| 759 |
+
module.bias.data.zero_()
|
| 760 |
+
elif isinstance(module, nn.Embedding):
|
| 761 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
PEGASUS_X_START_DOCSTRING = r"""
|
| 765 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 766 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 767 |
+
etc.)
|
| 768 |
+
|
| 769 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 770 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 771 |
+
and behavior.
|
| 772 |
+
|
| 773 |
+
Parameters:
|
| 774 |
+
config ([`PegasusXConfig`]):
|
| 775 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 776 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 777 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 778 |
+
"""
|
| 779 |
+
|
| 780 |
+
PEGASUS_X_GENERATION_EXAMPLE = r"""
|
| 781 |
+
Summarization example:
|
| 782 |
+
|
| 783 |
+
```python
|
| 784 |
+
>>> from transformers import AutoTokenizer, PegasusXForConditionalGeneration
|
| 785 |
+
|
| 786 |
+
>>> model = PegasusXForConditionalGeneration.from_pretrained("google/pegasus-x-base")
|
| 787 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/pegasus-x-large")
|
| 788 |
+
|
| 789 |
+
>>> ARTICLE_TO_SUMMARIZE = (
|
| 790 |
+
... "PG&E stated it scheduled the blackouts in response to forecasts for high winds "
|
| 791 |
+
... "amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were "
|
| 792 |
+
... "scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow."
|
| 793 |
+
... )
|
| 794 |
+
>>> inputs = tokenizer(ARTICLE_TO_SUMMARIZE, max_length=1024, return_tensors="pt")
|
| 795 |
+
|
| 796 |
+
>>> # Generate Summary
|
| 797 |
+
>>> summary_ids = model.generate(inputs["input_ids"])
|
| 798 |
+
>>> tokenizer.batch_decode(summary_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 799 |
+
"California's largest electricity provider has turned off power to hundreds of thousands of customers."
|
| 800 |
+
```
|
| 801 |
+
"""
|
| 802 |
+
|
| 803 |
+
PEGASUS_X_INPUTS_DOCSTRING = r"""
|
| 804 |
+
Args:
|
| 805 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 806 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 807 |
+
it.
|
| 808 |
+
|
| 809 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 810 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 811 |
+
|
| 812 |
+
[What are input IDs?](../glossary#input-ids)
|
| 813 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 814 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 815 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 816 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 817 |
+
|
| 818 |
+
- 1 for tokens that are **not masked**,
|
| 819 |
+
- 0 for tokens that are **masked**.
|
| 820 |
+
|
| 821 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 822 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 823 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 824 |
+
|
| 825 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 826 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 827 |
+
|
| 828 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 829 |
+
|
| 830 |
+
PEGASUS-X uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If
|
| 831 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 832 |
+
`past_key_values`).
|
| 833 |
+
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 834 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 835 |
+
be used by default.
|
| 836 |
+
|
| 837 |
+
encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
|
| 838 |
+
Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
|
| 839 |
+
`last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
|
| 840 |
+
hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
|
| 841 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 842 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
| 843 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
|
| 844 |
+
`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
| 845 |
+
|
| 846 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 847 |
+
blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 848 |
+
|
| 849 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 850 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 851 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 852 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 853 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 854 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 855 |
+
than the model's internal embedding lookup matrix.
|
| 856 |
+
decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
|
| 857 |
+
Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
|
| 858 |
+
representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
|
| 859 |
+
input (see `past_key_values`). This is useful if you want more control over how to convert
|
| 860 |
+
`decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
|
| 861 |
+
|
| 862 |
+
If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
|
| 863 |
+
of `inputs_embeds`.
|
| 864 |
+
use_cache (`bool`, *optional*):
|
| 865 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 866 |
+
`past_key_values`).
|
| 867 |
+
output_attentions (`bool`, *optional*):
|
| 868 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 869 |
+
tensors for more detail.
|
| 870 |
+
output_hidden_states (`bool`, *optional*):
|
| 871 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 872 |
+
more detail.
|
| 873 |
+
return_dict (`bool`, *optional*):
|
| 874 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 875 |
+
"""
|
| 876 |
+
|
| 877 |
+
|
| 878 |
+
class PegasusXEncoder(PegasusXPreTrainedModel):
|
| 879 |
+
"""
|
| 880 |
+
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
|
| 881 |
+
[`PegasusXEncoderLayer`].
|
| 882 |
+
|
| 883 |
+
Args:
|
| 884 |
+
config: PegasusXConfig
|
| 885 |
+
embed_tokens (nn.Embedding): output embedding
|
| 886 |
+
"""
|
| 887 |
+
|
| 888 |
+
def __init__(self, config: PegasusXConfig, embed_tokens: Optional[nn.Embedding] = None):
|
| 889 |
+
super().__init__(config)
|
| 890 |
+
|
| 891 |
+
self.dropout = config.dropout
|
| 892 |
+
self.layerdrop = config.encoder_layerdrop
|
| 893 |
+
|
| 894 |
+
embed_dim = config.d_model
|
| 895 |
+
padding_idx = config.pad_token_id
|
| 896 |
+
self.max_source_positions = config.max_position_embeddings
|
| 897 |
+
embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
|
| 898 |
+
|
| 899 |
+
if embed_tokens is not None:
|
| 900 |
+
self.embed_tokens = embed_tokens
|
| 901 |
+
else:
|
| 902 |
+
self.embed_tokens = PegasusXScaledWordEmbedding(
|
| 903 |
+
config.vocab_size, embed_dim, padding_idx, embed_scale=embed_scale
|
| 904 |
+
)
|
| 905 |
+
|
| 906 |
+
self.embed_global = nn.Embedding(config.num_global_tokens, embed_dim)
|
| 907 |
+
self.embed_positions = PegasusXSinusoidalPositionalEmbedding(embed_dim)
|
| 908 |
+
self.layers = nn.ModuleList(
|
| 909 |
+
[
|
| 910 |
+
PegasusXEncoderLayer(
|
| 911 |
+
stagger_blocks_this_layer=i % 2 == 1 and config.stagger_local_blocks, config=config
|
| 912 |
+
)
|
| 913 |
+
for i in range(config.encoder_layers)
|
| 914 |
+
]
|
| 915 |
+
)
|
| 916 |
+
self.layer_norm = nn.LayerNorm(config.d_model)
|
| 917 |
+
|
| 918 |
+
self.gradient_checkpointing = False
|
| 919 |
+
# Initialize weights and apply final processing
|
| 920 |
+
self.post_init()
|
| 921 |
+
|
| 922 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 923 |
+
"""
|
| 924 |
+
Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
|
| 925 |
+
config.max_position_embeddings`.
|
| 926 |
+
|
| 927 |
+
Arguments:
|
| 928 |
+
new_num_position_embeddings (`int`):
|
| 929 |
+
The number of new position embeddings. If position embeddings are learned, increasing the size will add
|
| 930 |
+
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
|
| 931 |
+
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
|
| 932 |
+
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
|
| 933 |
+
will remove vectors from the end.
|
| 934 |
+
"""
|
| 935 |
+
logger.info(f"Setting `config.max_position_embeddings={new_num_position_embeddings}`...")
|
| 936 |
+
self.config.max_position_embeddings = new_num_position_embeddings
|
| 937 |
+
|
| 938 |
+
self.embed_positions = PegasusXSinusoidalPositionalEmbedding(self.config.d_model)
|
| 939 |
+
self.embed_positions.to(self.device)
|
| 940 |
+
|
| 941 |
+
def get_position_embeddings(self) -> nn.Embedding:
|
| 942 |
+
"""
|
| 943 |
+
Returns the position embeddings matrix
|
| 944 |
+
"""
|
| 945 |
+
return self.embed_positions
|
| 946 |
+
|
| 947 |
+
def forward(
|
| 948 |
+
self,
|
| 949 |
+
input_ids=None,
|
| 950 |
+
attention_mask=None,
|
| 951 |
+
inputs_embeds=None,
|
| 952 |
+
output_attentions=None,
|
| 953 |
+
output_hidden_states=None,
|
| 954 |
+
return_dict=None,
|
| 955 |
+
):
|
| 956 |
+
r"""
|
| 957 |
+
Args:
|
| 958 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 959 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 960 |
+
provide it.
|
| 961 |
+
|
| 962 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 963 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 964 |
+
|
| 965 |
+
[What are input IDs?](../glossary#input-ids)
|
| 966 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 967 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 968 |
+
|
| 969 |
+
- 1 for tokens that are **not masked**,
|
| 970 |
+
- 0 for tokens that are **masked**.
|
| 971 |
+
|
| 972 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 973 |
+
|
| 974 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 975 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 976 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 977 |
+
than the model's internal embedding lookup matrix.
|
| 978 |
+
output_attentions (`bool`, *optional*):
|
| 979 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 980 |
+
returned tensors for more detail.
|
| 981 |
+
output_hidden_states (`bool`, *optional*):
|
| 982 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 983 |
+
for more detail.
|
| 984 |
+
return_dict (`bool`, *optional*):
|
| 985 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 986 |
+
"""
|
| 987 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 988 |
+
output_hidden_states = (
|
| 989 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 990 |
+
)
|
| 991 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 992 |
+
|
| 993 |
+
# retrieve input_ids and inputs_embeds
|
| 994 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 995 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 996 |
+
elif input_ids is not None:
|
| 997 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 998 |
+
input_shape = input_ids.size()
|
| 999 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 1000 |
+
elif inputs_embeds is not None:
|
| 1001 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1002 |
+
else:
|
| 1003 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 1004 |
+
|
| 1005 |
+
if inputs_embeds is None:
|
| 1006 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 1007 |
+
|
| 1008 |
+
embed_pos = self.embed_positions(inputs_embeds)
|
| 1009 |
+
|
| 1010 |
+
hidden_states = inputs_embeds + embed_pos
|
| 1011 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 1012 |
+
|
| 1013 |
+
batch_size, seq_len, _ = hidden_states.shape
|
| 1014 |
+
|
| 1015 |
+
# Setup mask
|
| 1016 |
+
if attention_mask is None:
|
| 1017 |
+
attention_mask = torch.ones(*input_shape, dtype=inputs_embeds.dtype, device=inputs_embeds.device)
|
| 1018 |
+
attention_mask = attention_mask.to(dtype=hidden_states.dtype)
|
| 1019 |
+
mask_min_value = torch.finfo(hidden_states.dtype).min
|
| 1020 |
+
inverted_mask = 1.0 - attention_mask
|
| 1021 |
+
attention_mask = inverted_mask.masked_fill(
|
| 1022 |
+
inverted_mask.to(torch.bool),
|
| 1023 |
+
mask_min_value,
|
| 1024 |
+
)
|
| 1025 |
+
|
| 1026 |
+
# padding to block_size
|
| 1027 |
+
if seq_len % self.config.block_size != 0:
|
| 1028 |
+
pad_len = self.config.block_size - seq_len % self.config.block_size
|
| 1029 |
+
hidden_states = nn.functional.pad(hidden_states, pad=(0, 0, 0, pad_len), value=0)
|
| 1030 |
+
attention_mask = nn.functional.pad(attention_mask, pad=(0, pad_len), value=mask_min_value)
|
| 1031 |
+
|
| 1032 |
+
# Global tokens
|
| 1033 |
+
global_hidden_states = self.embed_global(
|
| 1034 |
+
torch.arange(self.config.num_global_tokens, device=hidden_states.device)[None].expand(batch_size, -1)
|
| 1035 |
+
)
|
| 1036 |
+
|
| 1037 |
+
encoder_states = () if output_hidden_states else None
|
| 1038 |
+
all_attentions = () if output_attentions else None
|
| 1039 |
+
|
| 1040 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 1041 |
+
if output_hidden_states:
|
| 1042 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 1043 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 1044 |
+
to_drop = False
|
| 1045 |
+
if self.training:
|
| 1046 |
+
dropout_probability = torch.rand([])
|
| 1047 |
+
if dropout_probability < self.layerdrop: # skip the layer
|
| 1048 |
+
to_drop = True
|
| 1049 |
+
|
| 1050 |
+
if to_drop:
|
| 1051 |
+
layer_outputs = (None, None)
|
| 1052 |
+
else:
|
| 1053 |
+
if self.gradient_checkpointing and self.training:
|
| 1054 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 1055 |
+
encoder_layer.__call__,
|
| 1056 |
+
hidden_states,
|
| 1057 |
+
global_hidden_states,
|
| 1058 |
+
attention_mask,
|
| 1059 |
+
output_attentions,
|
| 1060 |
+
)
|
| 1061 |
+
else:
|
| 1062 |
+
layer_outputs = encoder_layer(
|
| 1063 |
+
hidden_states,
|
| 1064 |
+
global_hidden_states,
|
| 1065 |
+
attention_mask,
|
| 1066 |
+
output_attentions=output_attentions,
|
| 1067 |
+
)
|
| 1068 |
+
|
| 1069 |
+
hidden_states = layer_outputs[0]
|
| 1070 |
+
global_hidden_states = layer_outputs[1]
|
| 1071 |
+
|
| 1072 |
+
if output_attentions:
|
| 1073 |
+
all_attentions = all_attentions + (layer_outputs[2],)
|
| 1074 |
+
|
| 1075 |
+
# Undo padding-to-block-size
|
| 1076 |
+
hidden_states = hidden_states[:, :seq_len]
|
| 1077 |
+
|
| 1078 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 1079 |
+
|
| 1080 |
+
if output_hidden_states:
|
| 1081 |
+
encoder_states = encoder_states + ((hidden_states, global_hidden_states),)
|
| 1082 |
+
|
| 1083 |
+
if not return_dict:
|
| 1084 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 1085 |
+
return BaseModelOutput(
|
| 1086 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 1087 |
+
)
|
| 1088 |
+
|
| 1089 |
+
|
| 1090 |
+
class PegasusXDecoder(PegasusXPreTrainedModel):
|
| 1091 |
+
"""
|
| 1092 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`PegasusDecoderLayer`]
|
| 1093 |
+
|
| 1094 |
+
Args:
|
| 1095 |
+
config: PegasusXConfig
|
| 1096 |
+
embed_tokens (nn.Embedding): output embedding
|
| 1097 |
+
"""
|
| 1098 |
+
|
| 1099 |
+
def __init__(self, config: PegasusXConfig, embed_tokens: Optional[nn.Embedding] = None):
|
| 1100 |
+
super().__init__(config)
|
| 1101 |
+
self.dropout = config.dropout
|
| 1102 |
+
self.layerdrop = config.decoder_layerdrop
|
| 1103 |
+
self.max_target_positions = config.max_position_embeddings
|
| 1104 |
+
embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 1105 |
+
padding_idx = config.pad_token_id
|
| 1106 |
+
|
| 1107 |
+
if embed_tokens is not None:
|
| 1108 |
+
self.embed_tokens = embed_tokens
|
| 1109 |
+
else:
|
| 1110 |
+
self.embed_tokens = PegasusXScaledWordEmbedding(
|
| 1111 |
+
config.vocab_size, config.d_model, padding_idx=padding_idx, embed_scale=embed_scale
|
| 1112 |
+
)
|
| 1113 |
+
|
| 1114 |
+
self.embed_positions = PegasusXSinusoidalPositionalEmbedding(config.d_model)
|
| 1115 |
+
self.layers = nn.ModuleList([PegasusXDecoderLayer(config) for _ in range(config.decoder_layers)])
|
| 1116 |
+
self.layer_norm = nn.LayerNorm(config.d_model)
|
| 1117 |
+
|
| 1118 |
+
self.gradient_checkpointing = False
|
| 1119 |
+
# Initialize weights and apply final processing
|
| 1120 |
+
self.post_init()
|
| 1121 |
+
|
| 1122 |
+
def get_input_embeddings(self):
|
| 1123 |
+
return self.embed_tokens
|
| 1124 |
+
|
| 1125 |
+
def set_input_embeddings(self, value):
|
| 1126 |
+
self.embed_tokens = value
|
| 1127 |
+
|
| 1128 |
+
def forward(
|
| 1129 |
+
self,
|
| 1130 |
+
input_ids=None,
|
| 1131 |
+
attention_mask=None,
|
| 1132 |
+
encoder_hidden_states=None,
|
| 1133 |
+
encoder_attention_mask=None,
|
| 1134 |
+
past_key_values=None,
|
| 1135 |
+
inputs_embeds=None,
|
| 1136 |
+
use_cache=None,
|
| 1137 |
+
output_attentions=None,
|
| 1138 |
+
output_hidden_states=None,
|
| 1139 |
+
return_dict=None,
|
| 1140 |
+
):
|
| 1141 |
+
r"""
|
| 1142 |
+
Args:
|
| 1143 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 1144 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 1145 |
+
provide it.
|
| 1146 |
+
|
| 1147 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1148 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1149 |
+
|
| 1150 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1151 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1152 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 1153 |
+
|
| 1154 |
+
- 1 for tokens that are **not masked**,
|
| 1155 |
+
- 0 for tokens that are **masked**.
|
| 1156 |
+
|
| 1157 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 1158 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 1159 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 1160 |
+
of the decoder.
|
| 1161 |
+
encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
|
| 1162 |
+
Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
|
| 1163 |
+
selected in `[0, 1]`:
|
| 1164 |
+
|
| 1165 |
+
- 1 for tokens that are **not masked**,
|
| 1166 |
+
- 0 for tokens that are **masked**.
|
| 1167 |
+
|
| 1168 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 1169 |
+
|
| 1170 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 1171 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 1172 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
|
| 1173 |
+
shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
| 1174 |
+
|
| 1175 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
|
| 1176 |
+
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 1177 |
+
|
| 1178 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
|
| 1179 |
+
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
|
| 1180 |
+
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 1181 |
+
inputs_embeds (`torch.FloatTensor` of
|
| 1182 |
+
shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing
|
| 1183 |
+
`input_ids` you can choose to directly pass an embedded representation. This is useful if you want more
|
| 1184 |
+
control over how to convert `input_ids` indices into associated vectors than the model's internal
|
| 1185 |
+
embedding lookup matrix.
|
| 1186 |
+
output_attentions (`bool`, *optional*):
|
| 1187 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 1188 |
+
returned tensors for more detail.
|
| 1189 |
+
output_hidden_states (`bool`, *optional*):
|
| 1190 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 1191 |
+
for more detail.
|
| 1192 |
+
return_dict (`bool`, *optional*):
|
| 1193 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 1194 |
+
"""
|
| 1195 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1196 |
+
output_hidden_states = (
|
| 1197 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1198 |
+
)
|
| 1199 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1200 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1201 |
+
|
| 1202 |
+
# retrieve input_ids and inputs_embeds
|
| 1203 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 1204 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 1205 |
+
elif input_ids is not None:
|
| 1206 |
+
input_shape = input_ids.size()
|
| 1207 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 1208 |
+
elif inputs_embeds is not None:
|
| 1209 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1210 |
+
else:
|
| 1211 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
| 1212 |
+
|
| 1213 |
+
# past_key_values_length
|
| 1214 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
| 1215 |
+
|
| 1216 |
+
if inputs_embeds is None:
|
| 1217 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 1218 |
+
|
| 1219 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
| 1220 |
+
attention_mask, input_shape, inputs_embeds, past_key_values_length
|
| 1221 |
+
)
|
| 1222 |
+
|
| 1223 |
+
# expand encoder attention mask
|
| 1224 |
+
if encoder_hidden_states is not None and encoder_attention_mask is not None:
|
| 1225 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 1226 |
+
encoder_attention_mask = _prepare_4d_attention_mask(
|
| 1227 |
+
encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
|
| 1228 |
+
)
|
| 1229 |
+
|
| 1230 |
+
# embed positions
|
| 1231 |
+
positions = self.embed_positions(inputs_embeds, past_key_values_length)
|
| 1232 |
+
|
| 1233 |
+
positions = positions.to(inputs_embeds.device)
|
| 1234 |
+
|
| 1235 |
+
hidden_states = inputs_embeds + positions
|
| 1236 |
+
|
| 1237 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 1238 |
+
|
| 1239 |
+
if self.gradient_checkpointing and self.training:
|
| 1240 |
+
if use_cache:
|
| 1241 |
+
logger.warning_once(
|
| 1242 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 1243 |
+
)
|
| 1244 |
+
use_cache = False
|
| 1245 |
+
|
| 1246 |
+
# decoder layers
|
| 1247 |
+
all_hidden_states = () if output_hidden_states else None
|
| 1248 |
+
all_self_attns = () if output_attentions else None
|
| 1249 |
+
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 1250 |
+
next_decoder_cache = () if use_cache else None
|
| 1251 |
+
|
| 1252 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 1253 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 1254 |
+
if output_hidden_states:
|
| 1255 |
+
all_hidden_states += (hidden_states,)
|
| 1256 |
+
if self.training:
|
| 1257 |
+
dropout_probability = torch.rand([])
|
| 1258 |
+
if dropout_probability < self.layerdrop:
|
| 1259 |
+
continue
|
| 1260 |
+
|
| 1261 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 1262 |
+
|
| 1263 |
+
if self.gradient_checkpointing and self.training:
|
| 1264 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 1265 |
+
decoder_layer.__call__,
|
| 1266 |
+
hidden_states,
|
| 1267 |
+
attention_mask,
|
| 1268 |
+
encoder_hidden_states,
|
| 1269 |
+
encoder_attention_mask,
|
| 1270 |
+
None,
|
| 1271 |
+
output_attentions,
|
| 1272 |
+
use_cache,
|
| 1273 |
+
)
|
| 1274 |
+
else:
|
| 1275 |
+
layer_outputs = decoder_layer(
|
| 1276 |
+
hidden_states,
|
| 1277 |
+
attention_mask=attention_mask,
|
| 1278 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1279 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1280 |
+
past_key_value=past_key_value,
|
| 1281 |
+
output_attentions=output_attentions,
|
| 1282 |
+
use_cache=use_cache,
|
| 1283 |
+
)
|
| 1284 |
+
hidden_states = layer_outputs[0]
|
| 1285 |
+
|
| 1286 |
+
if use_cache:
|
| 1287 |
+
next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
|
| 1288 |
+
|
| 1289 |
+
if output_attentions:
|
| 1290 |
+
all_self_attns += (layer_outputs[1],)
|
| 1291 |
+
|
| 1292 |
+
if encoder_hidden_states is not None:
|
| 1293 |
+
all_cross_attentions += (layer_outputs[2],)
|
| 1294 |
+
|
| 1295 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 1296 |
+
|
| 1297 |
+
# add hidden states from the last decoder layer
|
| 1298 |
+
if output_hidden_states:
|
| 1299 |
+
all_hidden_states += (hidden_states,)
|
| 1300 |
+
|
| 1301 |
+
next_cache = next_decoder_cache if use_cache else None
|
| 1302 |
+
if not return_dict:
|
| 1303 |
+
return tuple(
|
| 1304 |
+
v
|
| 1305 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
|
| 1306 |
+
if v is not None
|
| 1307 |
+
)
|
| 1308 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 1309 |
+
last_hidden_state=hidden_states,
|
| 1310 |
+
past_key_values=next_cache,
|
| 1311 |
+
hidden_states=all_hidden_states,
|
| 1312 |
+
attentions=all_self_attns,
|
| 1313 |
+
cross_attentions=all_cross_attentions,
|
| 1314 |
+
)
|
| 1315 |
+
|
| 1316 |
+
|
| 1317 |
+
@add_start_docstrings(
|
| 1318 |
+
"The bare PEGASUS-X Model outputting raw hidden-states without any specific head on top.",
|
| 1319 |
+
PEGASUS_X_START_DOCSTRING,
|
| 1320 |
+
)
|
| 1321 |
+
class PegasusXModel(PegasusXPreTrainedModel):
|
| 1322 |
+
_tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
|
| 1323 |
+
|
| 1324 |
+
def __init__(self, config: PegasusXConfig):
|
| 1325 |
+
super().__init__(config)
|
| 1326 |
+
|
| 1327 |
+
vocab_size = config.vocab_size
|
| 1328 |
+
embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 1329 |
+
padding_idx = config.pad_token_id
|
| 1330 |
+
self.shared = PegasusXScaledWordEmbedding(
|
| 1331 |
+
vocab_size, config.d_model, padding_idx=padding_idx, embed_scale=embed_scale
|
| 1332 |
+
)
|
| 1333 |
+
|
| 1334 |
+
self.encoder = PegasusXEncoder(config, self.shared)
|
| 1335 |
+
self.decoder = PegasusXDecoder(config, self.shared)
|
| 1336 |
+
|
| 1337 |
+
# Initialize weights and apply final processing
|
| 1338 |
+
self.post_init()
|
| 1339 |
+
|
| 1340 |
+
def get_input_embeddings(self):
|
| 1341 |
+
return self.shared
|
| 1342 |
+
|
| 1343 |
+
def set_input_embeddings(self, value):
|
| 1344 |
+
self.shared = value
|
| 1345 |
+
self.encoder.embed_tokens = self.shared
|
| 1346 |
+
self.decoder.embed_tokens = self.shared
|
| 1347 |
+
|
| 1348 |
+
def get_encoder(self):
|
| 1349 |
+
return self.encoder
|
| 1350 |
+
|
| 1351 |
+
def get_decoder(self):
|
| 1352 |
+
return self.decoder
|
| 1353 |
+
|
| 1354 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 1355 |
+
"""
|
| 1356 |
+
Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
|
| 1357 |
+
config.max_position_embeddings`.
|
| 1358 |
+
|
| 1359 |
+
Arguments:
|
| 1360 |
+
new_num_position_embeddings (`int`):
|
| 1361 |
+
The number of new position embeddings. If position embeddings are learned, increasing the size will add
|
| 1362 |
+
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
|
| 1363 |
+
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
|
| 1364 |
+
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
|
| 1365 |
+
will remove vectors from the end.
|
| 1366 |
+
"""
|
| 1367 |
+
self.config.max_position_embeddings = new_num_position_embeddings
|
| 1368 |
+
self.encoder.resize_position_embeddings(new_num_position_embeddings)
|
| 1369 |
+
self.decoder.resize_position_embeddings(new_num_position_embeddings)
|
| 1370 |
+
|
| 1371 |
+
def get_position_embeddings(self) -> Tuple[nn.Embedding]:
|
| 1372 |
+
"""
|
| 1373 |
+
Returns the position embeddings matrix
|
| 1374 |
+
"""
|
| 1375 |
+
return (self.encoder.get_position_embeddings(), self.decoder.get_position_embeddings())
|
| 1376 |
+
|
| 1377 |
+
@add_start_docstrings_to_model_forward(PEGASUS_X_INPUTS_DOCSTRING)
|
| 1378 |
+
@replace_return_docstrings(output_type=Seq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)
|
| 1379 |
+
def forward(
|
| 1380 |
+
self,
|
| 1381 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1382 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1383 |
+
decoder_input_ids: Optional[torch.Tensor] = None,
|
| 1384 |
+
decoder_attention_mask: Optional[torch.Tensor] = None,
|
| 1385 |
+
encoder_outputs: Optional[Tuple[torch.FloatTensor]] = None,
|
| 1386 |
+
past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
|
| 1387 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1388 |
+
decoder_inputs_embeds: Optional[torch.Tensor] = None,
|
| 1389 |
+
use_cache: Optional[bool] = None,
|
| 1390 |
+
output_attentions: Optional[bool] = None,
|
| 1391 |
+
output_hidden_states: Optional[bool] = None,
|
| 1392 |
+
return_dict: Optional[bool] = None,
|
| 1393 |
+
) -> Union[Tuple, Seq2SeqModelOutput]:
|
| 1394 |
+
r"""
|
| 1395 |
+
Returns:
|
| 1396 |
+
|
| 1397 |
+
Example:
|
| 1398 |
+
|
| 1399 |
+
```python
|
| 1400 |
+
>>> from transformers import AutoTokenizer, PegasusModel
|
| 1401 |
+
|
| 1402 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/pegasus-x-large")
|
| 1403 |
+
>>> model = PegasusModel.from_pretrained("google/pegasus-x-large")
|
| 1404 |
+
|
| 1405 |
+
>>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
|
| 1406 |
+
>>> decoder_inputs = tokenizer("Studies show that", return_tensors="pt")
|
| 1407 |
+
>>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)
|
| 1408 |
+
|
| 1409 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 1410 |
+
>>> list(last_hidden_states.shape)
|
| 1411 |
+
[1, 4, 1024]
|
| 1412 |
+
```"""
|
| 1413 |
+
|
| 1414 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1415 |
+
output_hidden_states = (
|
| 1416 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1417 |
+
)
|
| 1418 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1419 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1420 |
+
|
| 1421 |
+
if encoder_outputs is None:
|
| 1422 |
+
encoder_outputs = self.encoder(
|
| 1423 |
+
input_ids=input_ids,
|
| 1424 |
+
attention_mask=attention_mask,
|
| 1425 |
+
inputs_embeds=inputs_embeds,
|
| 1426 |
+
output_attentions=output_attentions,
|
| 1427 |
+
output_hidden_states=output_hidden_states,
|
| 1428 |
+
return_dict=return_dict,
|
| 1429 |
+
)
|
| 1430 |
+
# If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
|
| 1431 |
+
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
|
| 1432 |
+
encoder_outputs = BaseModelOutput(
|
| 1433 |
+
last_hidden_state=encoder_outputs[0],
|
| 1434 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 1435 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 1436 |
+
)
|
| 1437 |
+
|
| 1438 |
+
# decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
|
| 1439 |
+
decoder_outputs = self.decoder(
|
| 1440 |
+
input_ids=decoder_input_ids,
|
| 1441 |
+
attention_mask=decoder_attention_mask,
|
| 1442 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 1443 |
+
encoder_attention_mask=attention_mask,
|
| 1444 |
+
past_key_values=past_key_values,
|
| 1445 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 1446 |
+
use_cache=use_cache,
|
| 1447 |
+
output_attentions=output_attentions,
|
| 1448 |
+
output_hidden_states=output_hidden_states,
|
| 1449 |
+
return_dict=return_dict,
|
| 1450 |
+
)
|
| 1451 |
+
|
| 1452 |
+
if not return_dict:
|
| 1453 |
+
return decoder_outputs + encoder_outputs
|
| 1454 |
+
|
| 1455 |
+
return Seq2SeqModelOutput(
|
| 1456 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 1457 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 1458 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 1459 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 1460 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 1461 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 1462 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 1463 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 1464 |
+
)
|
| 1465 |
+
|
| 1466 |
+
|
| 1467 |
+
@add_start_docstrings("The PEGASUS-X for conditional generation (e.g. summarization).", PEGASUS_X_START_DOCSTRING)
|
| 1468 |
+
class PegasusXForConditionalGeneration(PegasusXPreTrainedModel, GenerationMixin):
|
| 1469 |
+
base_model_prefix = "model"
|
| 1470 |
+
_tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight", "lm_head.weight"]
|
| 1471 |
+
|
| 1472 |
+
def __init__(self, config: PegasusXConfig):
|
| 1473 |
+
super().__init__(config)
|
| 1474 |
+
self.model = PegasusXModel(config)
|
| 1475 |
+
self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
|
| 1476 |
+
|
| 1477 |
+
# Initialize weights and apply final processing
|
| 1478 |
+
self.post_init()
|
| 1479 |
+
|
| 1480 |
+
def get_encoder(self):
|
| 1481 |
+
return self.model.get_encoder()
|
| 1482 |
+
|
| 1483 |
+
def get_decoder(self):
|
| 1484 |
+
return self.model.get_decoder()
|
| 1485 |
+
|
| 1486 |
+
def get_output_embeddings(self):
|
| 1487 |
+
return self.lm_head
|
| 1488 |
+
|
| 1489 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1490 |
+
self.lm_head = new_embeddings
|
| 1491 |
+
|
| 1492 |
+
def resize_position_embeddings(self, new_num_position_embeddings: int):
|
| 1493 |
+
"""
|
| 1494 |
+
Resizes position embeddings matrix of the model if `new_num_position_embeddings !=
|
| 1495 |
+
config.max_position_embeddings`.
|
| 1496 |
+
|
| 1497 |
+
Arguments:
|
| 1498 |
+
new_num_position_embeddings (`int`):
|
| 1499 |
+
The number of new position embeddings. If position embeddings are learned, increasing the size will add
|
| 1500 |
+
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
|
| 1501 |
+
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
|
| 1502 |
+
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
|
| 1503 |
+
will remove vectors from the end.
|
| 1504 |
+
"""
|
| 1505 |
+
self.config.max_position_embeddings = new_num_position_embeddings
|
| 1506 |
+
self.model.encoder.resize_position_embeddings(new_num_position_embeddings)
|
| 1507 |
+
self.model.decoder.resize_position_embeddings(new_num_position_embeddings)
|
| 1508 |
+
|
| 1509 |
+
def get_position_embeddings(self) -> Tuple[nn.Embedding]:
|
| 1510 |
+
"""
|
| 1511 |
+
Returns the position embeddings matrix
|
| 1512 |
+
"""
|
| 1513 |
+
return (self.model.encoder.get_position_embeddings(), self.model.decoder.get_position_embeddings())
|
| 1514 |
+
|
| 1515 |
+
@add_start_docstrings_to_model_forward(PEGASUS_X_INPUTS_DOCSTRING)
|
| 1516 |
+
@replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
|
| 1517 |
+
@add_end_docstrings(PEGASUS_X_GENERATION_EXAMPLE)
|
| 1518 |
+
def forward(
|
| 1519 |
+
self,
|
| 1520 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1521 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1522 |
+
decoder_input_ids: Optional[torch.Tensor] = None,
|
| 1523 |
+
decoder_attention_mask: Optional[torch.Tensor] = None,
|
| 1524 |
+
encoder_outputs: Optional[Tuple[torch.FloatTensor]] = None,
|
| 1525 |
+
past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
|
| 1526 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1527 |
+
decoder_inputs_embeds: Optional[torch.Tensor] = None,
|
| 1528 |
+
labels: Optional[torch.Tensor] = None,
|
| 1529 |
+
use_cache: Optional[bool] = None,
|
| 1530 |
+
output_attentions: Optional[bool] = None,
|
| 1531 |
+
output_hidden_states: Optional[bool] = None,
|
| 1532 |
+
return_dict: Optional[bool] = None,
|
| 1533 |
+
) -> Union[Tuple, Seq2SeqLMOutput]:
|
| 1534 |
+
r"""
|
| 1535 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1536 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1537 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1538 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1539 |
+
|
| 1540 |
+
Returns:
|
| 1541 |
+
|
| 1542 |
+
"""
|
| 1543 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1544 |
+
|
| 1545 |
+
if labels is not None:
|
| 1546 |
+
if use_cache:
|
| 1547 |
+
logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
|
| 1548 |
+
use_cache = False
|
| 1549 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 1550 |
+
decoder_input_ids = shift_tokens_right(
|
| 1551 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 1552 |
+
)
|
| 1553 |
+
|
| 1554 |
+
outputs = self.model(
|
| 1555 |
+
input_ids,
|
| 1556 |
+
attention_mask=attention_mask,
|
| 1557 |
+
decoder_input_ids=decoder_input_ids,
|
| 1558 |
+
encoder_outputs=encoder_outputs,
|
| 1559 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1560 |
+
past_key_values=past_key_values,
|
| 1561 |
+
inputs_embeds=inputs_embeds,
|
| 1562 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1563 |
+
use_cache=use_cache,
|
| 1564 |
+
output_attentions=output_attentions,
|
| 1565 |
+
output_hidden_states=output_hidden_states,
|
| 1566 |
+
return_dict=return_dict,
|
| 1567 |
+
)
|
| 1568 |
+
lm_logits = self.lm_head(outputs[0])
|
| 1569 |
+
|
| 1570 |
+
masked_lm_loss = None
|
| 1571 |
+
if labels is not None:
|
| 1572 |
+
loss_fct = CrossEntropyLoss()
|
| 1573 |
+
masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1574 |
+
|
| 1575 |
+
if not return_dict:
|
| 1576 |
+
output = (lm_logits,) + outputs[1:]
|
| 1577 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 1578 |
+
|
| 1579 |
+
return Seq2SeqLMOutput(
|
| 1580 |
+
loss=masked_lm_loss,
|
| 1581 |
+
logits=lm_logits,
|
| 1582 |
+
past_key_values=outputs.past_key_values,
|
| 1583 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1584 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1585 |
+
cross_attentions=outputs.cross_attentions,
|
| 1586 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1587 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 1588 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 1589 |
+
)
|
| 1590 |
+
|
| 1591 |
+
def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
|
| 1592 |
+
return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
|
| 1593 |
+
|
| 1594 |
+
@staticmethod
|
| 1595 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 1596 |
+
reordered_past = ()
|
| 1597 |
+
for layer_past in past_key_values:
|
| 1598 |
+
# cached cross_attention states don't have to be reordered -> they are always the same
|
| 1599 |
+
reordered_past += (
|
| 1600 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past[:2])
|
| 1601 |
+
+ layer_past[2:],
|
| 1602 |
+
)
|
| 1603 |
+
return reordered_past
|
| 1604 |
+
|
| 1605 |
+
|
| 1606 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoderWrapper with Bart->PegasusX
|
| 1607 |
+
class PegasusXDecoderWrapper(PegasusXPreTrainedModel):
|
| 1608 |
+
"""
|
| 1609 |
+
This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
|
| 1610 |
+
used in combination with the [`EncoderDecoderModel`] framework.
|
| 1611 |
+
"""
|
| 1612 |
+
|
| 1613 |
+
def __init__(self, config):
|
| 1614 |
+
super().__init__(config)
|
| 1615 |
+
self.decoder = PegasusXDecoder(config)
|
| 1616 |
+
|
| 1617 |
+
def forward(self, *args, **kwargs):
|
| 1618 |
+
return self.decoder(*args, **kwargs)
|
| 1619 |
+
|
| 1620 |
+
|
| 1621 |
+
__all__ = ["PegasusXForConditionalGeneration", "PegasusXModel", "PegasusXPreTrainedModel"]
|
janus/lib/python3.10/site-packages/transformers/models/phi3/__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_phi3 import *
|
| 22 |
+
from .modeling_phi3 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__)
|
janus/lib/python3.10/site-packages/transformers/models/phi3/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (531 Bytes). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/phi3/__pycache__/configuration_phi3.cpython-310.pyc
ADDED
|
Binary file (8.73 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/phi3/__pycache__/modeling_phi3.cpython-310.pyc
ADDED
|
Binary file (37.5 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/phi3/__pycache__/modular_phi3.cpython-310.pyc
ADDED
|
Binary file (10.2 kB). View file
|
|
|
janus/lib/python3.10/site-packages/transformers/models/phi3/configuration_phi3.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
"""Phi-3 model configuration"""
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PretrainedConfig
|
| 19 |
+
from ...utils import logging
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Phi3Config(PretrainedConfig):
|
| 26 |
+
r"""
|
| 27 |
+
This is the configuration class to store the configuration of a [`Phi3Model`]. It is used to instantiate a Phi-3
|
| 28 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 29 |
+
defaults will yield a similar configuration to that of the
|
| 30 |
+
[microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct).
|
| 31 |
+
|
| 32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 33 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
vocab_size (`int`, *optional*, defaults to 32064):
|
| 37 |
+
Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the
|
| 38 |
+
`inputs_ids` passed when calling [`Phi3Model`].
|
| 39 |
+
hidden_size (`int`, *optional*, defaults to 3072):
|
| 40 |
+
Dimension of the hidden representations.
|
| 41 |
+
intermediate_size (`int`, *optional*, defaults to 8192):
|
| 42 |
+
Dimension of the MLP representations.
|
| 43 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
| 44 |
+
Number of hidden layers in the Transformer decoder.
|
| 45 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
| 46 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 47 |
+
num_key_value_heads (`int`, *optional*):
|
| 48 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 49 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 50 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 51 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 52 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
| 53 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
| 54 |
+
`num_attention_heads`.
|
| 55 |
+
resid_pdrop (`float`, *optional*, defaults to 0.0):
|
| 56 |
+
Dropout probability for mlp outputs.
|
| 57 |
+
embd_pdrop (`int`, *optional*, defaults to 0.0):
|
| 58 |
+
The dropout ratio for the embeddings.
|
| 59 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 60 |
+
The dropout ratio after computing the attention scores.
|
| 61 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 62 |
+
The non-linear activation function (function or string) in the decoder.
|
| 63 |
+
max_position_embeddings (`int`, *optional*, defaults to 4096):
|
| 64 |
+
The maximum sequence length that this model might ever be used with.
|
| 65 |
+
original_max_position_embeddings (`int`, *optional*, defaults to 4096):
|
| 66 |
+
The maximum sequence length that this model was trained with. This is used to determine the size of the
|
| 67 |
+
original RoPE embeddings when using long scaling.
|
| 68 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 69 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 70 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 71 |
+
The epsilon value used for the RMSNorm.
|
| 72 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 73 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 74 |
+
relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
|
| 75 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 76 |
+
Whether to tie weight embeddings
|
| 77 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
| 78 |
+
The base period of the RoPE embeddings.
|
| 79 |
+
rope_scaling (`dict`, *optional*):
|
| 80 |
+
The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
|
| 81 |
+
contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be `longrope` and
|
| 82 |
+
the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
|
| 83 |
+
divided by the number of attention heads divided by 2.
|
| 84 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
| 85 |
+
The id of the "beginning-of-sequence" token.
|
| 86 |
+
eos_token_id (`int`, *optional*, defaults to 32000):
|
| 87 |
+
The id of the "end-of-sequence" token.
|
| 88 |
+
pad_token_id (`int`, *optional*, defaults to 32000):
|
| 89 |
+
The id of the padding token.
|
| 90 |
+
sliding_window (`int`, *optional*):
|
| 91 |
+
Sliding window attention window size. If `None`, no sliding window is applied.
|
| 92 |
+
|
| 93 |
+
Example:
|
| 94 |
+
|
| 95 |
+
```python
|
| 96 |
+
>>> from transformers import Phi3Model, Phi3Config
|
| 97 |
+
|
| 98 |
+
>>> # Initializing a Phi-3 style configuration
|
| 99 |
+
>>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
|
| 100 |
+
|
| 101 |
+
>>> # Initializing a model from the configuration
|
| 102 |
+
>>> model = Phi3Model(configuration)
|
| 103 |
+
|
| 104 |
+
>>> # Accessing the model configuration
|
| 105 |
+
>>> configuration = model.config
|
| 106 |
+
```"""
|
| 107 |
+
|
| 108 |
+
model_type = "phi3"
|
| 109 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 110 |
+
|
| 111 |
+
def __init__(
|
| 112 |
+
self,
|
| 113 |
+
vocab_size=32064,
|
| 114 |
+
hidden_size=3072,
|
| 115 |
+
intermediate_size=8192,
|
| 116 |
+
num_hidden_layers=32,
|
| 117 |
+
num_attention_heads=32,
|
| 118 |
+
num_key_value_heads=None,
|
| 119 |
+
resid_pdrop=0.0,
|
| 120 |
+
embd_pdrop=0.0,
|
| 121 |
+
attention_dropout=0.0,
|
| 122 |
+
hidden_act="silu",
|
| 123 |
+
max_position_embeddings=4096,
|
| 124 |
+
original_max_position_embeddings=4096,
|
| 125 |
+
initializer_range=0.02,
|
| 126 |
+
rms_norm_eps=1e-5,
|
| 127 |
+
use_cache=True,
|
| 128 |
+
tie_word_embeddings=False,
|
| 129 |
+
rope_theta=10000.0,
|
| 130 |
+
rope_scaling=None,
|
| 131 |
+
bos_token_id=1,
|
| 132 |
+
eos_token_id=32000,
|
| 133 |
+
pad_token_id=32000,
|
| 134 |
+
sliding_window=None,
|
| 135 |
+
**kwargs,
|
| 136 |
+
):
|
| 137 |
+
self.vocab_size = vocab_size
|
| 138 |
+
self.hidden_size = hidden_size
|
| 139 |
+
self.intermediate_size = intermediate_size
|
| 140 |
+
self.num_hidden_layers = num_hidden_layers
|
| 141 |
+
self.num_attention_heads = num_attention_heads
|
| 142 |
+
|
| 143 |
+
if num_key_value_heads is None:
|
| 144 |
+
num_key_value_heads = num_attention_heads
|
| 145 |
+
|
| 146 |
+
self.num_key_value_heads = num_key_value_heads
|
| 147 |
+
self.resid_pdrop = resid_pdrop
|
| 148 |
+
self.embd_pdrop = embd_pdrop
|
| 149 |
+
self.attention_dropout = attention_dropout
|
| 150 |
+
self.hidden_act = hidden_act
|
| 151 |
+
self.max_position_embeddings = max_position_embeddings
|
| 152 |
+
self.original_max_position_embeddings = original_max_position_embeddings
|
| 153 |
+
self.initializer_range = initializer_range
|
| 154 |
+
self.rms_norm_eps = rms_norm_eps
|
| 155 |
+
self.use_cache = use_cache
|
| 156 |
+
self.rope_theta = rope_theta
|
| 157 |
+
self.rope_scaling = rope_scaling
|
| 158 |
+
self._rope_scaling_adjustment()
|
| 159 |
+
self._rope_scaling_validation()
|
| 160 |
+
self.sliding_window = sliding_window
|
| 161 |
+
|
| 162 |
+
super().__init__(
|
| 163 |
+
bos_token_id=bos_token_id,
|
| 164 |
+
eos_token_id=eos_token_id,
|
| 165 |
+
pad_token_id=pad_token_id,
|
| 166 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 167 |
+
**kwargs,
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
def _rope_scaling_adjustment(self):
|
| 171 |
+
"""
|
| 172 |
+
Adjust the `type` of the `rope_scaling` configuration for backward compatibility.
|
| 173 |
+
"""
|
| 174 |
+
if self.rope_scaling is None:
|
| 175 |
+
return
|
| 176 |
+
|
| 177 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
| 178 |
+
|
| 179 |
+
# For backward compatibility if previous version used "su" or "yarn"
|
| 180 |
+
if rope_scaling_type is not None and rope_scaling_type in ["su", "yarn"]:
|
| 181 |
+
self.rope_scaling["type"] = "longrope"
|
| 182 |
+
|
| 183 |
+
def _rope_scaling_validation(self):
|
| 184 |
+
"""
|
| 185 |
+
Validate the `rope_scaling` configuration.
|
| 186 |
+
"""
|
| 187 |
+
if self.rope_scaling is None:
|
| 188 |
+
return
|
| 189 |
+
|
| 190 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
|
| 191 |
+
raise ValueError(
|
| 192 |
+
"`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
|
| 193 |
+
f"got {self.rope_scaling}"
|
| 194 |
+
)
|
| 195 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
| 196 |
+
rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
|
| 197 |
+
rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
|
| 198 |
+
if rope_scaling_type is None or rope_scaling_type not in ["longrope"]:
|
| 199 |
+
raise ValueError(f"`rope_scaling`'s type field must be one of ['longrope'], got {rope_scaling_type}")
|
| 200 |
+
if not (
|
| 201 |
+
isinstance(rope_scaling_short_factor, list)
|
| 202 |
+
and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
|
| 203 |
+
):
|
| 204 |
+
raise ValueError(
|
| 205 |
+
f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
|
| 206 |
+
)
|
| 207 |
+
if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
|
| 208 |
+
raise ValueError(
|
| 209 |
+
f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
|
| 210 |
+
)
|
| 211 |
+
if not (
|
| 212 |
+
isinstance(rope_scaling_long_factor, list)
|
| 213 |
+
and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
|
| 214 |
+
):
|
| 215 |
+
raise ValueError(
|
| 216 |
+
f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
|
| 217 |
+
)
|
| 218 |
+
if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
|
| 219 |
+
raise ValueError(
|
| 220 |
+
f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
__all__ = ["Phi3Config"]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🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/phi3/modular_phi3.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_phi3.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
from typing import Callable, List, Optional, Tuple, Union
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
from torch import nn
|
| 27 |
+
|
| 28 |
+
from ...activations import ACT2FN
|
| 29 |
+
from ...cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
|
| 30 |
+
from ...generation import GenerationMixin
|
| 31 |
+
from ...modeling_attn_mask_utils import AttentionMaskConverter
|
| 32 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 33 |
+
from ...modeling_outputs import (
|
| 34 |
+
BaseModelOutputWithPast,
|
| 35 |
+
CausalLMOutputWithPast,
|
| 36 |
+
SequenceClassifierOutputWithPast,
|
| 37 |
+
TokenClassifierOutput,
|
| 38 |
+
)
|
| 39 |
+
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
| 40 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 41 |
+
from ...processing_utils import Unpack
|
| 42 |
+
from ...utils import (
|
| 43 |
+
LossKwargs,
|
| 44 |
+
add_code_sample_docstrings,
|
| 45 |
+
add_start_docstrings,
|
| 46 |
+
add_start_docstrings_to_model_forward,
|
| 47 |
+
logging,
|
| 48 |
+
replace_return_docstrings,
|
| 49 |
+
)
|
| 50 |
+
from .configuration_phi3 import Phi3Config
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
logger = logging.get_logger(__name__)
|
| 54 |
+
|
| 55 |
+
_CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
|
| 56 |
+
_CONFIG_FOR_DOC = "Phi3Config"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class Phi3MLP(nn.Module):
|
| 60 |
+
def __init__(self, config):
|
| 61 |
+
super().__init__()
|
| 62 |
+
|
| 63 |
+
self.config = config
|
| 64 |
+
self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
|
| 65 |
+
self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
|
| 66 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 67 |
+
|
| 68 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
|
| 69 |
+
up_states = self.gate_up_proj(hidden_states)
|
| 70 |
+
|
| 71 |
+
gate, up_states = up_states.chunk(2, dim=-1)
|
| 72 |
+
up_states = up_states * self.activation_fn(gate)
|
| 73 |
+
|
| 74 |
+
return self.down_proj(up_states)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def rotate_half(x):
|
| 78 |
+
"""Rotates half the hidden dims of the input."""
|
| 79 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 80 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 81 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 85 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
q (`torch.Tensor`): The query tensor.
|
| 89 |
+
k (`torch.Tensor`): The key tensor.
|
| 90 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 91 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 92 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 93 |
+
Deprecated and unused.
|
| 94 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 95 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 96 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 97 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 98 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 99 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 100 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 101 |
+
Returns:
|
| 102 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 103 |
+
"""
|
| 104 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 105 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 106 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 107 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 108 |
+
return q_embed, k_embed
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 112 |
+
"""
|
| 113 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 114 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 115 |
+
"""
|
| 116 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 117 |
+
if n_rep == 1:
|
| 118 |
+
return hidden_states
|
| 119 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 120 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def eager_attention_forward(
|
| 124 |
+
module: nn.Module,
|
| 125 |
+
query: torch.Tensor,
|
| 126 |
+
key: torch.Tensor,
|
| 127 |
+
value: torch.Tensor,
|
| 128 |
+
attention_mask: Optional[torch.Tensor],
|
| 129 |
+
scaling: float,
|
| 130 |
+
dropout: float = 0.0,
|
| 131 |
+
**kwargs,
|
| 132 |
+
):
|
| 133 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 134 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 135 |
+
|
| 136 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 137 |
+
if attention_mask is not None:
|
| 138 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 139 |
+
attn_weights = attn_weights + causal_mask
|
| 140 |
+
|
| 141 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 142 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 143 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 144 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 145 |
+
|
| 146 |
+
return attn_output, attn_weights
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class Phi3Attention(nn.Module):
|
| 150 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 151 |
+
|
| 152 |
+
def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
|
| 153 |
+
super().__init__()
|
| 154 |
+
self.config = config
|
| 155 |
+
self.layer_idx = layer_idx
|
| 156 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 157 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 158 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 159 |
+
self.scaling = self.head_dim**-0.5
|
| 160 |
+
self.attention_dropout = config.attention_dropout
|
| 161 |
+
self.is_causal = True
|
| 162 |
+
|
| 163 |
+
op_size = config.num_attention_heads * self.head_dim + 2 * (config.num_key_value_heads * self.head_dim)
|
| 164 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
| 165 |
+
self.qkv_proj = nn.Linear(config.hidden_size, op_size, bias=False)
|
| 166 |
+
|
| 167 |
+
def forward(
|
| 168 |
+
self,
|
| 169 |
+
hidden_states: torch.Tensor,
|
| 170 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
| 171 |
+
attention_mask: Optional[torch.Tensor],
|
| 172 |
+
past_key_value: Optional[Cache] = None,
|
| 173 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 174 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 175 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 176 |
+
input_shape = hidden_states.shape[:-1]
|
| 177 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 178 |
+
|
| 179 |
+
qkv = self.qkv_proj(hidden_states)
|
| 180 |
+
query_pos = self.config.num_attention_heads * self.head_dim
|
| 181 |
+
query_states = qkv[..., :query_pos]
|
| 182 |
+
key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
|
| 183 |
+
value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
|
| 184 |
+
|
| 185 |
+
query_states = query_states.view(hidden_shape).transpose(1, 2)
|
| 186 |
+
key_states = key_states.view(hidden_shape).transpose(1, 2)
|
| 187 |
+
value_states = value_states.view(hidden_shape).transpose(1, 2)
|
| 188 |
+
|
| 189 |
+
cos, sin = position_embeddings
|
| 190 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 191 |
+
|
| 192 |
+
if past_key_value is not None:
|
| 193 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 194 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 195 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 196 |
+
|
| 197 |
+
attention_interface: Callable = eager_attention_forward
|
| 198 |
+
if self.config._attn_implementation != "eager":
|
| 199 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
| 200 |
+
logger.warning_once(
|
| 201 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
| 202 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 203 |
+
)
|
| 204 |
+
else:
|
| 205 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 206 |
+
|
| 207 |
+
attn_output, attn_weights = attention_interface(
|
| 208 |
+
self,
|
| 209 |
+
query_states,
|
| 210 |
+
key_states,
|
| 211 |
+
value_states,
|
| 212 |
+
attention_mask,
|
| 213 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 214 |
+
scaling=self.scaling,
|
| 215 |
+
sliding_window=getattr(self.config, "sliding_window", None),
|
| 216 |
+
**kwargs,
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 220 |
+
attn_output = self.o_proj(attn_output)
|
| 221 |
+
return attn_output, attn_weights
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
class Phi3RMSNorm(nn.Module):
|
| 225 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 226 |
+
"""
|
| 227 |
+
Phi3RMSNorm is equivalent to T5LayerNorm
|
| 228 |
+
"""
|
| 229 |
+
super().__init__()
|
| 230 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 231 |
+
self.variance_epsilon = eps
|
| 232 |
+
|
| 233 |
+
def forward(self, hidden_states):
|
| 234 |
+
input_dtype = hidden_states.dtype
|
| 235 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 236 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 237 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 238 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 239 |
+
|
| 240 |
+
def extra_repr(self):
|
| 241 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
class Phi3DecoderLayer(nn.Module):
|
| 245 |
+
def __init__(self, config: Phi3Config, layer_idx: int):
|
| 246 |
+
super().__init__()
|
| 247 |
+
self.hidden_size = config.hidden_size
|
| 248 |
+
self.self_attn = Phi3Attention(config=config, layer_idx=layer_idx)
|
| 249 |
+
self.mlp = Phi3MLP(config)
|
| 250 |
+
self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 251 |
+
self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 252 |
+
self.config = config
|
| 253 |
+
self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
|
| 254 |
+
self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
|
| 255 |
+
|
| 256 |
+
def forward(
|
| 257 |
+
self,
|
| 258 |
+
hidden_states: torch.Tensor,
|
| 259 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 260 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 261 |
+
past_key_value: Optional[Cache] = None,
|
| 262 |
+
output_attentions: Optional[bool] = False,
|
| 263 |
+
use_cache: Optional[bool] = False,
|
| 264 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 265 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
| 266 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 267 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 268 |
+
"""
|
| 269 |
+
Args:
|
| 270 |
+
hidden_states (`torch.FloatTensor`):
|
| 271 |
+
input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 272 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
| 273 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 274 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 275 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
|
| 276 |
+
`[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
|
| 277 |
+
past_key_value (`Cache`, *optional*): cached past key and value projection states
|
| 278 |
+
output_attentions (`bool`, *optional*):
|
| 279 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 280 |
+
returned tensors for more detail.
|
| 281 |
+
use_cache (`bool`, *optional*):
|
| 282 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 283 |
+
(see `past_key_values`).
|
| 284 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 285 |
+
Indices depicting the position of the input sequence tokens in the sequence
|
| 286 |
+
kwargs (`dict`, *optional*):
|
| 287 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
| 288 |
+
into the model
|
| 289 |
+
"""
|
| 290 |
+
residual = hidden_states
|
| 291 |
+
|
| 292 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 293 |
+
|
| 294 |
+
# Self Attention
|
| 295 |
+
hidden_states, self_attn_weights = self.self_attn(
|
| 296 |
+
hidden_states=hidden_states,
|
| 297 |
+
attention_mask=attention_mask,
|
| 298 |
+
position_ids=position_ids,
|
| 299 |
+
past_key_value=past_key_value,
|
| 300 |
+
output_attentions=output_attentions,
|
| 301 |
+
use_cache=use_cache,
|
| 302 |
+
cache_position=cache_position,
|
| 303 |
+
position_embeddings=position_embeddings,
|
| 304 |
+
**kwargs,
|
| 305 |
+
)
|
| 306 |
+
hidden_states = residual + self.resid_attn_dropout(hidden_states) # main diff with Llama
|
| 307 |
+
|
| 308 |
+
residual = hidden_states
|
| 309 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 310 |
+
hidden_states = self.mlp(hidden_states)
|
| 311 |
+
hidden_states = residual + self.resid_mlp_dropout(hidden_states) # main diff with Llama
|
| 312 |
+
|
| 313 |
+
outputs = (hidden_states,)
|
| 314 |
+
if output_attentions:
|
| 315 |
+
outputs += (self_attn_weights,)
|
| 316 |
+
|
| 317 |
+
return outputs
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
class Phi3RotaryEmbedding(nn.Module):
|
| 321 |
+
def __init__(self, config: Phi3Config, device=None):
|
| 322 |
+
super().__init__()
|
| 323 |
+
# BC: "rope_type" was originally "type"
|
| 324 |
+
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
| 325 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
| 326 |
+
else:
|
| 327 |
+
self.rope_type = "default"
|
| 328 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 329 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 330 |
+
|
| 331 |
+
self.config = config
|
| 332 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 333 |
+
|
| 334 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
| 335 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 336 |
+
self.original_inv_freq = self.inv_freq
|
| 337 |
+
|
| 338 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
| 339 |
+
"""
|
| 340 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
| 341 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
| 342 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
| 343 |
+
"""
|
| 344 |
+
seq_len = torch.max(position_ids) + 1
|
| 345 |
+
if seq_len > self.max_seq_len_cached: # growth
|
| 346 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
|
| 347 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
| 348 |
+
self.max_seq_len_cached = seq_len
|
| 349 |
+
|
| 350 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
| 351 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
| 352 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
| 353 |
+
|
| 354 |
+
@torch.no_grad()
|
| 355 |
+
def forward(self, x, position_ids):
|
| 356 |
+
if "dynamic" in self.rope_type:
|
| 357 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
| 358 |
+
elif self.rope_type == "longrope":
|
| 359 |
+
self._longrope_frequency_update(position_ids, device=x.device)
|
| 360 |
+
|
| 361 |
+
# Core RoPE block
|
| 362 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
| 363 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 364 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
| 365 |
+
device_type = x.device.type
|
| 366 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
| 367 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
| 368 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 369 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 370 |
+
cos = emb.cos()
|
| 371 |
+
sin = emb.sin()
|
| 372 |
+
|
| 373 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
| 374 |
+
cos = cos * self.attention_scaling
|
| 375 |
+
sin = sin * self.attention_scaling
|
| 376 |
+
|
| 377 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 378 |
+
|
| 379 |
+
def _longrope_frequency_update(self, position_ids, device):
|
| 380 |
+
"""Longrope uses long factor if sequence is larger than original pretraining length, short otherwise."""
|
| 381 |
+
seq_len = torch.max(position_ids) + 1
|
| 382 |
+
if hasattr(self.config, "original_max_position_embeddings"):
|
| 383 |
+
original_max_position_embeddings = self.config.original_max_position_embeddings
|
| 384 |
+
else:
|
| 385 |
+
original_max_position_embeddings = self.config.max_position_embeddings
|
| 386 |
+
if seq_len > original_max_position_embeddings:
|
| 387 |
+
if not hasattr(self, "long_inv_freq"):
|
| 388 |
+
self.long_inv_freq, _ = self.rope_init_fn(
|
| 389 |
+
self.config, device, seq_len=original_max_position_embeddings + 1
|
| 390 |
+
)
|
| 391 |
+
self.register_buffer("inv_freq", self.long_inv_freq, persistent=False)
|
| 392 |
+
else:
|
| 393 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
PHI3_START_DOCSTRING = r"""
|
| 397 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 398 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 399 |
+
etc.)
|
| 400 |
+
|
| 401 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 402 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 403 |
+
and behavior.
|
| 404 |
+
|
| 405 |
+
Parameters:
|
| 406 |
+
config ([`Phi3Config`]):
|
| 407 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 408 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 409 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 410 |
+
"""
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
@add_start_docstrings(
|
| 414 |
+
"The bare Phi3 Model outputting raw hidden-states without any specific head on top.",
|
| 415 |
+
PHI3_START_DOCSTRING,
|
| 416 |
+
)
|
| 417 |
+
class Phi3PreTrainedModel(PreTrainedModel):
|
| 418 |
+
config_class = Phi3Config
|
| 419 |
+
base_model_prefix = "model"
|
| 420 |
+
supports_gradient_checkpointing = True
|
| 421 |
+
_no_split_modules = ["Phi3DecoderLayer"]
|
| 422 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 423 |
+
_supports_flash_attn_2 = True
|
| 424 |
+
_supports_sdpa = True
|
| 425 |
+
_supports_flex_attn = True
|
| 426 |
+
_supports_cache_class = True
|
| 427 |
+
_supports_quantized_cache = True
|
| 428 |
+
_supports_static_cache = True
|
| 429 |
+
_version = "0.0.5"
|
| 430 |
+
|
| 431 |
+
def _init_weights(self, module):
|
| 432 |
+
std = self.config.initializer_range
|
| 433 |
+
if isinstance(module, nn.Linear):
|
| 434 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 435 |
+
if module.bias is not None:
|
| 436 |
+
module.bias.data.zero_()
|
| 437 |
+
elif isinstance(module, nn.Embedding):
|
| 438 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 439 |
+
if module.padding_idx is not None:
|
| 440 |
+
module.weight.data[module.padding_idx].zero_()
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
PHI3_INPUTS_DOCSTRING = r"""
|
| 444 |
+
Args:
|
| 445 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 446 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 447 |
+
it.
|
| 448 |
+
|
| 449 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 450 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 451 |
+
|
| 452 |
+
[What are input IDs?](../glossary#input-ids)
|
| 453 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 454 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 455 |
+
|
| 456 |
+
- 1 for tokens that are **not masked**,
|
| 457 |
+
- 0 for tokens that are **masked**.
|
| 458 |
+
|
| 459 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 460 |
+
|
| 461 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 462 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 463 |
+
|
| 464 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
| 465 |
+
`past_key_values`).
|
| 466 |
+
|
| 467 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
| 468 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
| 469 |
+
information on the default strategy.
|
| 470 |
+
|
| 471 |
+
- 1 indicates the head is **not masked**,
|
| 472 |
+
- 0 indicates the head is **masked**.
|
| 473 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 474 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 475 |
+
config.n_positions - 1]`.
|
| 476 |
+
|
| 477 |
+
[What are position IDs?](../glossary#position-ids)
|
| 478 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
| 479 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 480 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
| 481 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
| 482 |
+
|
| 483 |
+
Two formats are allowed:
|
| 484 |
+
- a [`~cache_utils.Cache`] instance, see our
|
| 485 |
+
[kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
|
| 486 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 487 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
| 488 |
+
cache format.
|
| 489 |
+
|
| 490 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
| 491 |
+
legacy cache format will be returned.
|
| 492 |
+
|
| 493 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
| 494 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
| 495 |
+
of shape `(batch_size, sequence_length)`.
|
| 496 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 497 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 498 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 499 |
+
model's internal embedding lookup matrix.
|
| 500 |
+
use_cache (`bool`, *optional*):
|
| 501 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 502 |
+
`past_key_values`).
|
| 503 |
+
output_attentions (`bool`, *optional*):
|
| 504 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 505 |
+
tensors for more detail.
|
| 506 |
+
output_hidden_states (`bool`, *optional*):
|
| 507 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 508 |
+
more detail.
|
| 509 |
+
return_dict (`bool`, *optional*):
|
| 510 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 511 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 512 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
| 513 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
| 514 |
+
the complete sequence length.
|
| 515 |
+
"""
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
@add_start_docstrings(
|
| 519 |
+
"The bare Phi3 Model outputting raw hidden-states without any specific head on top.",
|
| 520 |
+
PHI3_START_DOCSTRING,
|
| 521 |
+
)
|
| 522 |
+
class Phi3Model(Phi3PreTrainedModel):
|
| 523 |
+
"""
|
| 524 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
|
| 525 |
+
|
| 526 |
+
Args:
|
| 527 |
+
config: Phi3Config
|
| 528 |
+
"""
|
| 529 |
+
|
| 530 |
+
def __init__(self, config: Phi3Config):
|
| 531 |
+
super().__init__(config)
|
| 532 |
+
self.padding_idx = config.pad_token_id
|
| 533 |
+
self.vocab_size = config.vocab_size
|
| 534 |
+
|
| 535 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 536 |
+
self.layers = nn.ModuleList(
|
| 537 |
+
[Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 538 |
+
)
|
| 539 |
+
self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 540 |
+
self.rotary_emb = Phi3RotaryEmbedding(config=config)
|
| 541 |
+
self.gradient_checkpointing = False
|
| 542 |
+
|
| 543 |
+
# Initialize weights and apply final processing
|
| 544 |
+
self.post_init()
|
| 545 |
+
|
| 546 |
+
def get_input_embeddings(self):
|
| 547 |
+
return self.embed_tokens
|
| 548 |
+
|
| 549 |
+
def set_input_embeddings(self, value):
|
| 550 |
+
self.embed_tokens = value
|
| 551 |
+
|
| 552 |
+
@add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
|
| 553 |
+
def forward(
|
| 554 |
+
self,
|
| 555 |
+
input_ids: torch.LongTensor = None,
|
| 556 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 557 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 558 |
+
past_key_values: Optional[Cache] = None,
|
| 559 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 560 |
+
use_cache: Optional[bool] = None,
|
| 561 |
+
output_attentions: Optional[bool] = None,
|
| 562 |
+
output_hidden_states: Optional[bool] = None,
|
| 563 |
+
return_dict: Optional[bool] = None,
|
| 564 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 565 |
+
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
|
| 566 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 567 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 568 |
+
output_hidden_states = (
|
| 569 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 570 |
+
)
|
| 571 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 572 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 573 |
+
|
| 574 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 575 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 576 |
+
|
| 577 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
| 578 |
+
logger.warning_once(
|
| 579 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
| 580 |
+
)
|
| 581 |
+
use_cache = False
|
| 582 |
+
|
| 583 |
+
if inputs_embeds is None:
|
| 584 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 585 |
+
|
| 586 |
+
if use_cache and past_key_values is None:
|
| 587 |
+
past_key_values = DynamicCache()
|
| 588 |
+
|
| 589 |
+
if cache_position is None:
|
| 590 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 591 |
+
cache_position = torch.arange(
|
| 592 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
if position_ids is None:
|
| 596 |
+
position_ids = cache_position.unsqueeze(0)
|
| 597 |
+
|
| 598 |
+
causal_mask = self._update_causal_mask(
|
| 599 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
hidden_states = inputs_embeds
|
| 603 |
+
|
| 604 |
+
# create position embeddings to be shared across the decoder layers
|
| 605 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 606 |
+
|
| 607 |
+
# decoder layers
|
| 608 |
+
all_hidden_states = () if output_hidden_states else None
|
| 609 |
+
all_self_attns = () if output_attentions else None
|
| 610 |
+
|
| 611 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
| 612 |
+
if output_hidden_states:
|
| 613 |
+
all_hidden_states += (hidden_states,)
|
| 614 |
+
|
| 615 |
+
if self.gradient_checkpointing and self.training:
|
| 616 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 617 |
+
decoder_layer.__call__,
|
| 618 |
+
hidden_states,
|
| 619 |
+
causal_mask,
|
| 620 |
+
position_ids,
|
| 621 |
+
past_key_values,
|
| 622 |
+
output_attentions,
|
| 623 |
+
use_cache,
|
| 624 |
+
cache_position,
|
| 625 |
+
position_embeddings,
|
| 626 |
+
)
|
| 627 |
+
else:
|
| 628 |
+
layer_outputs = decoder_layer(
|
| 629 |
+
hidden_states,
|
| 630 |
+
attention_mask=causal_mask,
|
| 631 |
+
position_ids=position_ids,
|
| 632 |
+
past_key_value=past_key_values,
|
| 633 |
+
output_attentions=output_attentions,
|
| 634 |
+
use_cache=use_cache,
|
| 635 |
+
cache_position=cache_position,
|
| 636 |
+
position_embeddings=position_embeddings,
|
| 637 |
+
**flash_attn_kwargs,
|
| 638 |
+
)
|
| 639 |
+
|
| 640 |
+
hidden_states = layer_outputs[0]
|
| 641 |
+
|
| 642 |
+
if output_attentions:
|
| 643 |
+
all_self_attns += (layer_outputs[1],)
|
| 644 |
+
|
| 645 |
+
hidden_states = self.norm(hidden_states)
|
| 646 |
+
|
| 647 |
+
# add hidden states from the last decoder layer
|
| 648 |
+
if output_hidden_states:
|
| 649 |
+
all_hidden_states += (hidden_states,)
|
| 650 |
+
|
| 651 |
+
output = BaseModelOutputWithPast(
|
| 652 |
+
last_hidden_state=hidden_states,
|
| 653 |
+
past_key_values=past_key_values if use_cache else None,
|
| 654 |
+
hidden_states=all_hidden_states,
|
| 655 |
+
attentions=all_self_attns,
|
| 656 |
+
)
|
| 657 |
+
return output if return_dict else output.to_tuple()
|
| 658 |
+
|
| 659 |
+
def _update_causal_mask(
|
| 660 |
+
self,
|
| 661 |
+
attention_mask: torch.Tensor,
|
| 662 |
+
input_tensor: torch.Tensor,
|
| 663 |
+
cache_position: torch.Tensor,
|
| 664 |
+
past_key_values: Cache,
|
| 665 |
+
output_attentions: bool,
|
| 666 |
+
):
|
| 667 |
+
if self.config._attn_implementation == "flash_attention_2":
|
| 668 |
+
if attention_mask is not None and past_key_values is not None:
|
| 669 |
+
is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]
|
| 670 |
+
if is_padding_right:
|
| 671 |
+
raise ValueError(
|
| 672 |
+
"You are attempting to perform batched generation with padding_side='right'"
|
| 673 |
+
" this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
|
| 674 |
+
" call `tokenizer.padding_side = 'left'` before tokenizing the input. "
|
| 675 |
+
)
|
| 676 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
| 677 |
+
return attention_mask
|
| 678 |
+
return None
|
| 679 |
+
|
| 680 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
| 681 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
| 682 |
+
# to infer the attention mask.
|
| 683 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 684 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
| 685 |
+
using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
|
| 686 |
+
|
| 687 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
| 688 |
+
if (
|
| 689 |
+
self.config._attn_implementation == "sdpa"
|
| 690 |
+
and not (using_static_cache or using_sliding_window_cache)
|
| 691 |
+
and not output_attentions
|
| 692 |
+
):
|
| 693 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
| 694 |
+
attention_mask,
|
| 695 |
+
inputs_embeds=input_tensor,
|
| 696 |
+
past_key_values_length=past_seen_tokens,
|
| 697 |
+
sliding_window=self.config.sliding_window,
|
| 698 |
+
is_training=self.training,
|
| 699 |
+
):
|
| 700 |
+
return None
|
| 701 |
+
|
| 702 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
| 703 |
+
min_dtype = torch.finfo(dtype).min
|
| 704 |
+
sequence_length = input_tensor.shape[1]
|
| 705 |
+
# SlidingWindowCache or StaticCache
|
| 706 |
+
if using_sliding_window_cache or using_static_cache:
|
| 707 |
+
target_length = past_key_values.get_max_cache_shape()
|
| 708 |
+
# DynamicCache or no cache
|
| 709 |
+
else:
|
| 710 |
+
target_length = (
|
| 711 |
+
attention_mask.shape[-1]
|
| 712 |
+
if isinstance(attention_mask, torch.Tensor)
|
| 713 |
+
else past_seen_tokens + sequence_length + 1
|
| 714 |
+
)
|
| 715 |
+
|
| 716 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
| 717 |
+
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
|
| 718 |
+
attention_mask,
|
| 719 |
+
sequence_length=sequence_length,
|
| 720 |
+
target_length=target_length,
|
| 721 |
+
dtype=dtype,
|
| 722 |
+
device=device,
|
| 723 |
+
cache_position=cache_position,
|
| 724 |
+
batch_size=input_tensor.shape[0],
|
| 725 |
+
config=self.config,
|
| 726 |
+
past_key_values=past_key_values,
|
| 727 |
+
)
|
| 728 |
+
|
| 729 |
+
if (
|
| 730 |
+
self.config._attn_implementation == "sdpa"
|
| 731 |
+
and attention_mask is not None
|
| 732 |
+
and attention_mask.device.type == "cuda"
|
| 733 |
+
and not output_attentions
|
| 734 |
+
):
|
| 735 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
| 736 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
| 737 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
| 738 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
| 739 |
+
|
| 740 |
+
return causal_mask
|
| 741 |
+
|
| 742 |
+
@staticmethod
|
| 743 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
| 744 |
+
attention_mask: torch.Tensor,
|
| 745 |
+
sequence_length: int,
|
| 746 |
+
target_length: int,
|
| 747 |
+
dtype: torch.dtype,
|
| 748 |
+
device: torch.device,
|
| 749 |
+
cache_position: torch.Tensor,
|
| 750 |
+
batch_size: int,
|
| 751 |
+
config: Phi3Config,
|
| 752 |
+
past_key_values: Cache,
|
| 753 |
+
):
|
| 754 |
+
"""
|
| 755 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
| 756 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
| 757 |
+
|
| 758 |
+
Args:
|
| 759 |
+
attention_mask (`torch.Tensor`):
|
| 760 |
+
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
|
| 761 |
+
sequence_length (`int`):
|
| 762 |
+
The sequence length being processed.
|
| 763 |
+
target_length (`int`):
|
| 764 |
+
The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
|
| 765 |
+
dtype (`torch.dtype`):
|
| 766 |
+
The dtype to use for the 4D attention mask.
|
| 767 |
+
device (`torch.device`):
|
| 768 |
+
The device to plcae the 4D attention mask on.
|
| 769 |
+
cache_position (`torch.Tensor`):
|
| 770 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
| 771 |
+
batch_size (`torch.Tensor`):
|
| 772 |
+
Batch size.
|
| 773 |
+
config (`Phi3Config`):
|
| 774 |
+
The model's configuration class
|
| 775 |
+
past_key_values (`Cache`):
|
| 776 |
+
The cache class that is being used currently to generate
|
| 777 |
+
"""
|
| 778 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
| 779 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
| 780 |
+
causal_mask = attention_mask
|
| 781 |
+
else:
|
| 782 |
+
min_dtype = torch.finfo(dtype).min
|
| 783 |
+
causal_mask = torch.full(
|
| 784 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
| 785 |
+
)
|
| 786 |
+
diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
| 787 |
+
if config.sliding_window is not None:
|
| 788 |
+
# if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
|
| 789 |
+
# the check is needed to verify is current checkpoint was trained with sliding window or not
|
| 790 |
+
if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
|
| 791 |
+
sliding_attend_mask = torch.arange(target_length, device=device) <= (
|
| 792 |
+
cache_position.reshape(-1, 1) - config.sliding_window
|
| 793 |
+
)
|
| 794 |
+
diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
|
| 795 |
+
causal_mask *= diagonal_attend_mask
|
| 796 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
| 797 |
+
if attention_mask is not None:
|
| 798 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
| 799 |
+
if attention_mask.shape[-1] > target_length:
|
| 800 |
+
attention_mask = attention_mask[:, :target_length]
|
| 801 |
+
mask_length = attention_mask.shape[-1]
|
| 802 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
| 803 |
+
padding_mask = padding_mask == 0
|
| 804 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
| 805 |
+
padding_mask, min_dtype
|
| 806 |
+
)
|
| 807 |
+
return causal_mask
|
| 808 |
+
|
| 809 |
+
|
| 810 |
+
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
|
| 811 |
+
|
| 812 |
+
|
| 813 |
+
class Phi3ForCausalLM(Phi3PreTrainedModel, GenerationMixin):
|
| 814 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 815 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
| 816 |
+
|
| 817 |
+
def __init__(self, config):
|
| 818 |
+
super().__init__(config)
|
| 819 |
+
self.model = Phi3Model(config)
|
| 820 |
+
self.vocab_size = config.vocab_size
|
| 821 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 822 |
+
|
| 823 |
+
# Initialize weights and apply final processing
|
| 824 |
+
self.post_init()
|
| 825 |
+
|
| 826 |
+
def get_input_embeddings(self):
|
| 827 |
+
return self.model.embed_tokens
|
| 828 |
+
|
| 829 |
+
def set_input_embeddings(self, value):
|
| 830 |
+
self.model.embed_tokens = value
|
| 831 |
+
|
| 832 |
+
def get_output_embeddings(self):
|
| 833 |
+
return self.lm_head
|
| 834 |
+
|
| 835 |
+
def set_output_embeddings(self, new_embeddings):
|
| 836 |
+
self.lm_head = new_embeddings
|
| 837 |
+
|
| 838 |
+
def set_decoder(self, decoder):
|
| 839 |
+
self.model = decoder
|
| 840 |
+
|
| 841 |
+
def get_decoder(self):
|
| 842 |
+
return self.model
|
| 843 |
+
|
| 844 |
+
@add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
|
| 845 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
| 846 |
+
def forward(
|
| 847 |
+
self,
|
| 848 |
+
input_ids: torch.LongTensor = None,
|
| 849 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 850 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 851 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 852 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 853 |
+
labels: Optional[torch.LongTensor] = None,
|
| 854 |
+
use_cache: Optional[bool] = None,
|
| 855 |
+
output_attentions: Optional[bool] = None,
|
| 856 |
+
output_hidden_states: Optional[bool] = None,
|
| 857 |
+
return_dict: Optional[bool] = None,
|
| 858 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 859 |
+
num_logits_to_keep: int = 0,
|
| 860 |
+
**kwargs: Unpack[KwargsForCausalLM],
|
| 861 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 862 |
+
r"""
|
| 863 |
+
Args:
|
| 864 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 865 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 866 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 867 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 868 |
+
|
| 869 |
+
num_logits_to_keep (`int`, *optional*):
|
| 870 |
+
Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
|
| 871 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
| 872 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
| 873 |
+
|
| 874 |
+
Returns:
|
| 875 |
+
|
| 876 |
+
Example:
|
| 877 |
+
|
| 878 |
+
```python
|
| 879 |
+
>>> from transformers import AutoTokenizer, Phi3ForCausalLM
|
| 880 |
+
|
| 881 |
+
>>> model = Phi3ForCausalLM.from_pretrained("meta-phi3/Phi3-2-7b-hf")
|
| 882 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-phi3/Phi3-2-7b-hf")
|
| 883 |
+
|
| 884 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 885 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 886 |
+
|
| 887 |
+
>>> # Generate
|
| 888 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 889 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 890 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 891 |
+
```"""
|
| 892 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 893 |
+
output_hidden_states = (
|
| 894 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 895 |
+
)
|
| 896 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 897 |
+
|
| 898 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 899 |
+
outputs = self.model(
|
| 900 |
+
input_ids=input_ids,
|
| 901 |
+
attention_mask=attention_mask,
|
| 902 |
+
position_ids=position_ids,
|
| 903 |
+
past_key_values=past_key_values,
|
| 904 |
+
inputs_embeds=inputs_embeds,
|
| 905 |
+
use_cache=use_cache,
|
| 906 |
+
output_attentions=output_attentions,
|
| 907 |
+
output_hidden_states=output_hidden_states,
|
| 908 |
+
return_dict=return_dict,
|
| 909 |
+
cache_position=cache_position,
|
| 910 |
+
**kwargs,
|
| 911 |
+
)
|
| 912 |
+
|
| 913 |
+
hidden_states = outputs[0]
|
| 914 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 915 |
+
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|
| 916 |
+
|
| 917 |
+
loss = None
|
| 918 |
+
if labels is not None:
|
| 919 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 920 |
+
|
| 921 |
+
if not return_dict:
|
| 922 |
+
output = (logits,) + outputs[1:]
|
| 923 |
+
return (loss,) + output if loss is not None else output
|
| 924 |
+
|
| 925 |
+
return CausalLMOutputWithPast(
|
| 926 |
+
loss=loss,
|
| 927 |
+
logits=logits,
|
| 928 |
+
past_key_values=outputs.past_key_values,
|
| 929 |
+
hidden_states=outputs.hidden_states,
|
| 930 |
+
attentions=outputs.attentions,
|
| 931 |
+
)
|
| 932 |
+
|
| 933 |
+
def prepare_inputs_for_generation(
|
| 934 |
+
self,
|
| 935 |
+
input_ids,
|
| 936 |
+
past_key_values=None,
|
| 937 |
+
attention_mask=None,
|
| 938 |
+
inputs_embeds=None,
|
| 939 |
+
cache_position=None,
|
| 940 |
+
position_ids=None,
|
| 941 |
+
use_cache=True,
|
| 942 |
+
num_logits_to_keep=None,
|
| 943 |
+
**kwargs,
|
| 944 |
+
):
|
| 945 |
+
# Overwritten -- this model may need to switch between short and long rope, invalidating the cache in the
|
| 946 |
+
# process
|
| 947 |
+
|
| 948 |
+
# When the first time input length reached long and short factor switching point, enforce re-compute cache
|
| 949 |
+
# It will cause downside of slower at this single token position, however, better than current failure.
|
| 950 |
+
if (
|
| 951 |
+
past_key_values
|
| 952 |
+
and self.config.rope_scaling
|
| 953 |
+
and input_ids.shape[1] >= self.config.original_max_position_embeddings + 1
|
| 954 |
+
):
|
| 955 |
+
past_length = cache_position[0]
|
| 956 |
+
if past_length <= self.config.original_max_position_embeddings:
|
| 957 |
+
past_key_values = None
|
| 958 |
+
|
| 959 |
+
model_inputs = super().prepare_inputs_for_generation(
|
| 960 |
+
input_ids=input_ids,
|
| 961 |
+
past_key_values=past_key_values,
|
| 962 |
+
attention_mask=attention_mask,
|
| 963 |
+
inputs_embeds=inputs_embeds,
|
| 964 |
+
cache_position=cache_position,
|
| 965 |
+
position_ids=position_ids,
|
| 966 |
+
use_cache=use_cache,
|
| 967 |
+
num_logits_to_keep=num_logits_to_keep,
|
| 968 |
+
**kwargs,
|
| 969 |
+
)
|
| 970 |
+
return model_inputs
|
| 971 |
+
|
| 972 |
+
|
| 973 |
+
@add_start_docstrings(
|
| 974 |
+
"""
|
| 975 |
+
The Phi3 Model transformer with a sequence classification head on top (linear layer).
|
| 976 |
+
|
| 977 |
+
[`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
| 978 |
+
(e.g. GPT-2) do.
|
| 979 |
+
|
| 980 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
| 981 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
| 982 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
| 983 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
| 984 |
+
each row of the batch).
|
| 985 |
+
""",
|
| 986 |
+
PHI3_START_DOCSTRING,
|
| 987 |
+
)
|
| 988 |
+
class Phi3ForSequenceClassification(Phi3PreTrainedModel):
|
| 989 |
+
def __init__(self, config):
|
| 990 |
+
super().__init__(config)
|
| 991 |
+
self.num_labels = config.num_labels
|
| 992 |
+
self.model = Phi3Model(config)
|
| 993 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
| 994 |
+
|
| 995 |
+
# Initialize weights and apply final processing
|
| 996 |
+
self.post_init()
|
| 997 |
+
|
| 998 |
+
def get_input_embeddings(self):
|
| 999 |
+
return self.model.embed_tokens
|
| 1000 |
+
|
| 1001 |
+
def set_input_embeddings(self, value):
|
| 1002 |
+
self.model.embed_tokens = value
|
| 1003 |
+
|
| 1004 |
+
@add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
|
| 1005 |
+
def forward(
|
| 1006 |
+
self,
|
| 1007 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1008 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1009 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1010 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 1011 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1012 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1013 |
+
use_cache: Optional[bool] = None,
|
| 1014 |
+
output_attentions: Optional[bool] = None,
|
| 1015 |
+
output_hidden_states: Optional[bool] = None,
|
| 1016 |
+
return_dict: Optional[bool] = None,
|
| 1017 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
| 1018 |
+
r"""
|
| 1019 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1020 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1021 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1022 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1023 |
+
"""
|
| 1024 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1025 |
+
|
| 1026 |
+
transformer_outputs = self.model(
|
| 1027 |
+
input_ids,
|
| 1028 |
+
attention_mask=attention_mask,
|
| 1029 |
+
position_ids=position_ids,
|
| 1030 |
+
past_key_values=past_key_values,
|
| 1031 |
+
inputs_embeds=inputs_embeds,
|
| 1032 |
+
use_cache=use_cache,
|
| 1033 |
+
output_attentions=output_attentions,
|
| 1034 |
+
output_hidden_states=output_hidden_states,
|
| 1035 |
+
return_dict=return_dict,
|
| 1036 |
+
)
|
| 1037 |
+
hidden_states = transformer_outputs[0]
|
| 1038 |
+
logits = self.score(hidden_states)
|
| 1039 |
+
|
| 1040 |
+
if input_ids is not None:
|
| 1041 |
+
batch_size = input_ids.shape[0]
|
| 1042 |
+
else:
|
| 1043 |
+
batch_size = inputs_embeds.shape[0]
|
| 1044 |
+
|
| 1045 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
| 1046 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
| 1047 |
+
if self.config.pad_token_id is None:
|
| 1048 |
+
sequence_lengths = -1
|
| 1049 |
+
else:
|
| 1050 |
+
if input_ids is not None:
|
| 1051 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
| 1052 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
| 1053 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
| 1054 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
| 1055 |
+
else:
|
| 1056 |
+
sequence_lengths = -1
|
| 1057 |
+
|
| 1058 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
| 1059 |
+
|
| 1060 |
+
loss = None
|
| 1061 |
+
if labels is not None:
|
| 1062 |
+
loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
|
| 1063 |
+
|
| 1064 |
+
if not return_dict:
|
| 1065 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
| 1066 |
+
return ((loss,) + output) if loss is not None else output
|
| 1067 |
+
|
| 1068 |
+
return SequenceClassifierOutputWithPast(
|
| 1069 |
+
loss=loss,
|
| 1070 |
+
logits=pooled_logits,
|
| 1071 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 1072 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1073 |
+
attentions=transformer_outputs.attentions,
|
| 1074 |
+
)
|
| 1075 |
+
|
| 1076 |
+
|
| 1077 |
+
@add_start_docstrings(
|
| 1078 |
+
"""
|
| 1079 |
+
The Phi3 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
|
| 1080 |
+
output) e.g. for Named-Entity-Recognition (NER) tasks.
|
| 1081 |
+
""",
|
| 1082 |
+
PHI3_START_DOCSTRING,
|
| 1083 |
+
)
|
| 1084 |
+
class Phi3ForTokenClassification(Phi3PreTrainedModel):
|
| 1085 |
+
def __init__(self, config):
|
| 1086 |
+
super().__init__(config)
|
| 1087 |
+
self.num_labels = config.num_labels
|
| 1088 |
+
self.model = Phi3Model(config)
|
| 1089 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
| 1090 |
+
classifier_dropout = config.classifier_dropout
|
| 1091 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
| 1092 |
+
classifier_dropout = config.hidden_dropout
|
| 1093 |
+
else:
|
| 1094 |
+
classifier_dropout = 0.1
|
| 1095 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 1096 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels)
|
| 1097 |
+
|
| 1098 |
+
# Initialize weights and apply final processing
|
| 1099 |
+
self.post_init()
|
| 1100 |
+
|
| 1101 |
+
def get_input_embeddings(self):
|
| 1102 |
+
return self.model.embed_tokens
|
| 1103 |
+
|
| 1104 |
+
def set_input_embeddings(self, value):
|
| 1105 |
+
self.model.embed_tokens = value
|
| 1106 |
+
|
| 1107 |
+
@add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
|
| 1108 |
+
@add_code_sample_docstrings(
|
| 1109 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1110 |
+
output_type=TokenClassifierOutput,
|
| 1111 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1112 |
+
)
|
| 1113 |
+
def forward(
|
| 1114 |
+
self,
|
| 1115 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1116 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1117 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1118 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1119 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1120 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1121 |
+
use_cache: Optional[bool] = None,
|
| 1122 |
+
output_attentions: Optional[bool] = None,
|
| 1123 |
+
output_hidden_states: Optional[bool] = None,
|
| 1124 |
+
return_dict: Optional[bool] = None,
|
| 1125 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
| 1126 |
+
r"""
|
| 1127 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1128 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1129 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1130 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1131 |
+
"""
|
| 1132 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1133 |
+
|
| 1134 |
+
outputs = self.model(
|
| 1135 |
+
input_ids,
|
| 1136 |
+
attention_mask=attention_mask,
|
| 1137 |
+
position_ids=position_ids,
|
| 1138 |
+
past_key_values=past_key_values,
|
| 1139 |
+
inputs_embeds=inputs_embeds,
|
| 1140 |
+
use_cache=use_cache,
|
| 1141 |
+
output_attentions=output_attentions,
|
| 1142 |
+
output_hidden_states=output_hidden_states,
|
| 1143 |
+
return_dict=return_dict,
|
| 1144 |
+
)
|
| 1145 |
+
sequence_output = outputs[0]
|
| 1146 |
+
sequence_output = self.dropout(sequence_output)
|
| 1147 |
+
logits = self.score(sequence_output)
|
| 1148 |
+
|
| 1149 |
+
loss = None
|
| 1150 |
+
if labels is not None:
|
| 1151 |
+
loss = self.loss_function(logits, labels, self.config)
|
| 1152 |
+
|
| 1153 |
+
if not return_dict:
|
| 1154 |
+
output = (logits,) + outputs[2:]
|
| 1155 |
+
return ((loss,) + output) if loss is not None else output
|
| 1156 |
+
|
| 1157 |
+
return TokenClassifierOutput(
|
| 1158 |
+
loss=loss,
|
| 1159 |
+
logits=logits,
|
| 1160 |
+
hidden_states=outputs.hidden_states,
|
| 1161 |
+
attentions=outputs.attentions,
|
| 1162 |
+
)
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
+
__all__ = [
|
| 1166 |
+
"Phi3PreTrainedModel",
|
| 1167 |
+
"Phi3Model",
|
| 1168 |
+
"Phi3ForCausalLM",
|
| 1169 |
+
"Phi3ForSequenceClassification",
|
| 1170 |
+
"Phi3ForTokenClassification",
|
| 1171 |
+
]
|
janus/l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 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
"""PyTorch Phi-3 model."""
|
| 17 |
+
|
| 18 |
+
from typing import Callable, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.utils.checkpoint
|
| 22 |
+
from torch import nn
|
| 23 |
+
|
| 24 |
+
from ...activations import ACT2FN
|
| 25 |
+
from ...cache_utils import Cache
|
| 26 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 27 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
|
| 28 |
+
from ...processing_utils import Unpack
|
| 29 |
+
from ...utils import logging
|
| 30 |
+
from ..mistral.modeling_mistral import (
|
| 31 |
+
MistralDecoderLayer,
|
| 32 |
+
MistralForCausalLM,
|
| 33 |
+
MistralForSequenceClassification,
|
| 34 |
+
MistralForTokenClassification,
|
| 35 |
+
MistralPreTrainedModel,
|
| 36 |
+
MistralRotaryEmbedding,
|
| 37 |
+
apply_rotary_pos_emb,
|
| 38 |
+
eager_attention_forward,
|
| 39 |
+
)
|
| 40 |
+
from .configuration_phi3 import Phi3Config
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
logger = logging.get_logger(__name__)
|
| 44 |
+
|
| 45 |
+
_CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
|
| 46 |
+
_CONFIG_FOR_DOC = "Phi3Config"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class Phi3MLP(nn.Module):
|
| 50 |
+
def __init__(self, config):
|
| 51 |
+
super().__init__()
|
| 52 |
+
|
| 53 |
+
self.config = config
|
| 54 |
+
self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
|
| 55 |
+
self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
|
| 56 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 57 |
+
|
| 58 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
|
| 59 |
+
up_states = self.gate_up_proj(hidden_states)
|
| 60 |
+
|
| 61 |
+
gate, up_states = up_states.chunk(2, dim=-1)
|
| 62 |
+
up_states = up_states * self.activation_fn(gate)
|
| 63 |
+
|
| 64 |
+
return self.down_proj(up_states)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class Phi3Attention(nn.Module):
|
| 68 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 69 |
+
|
| 70 |
+
def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
|
| 71 |
+
super().__init__()
|
| 72 |
+
self.config = config
|
| 73 |
+
self.layer_idx = layer_idx
|
| 74 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 75 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 76 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 77 |
+
self.scaling = self.head_dim**-0.5
|
| 78 |
+
self.attention_dropout = config.attention_dropout
|
| 79 |
+
self.is_causal = True
|
| 80 |
+
|
| 81 |
+
op_size = config.num_attention_heads * self.head_dim + 2 * (config.num_key_value_heads * self.head_dim)
|
| 82 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
| 83 |
+
self.qkv_proj = nn.Linear(config.hidden_size, op_size, bias=False)
|
| 84 |
+
|
| 85 |
+
def forward(
|
| 86 |
+
self,
|
| 87 |
+
hidden_states: torch.Tensor,
|
| 88 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
| 89 |
+
attention_mask: Optional[torch.Tensor],
|
| 90 |
+
past_key_value: Optional[Cache] = None,
|
| 91 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 92 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 93 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 94 |
+
input_shape = hidden_states.shape[:-1]
|
| 95 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 96 |
+
|
| 97 |
+
qkv = self.qkv_proj(hidden_states)
|
| 98 |
+
query_pos = self.config.num_attention_heads * self.head_dim
|
| 99 |
+
query_states = qkv[..., :query_pos]
|
| 100 |
+
key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
|
| 101 |
+
value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
|
| 102 |
+
|
| 103 |
+
query_states = query_states.view(hidden_shape).transpose(1, 2)
|
| 104 |
+
key_states = key_states.view(hidden_shape).transpose(1, 2)
|
| 105 |
+
value_states = value_states.view(hidden_shape).transpose(1, 2)
|
| 106 |
+
|
| 107 |
+
cos, sin = position_embeddings
|
| 108 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 109 |
+
|
| 110 |
+
if past_key_value is not None:
|
| 111 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 112 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 113 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 114 |
+
|
| 115 |
+
attention_interface: Callable = eager_attention_forward
|
| 116 |
+
if self.config._attn_implementation != "eager":
|
| 117 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
| 118 |
+
logger.warning_once(
|
| 119 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
| 120 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 121 |
+
)
|
| 122 |
+
else:
|
| 123 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 124 |
+
|
| 125 |
+
attn_output, attn_weights = attention_interface(
|
| 126 |
+
self,
|
| 127 |
+
query_states,
|
| 128 |
+
key_states,
|
| 129 |
+
value_states,
|
| 130 |
+
attention_mask,
|
| 131 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 132 |
+
scaling=self.scaling,
|
| 133 |
+
sliding_window=getattr(self.config, "sliding_window", None),
|
| 134 |
+
**kwargs,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 138 |
+
attn_output = self.o_proj(attn_output)
|
| 139 |
+
return attn_output, attn_weights
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class Phi3DecoderLayer(MistralDecoderLayer):
|
| 143 |
+
def __init__(self, config: Phi3Config, layer_idx: int):
|
| 144 |
+
super().__init__(config, layer_idx)
|
| 145 |
+
self.config = config
|
| 146 |
+
self.self_attn = Phi3Attention(config=config, layer_idx=layer_idx)
|
| 147 |
+
self.mlp = Phi3MLP(config)
|
| 148 |
+
self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
|
| 149 |
+
self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
|
| 150 |
+
|
| 151 |
+
def forward(
|
| 152 |
+
self,
|
| 153 |
+
hidden_states: torch.Tensor,
|
| 154 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 155 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 156 |
+
past_key_value: Optional[Cache] = None,
|
| 157 |
+
output_attentions: Optional[bool] = False,
|
| 158 |
+
use_cache: Optional[bool] = False,
|
| 159 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 160 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
| 161 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 162 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 163 |
+
"""
|
| 164 |
+
Args:
|
| 165 |
+
hidden_states (`torch.FloatTensor`):
|
| 166 |
+
input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 167 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
| 168 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 169 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 170 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
|
| 171 |
+
`[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
|
| 172 |
+
past_key_value (`Cache`, *optional*): cached past key and value projection states
|
| 173 |
+
output_attentions (`bool`, *optional*):
|
| 174 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 175 |
+
returned tensors for more detail.
|
| 176 |
+
use_cache (`bool`, *optional*):
|
| 177 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 178 |
+
(see `past_key_values`).
|
| 179 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 180 |
+
Indices depicting the position of the input sequence tokens in the sequence
|
| 181 |
+
kwargs (`dict`, *optional*):
|
| 182 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
| 183 |
+
into the model
|
| 184 |
+
"""
|
| 185 |
+
residual = hidden_states
|
| 186 |
+
|
| 187 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 188 |
+
|
| 189 |
+
# Self Attention
|
| 190 |
+
hidden_states, self_attn_weights = self.self_attn(
|
| 191 |
+
hidden_states=hidden_states,
|
| 192 |
+
attention_mask=attention_mask,
|
| 193 |
+
position_ids=position_ids,
|
| 194 |
+
past_key_value=past_key_value,
|
| 195 |
+
output_attentions=output_attentions,
|
| 196 |
+
use_cache=use_cache,
|
| 197 |
+
cache_position=cache_position,
|
| 198 |
+
position_embeddings=position_embeddings,
|
| 199 |
+
**kwargs,
|
| 200 |
+
)
|
| 201 |
+
hidden_states = residual + self.resid_attn_dropout(hidden_states) # main diff with Llama
|
| 202 |
+
|
| 203 |
+
residual = hidden_states
|
| 204 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 205 |
+
hidden_states = self.mlp(hidden_states)
|
| 206 |
+
hidden_states = residual + self.resid_mlp_dropout(hidden_states) # main diff with Llama
|
| 207 |
+
|
| 208 |
+
outputs = (hidden_states,)
|
| 209 |
+
if output_attentions:
|
| 210 |
+
outputs += (self_attn_weights,)
|
| 211 |
+
|
| 212 |
+
return outputs
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class Phi3RotaryEmbedding(MistralRotaryEmbedding):
|
| 216 |
+
def __init__(self, config: Phi3Config, device=None):
|
| 217 |
+
super().__init__(config, device)
|
| 218 |
+
|
| 219 |
+
def _longrope_frequency_update(self, position_ids, device):
|
| 220 |
+
"""Longrope uses long factor if sequence is larger than original pretraining length, short otherwise."""
|
| 221 |
+
seq_len = torch.max(position_ids) + 1
|
| 222 |
+
if hasattr(self.config, "original_max_position_embeddings"):
|
| 223 |
+
original_max_position_embeddings = self.config.original_max_position_embeddings
|
| 224 |
+
else:
|
| 225 |
+
original_max_position_embeddings = self.config.max_position_embeddings
|
| 226 |
+
if seq_len > original_max_position_embeddings:
|
| 227 |
+
if not hasattr(self, "long_inv_freq"):
|
| 228 |
+
self.long_inv_freq, _ = self.rope_init_fn(
|
| 229 |
+
self.config, device, seq_len=original_max_position_embeddings + 1
|
| 230 |
+
)
|
| 231 |
+
self.register_buffer("inv_freq", self.long_inv_freq, persistent=False)
|
| 232 |
+
else:
|
| 233 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
| 234 |
+
|
| 235 |
+
@torch.no_grad()
|
| 236 |
+
def forward(self, x, position_ids):
|
| 237 |
+
if "dynamic" in self.rope_type:
|
| 238 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
| 239 |
+
elif self.rope_type == "longrope":
|
| 240 |
+
self._longrope_frequency_update(position_ids, device=x.device)
|
| 241 |
+
|
| 242 |
+
# Core RoPE block
|
| 243 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
| 244 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 245 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
| 246 |
+
device_type = x.device.type
|
| 247 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
| 248 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
| 249 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 250 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 251 |
+
cos = emb.cos()
|
| 252 |
+
sin = emb.sin()
|
| 253 |
+
|
| 254 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
| 255 |
+
cos = cos * self.attention_scaling
|
| 256 |
+
sin = sin * self.attention_scaling
|
| 257 |
+
|
| 258 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
class Phi3PreTrainedModel(MistralPreTrainedModel):
|
| 262 |
+
_version = "0.0.5"
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
class Phi3ForCausalLM(MistralForCausalLM, Phi3PreTrainedModel):
|
| 266 |
+
def prepare_inputs_for_generation(
|
| 267 |
+
self,
|
| 268 |
+
input_ids,
|
| 269 |
+
past_key_values=None,
|
| 270 |
+
attention_mask=None,
|
| 271 |
+
inputs_embeds=None,
|
| 272 |
+
cache_position=None,
|
| 273 |
+
position_ids=None,
|
| 274 |
+
use_cache=True,
|
| 275 |
+
num_logits_to_keep=None,
|
| 276 |
+
**kwargs,
|
| 277 |
+
):
|
| 278 |
+
# Overwritten -- this model may need to switch between short and long rope, invalidating the cache in the
|
| 279 |
+
# process
|
| 280 |
+
|
| 281 |
+
# When the first time input length reached long and short factor switching point, enforce re-compute cache
|
| 282 |
+
# It will cause downside of slower at this single token position, however, better than current failure.
|
| 283 |
+
if (
|
| 284 |
+
past_key_values
|
| 285 |
+
and self.config.rope_scaling
|
| 286 |
+
and input_ids.shape[1] >= self.config.original_max_position_embeddings + 1
|
| 287 |
+
):
|
| 288 |
+
past_length = cache_position[0]
|
| 289 |
+
if past_length <= self.config.original_max_position_embeddings:
|
| 290 |
+
past_key_values = None
|
| 291 |
+
|
| 292 |
+
model_inputs = Phi3PreTrainedModel().prepare_inputs_for_generation(
|
| 293 |
+
input_ids=input_ids,
|
| 294 |
+
past_key_values=past_key_values,
|
| 295 |
+
attention_mask=attention_mask,
|
| 296 |
+
inputs_embeds=inputs_embeds,
|
| 297 |
+
cache_position=cache_position,
|
| 298 |
+
position_ids=position_ids,
|
| 299 |
+
use_cache=use_cache,
|
| 300 |
+
num_logits_to_keep=num_logits_to_keep,
|
| 301 |
+
**kwargs,
|
| 302 |
+
)
|
| 303 |
+
return model_inputs
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
class Phi3ForSequenceClassification(MistralForSequenceClassification):
|
| 307 |
+
pass
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
class Phi3ForTokenClassification(MistralForTokenClassification):
|
| 311 |
+
pass
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
__all__ = [
|
| 315 |
+
"Phi3PreTrainedModel",
|
| 316 |
+
"Phi3Model", # noqa: F822
|
| 317 |
+
"Phi3ForCausalLM",
|
| 318 |
+
"Phi3ForSequenceClassification",
|
| 319 |
+
"Phi3ForTokenClassification",
|
| 320 |
+
]
|