Add files using upload-large-folder tool
Browse files- .gitattributes +1 -0
- LTA_openwebtext_dualt/mini_owt_fit/cache/owt_t5_len512_from_payload1022_appendeos1.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deepseek_vl/image_processing_pil_deepseek_vl.py +174 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/depth_pro/__init__.py +28 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/depth_pro/configuration_depth_pro.py +181 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/depth_pro/image_processing_depth_pro.py +127 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/depth_pro/modeling_depth_pro.py +1124 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mt5/configuration_mt5.py +95 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/plbart/__init__.py +28 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/plbart/configuration_plbart.py +78 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/plbart/modular_plbart.py +391 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/plbart/tokenization_plbart.py +347 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_t5_stream_pack1023_ultraclean_prose_unk1_top008_run7_rejected.txt +3 -0
- LTA_openwebtext_dualt/runs_transfer/lta_owt_distilbert_len1024_init_lm1b1m_posemb_repeat_fully_c1024_adamw_gbs512_8gpu_20k_20260514_123358/step_0001000.pt +3 -0
- LTA_openwebtext_dualt/runs_transfer/lta_owt_distilbert_len1024_init_lm1b1m_posemb_repeat_fully_c1024_adamw_gbs512_8gpu_20k_20260514_123358/step_0004000.pt +3 -0
- LTA_openwebtext_dualt/runs_transfer/lta_owt_distilbert_len1024_init_lm1b1m_posemb_repeat_fully_c1024_adamw_gbs512_8gpu_20k_20260514_123358/step_0005000.pt +3 -0
- LTA_openwebtext_dualt/runs_transfer/lta_owt_distilbert_len1024_init_lm1b1m_posemb_repeat_fully_c1024_adamw_gbs512_8gpu_20k_20260514_123358/step_0006000.pt +3 -0
- LTA_openwebtext_dualt/runs_transfer/lta_owt_distilbert_len1024_init_lm1b1m_posemb_repeat_fully_c1024_adamw_gbs512_8gpu_20k_20260514_123358/step_0014000.pt +3 -0
- LTA_openwebtext_dualt/runs_transfer/lta_owt_distilbert_len1024_init_lm1b1m_posemb_repeat_fully_c1024_adamw_gbs512_8gpu_20k_20260514_123358/step_0016000.pt +3 -0
- LTA_openwebtext_dualt/runs_transfer/lta_owt_distilbert_len1024_init_lm1b1m_posemb_repeat_fully_c1024_adamw_gbs512_8gpu_20k_20260514_123358/step_0018000.pt +3 -0
- LTA_openwebtext_dualt/runs_transfer/lta_owt_distilbert_len1024_init_lm1b1m_posemb_repeat_fully_c1024_adamw_gbs512_8gpu_20k_20260514_123358/step_0019000.pt +3 -0
.gitattributes
CHANGED
|
@@ -47,3 +47,4 @@ LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/vllm_qwen36_35b_a3b_gpu2_port80
|
|
| 47 |
LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_t5_llmclean_qwen36_35b_articlefull_rev8_pack1023_300k_rejected_docs.txt filter=lfs diff=lfs merge=lfs -text
|
| 48 |
LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_t5_stream_pack1023_ultraclean_probe80k_rowvalid_rejected_docs.txt filter=lfs diff=lfs merge=lfs -text
|
| 49 |
LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_llmclean_qwen36_35b_articlefull_full/accepted.jsonl filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 47 |
LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_t5_llmclean_qwen36_35b_articlefull_rev8_pack1023_300k_rejected_docs.txt filter=lfs diff=lfs merge=lfs -text
|
| 48 |
LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_t5_stream_pack1023_ultraclean_probe80k_rowvalid_rejected_docs.txt filter=lfs diff=lfs merge=lfs -text
|
| 49 |
LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_llmclean_qwen36_35b_articlefull_full/accepted.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 50 |
+
LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_t5_stream_pack1023_ultraclean_prose_unk1_top008_run7_rejected.txt filter=lfs diff=lfs merge=lfs -text
|
LTA_openwebtext_dualt/mini_owt_fit/cache/owt_t5_len512_from_payload1022_appendeos1.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f06d5fafc077a27b3bfa2a962053cf279a6c6c1daca7057f7e294b9d9ce489e2
|
| 3 |
+
size 5858381626
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deepseek_vl/image_processing_pil_deepseek_vl.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/deepseek_vl/modular_deepseek_vl.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_deepseek_vl.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2025 Deepseek AI and The HuggingFace Team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
from ...image_processing_backends import PilBackend
|
| 25 |
+
from ...image_processing_utils import BatchFeature
|
| 26 |
+
from ...image_transforms import resize as np_resize
|
| 27 |
+
from ...image_utils import (
|
| 28 |
+
OPENAI_CLIP_MEAN,
|
| 29 |
+
OPENAI_CLIP_STD,
|
| 30 |
+
ChannelDimension,
|
| 31 |
+
ImageInput,
|
| 32 |
+
PILImageResampling,
|
| 33 |
+
SizeDict,
|
| 34 |
+
)
|
| 35 |
+
from ...processing_utils import ImagesKwargs, Unpack
|
| 36 |
+
from ...utils import TensorType, auto_docstring
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class DeepseekVLImageProcessorKwargs(ImagesKwargs, total=False):
|
| 40 |
+
r"""
|
| 41 |
+
min_size (`int`, *optional*, defaults to 14):
|
| 42 |
+
The minimum allowed size for the resized image. Ensures that neither the height nor width
|
| 43 |
+
falls below this value after resizing.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
min_size: int
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@auto_docstring
|
| 50 |
+
class DeepseekVLImageProcessorPil(PilBackend):
|
| 51 |
+
resample = PILImageResampling.BICUBIC
|
| 52 |
+
image_mean = OPENAI_CLIP_MEAN
|
| 53 |
+
image_std = OPENAI_CLIP_STD
|
| 54 |
+
size = {"height": 384, "width": 384}
|
| 55 |
+
min_size = 14
|
| 56 |
+
do_resize = True
|
| 57 |
+
do_rescale = True
|
| 58 |
+
do_normalize = True
|
| 59 |
+
do_pad = True
|
| 60 |
+
valid_kwargs = DeepseekVLImageProcessorKwargs
|
| 61 |
+
|
| 62 |
+
def __init__(self, **kwargs: Unpack[DeepseekVLImageProcessorKwargs]):
|
| 63 |
+
super().__init__(**kwargs)
|
| 64 |
+
image_mean = getattr(self, "image_mean", None)
|
| 65 |
+
if image_mean is None:
|
| 66 |
+
background_color = (127, 127, 127)
|
| 67 |
+
else:
|
| 68 |
+
background_color = tuple(int(x * 255) for x in image_mean)
|
| 69 |
+
self.background_color = tuple(background_color)
|
| 70 |
+
|
| 71 |
+
@auto_docstring
|
| 72 |
+
def preprocess(self, images: ImageInput, **kwargs: Unpack[DeepseekVLImageProcessorKwargs]) -> BatchFeature:
|
| 73 |
+
return super().preprocess(images, **kwargs)
|
| 74 |
+
|
| 75 |
+
def resize(
|
| 76 |
+
self,
|
| 77 |
+
image: np.ndarray,
|
| 78 |
+
size: SizeDict,
|
| 79 |
+
min_size: int,
|
| 80 |
+
resample: PILImageResampling | None = None,
|
| 81 |
+
**kwargs,
|
| 82 |
+
) -> np.ndarray:
|
| 83 |
+
"""Resize so largest side becomes size, with min_size floor."""
|
| 84 |
+
if size.height is None or size.width is None or size.height != size.width:
|
| 85 |
+
raise ValueError(
|
| 86 |
+
f"Output height and width must be the same. Got height={size.height} and width={size.width}"
|
| 87 |
+
)
|
| 88 |
+
target_size = size.height
|
| 89 |
+
|
| 90 |
+
height, width = image.shape[-2:]
|
| 91 |
+
max_size = max(height, width)
|
| 92 |
+
|
| 93 |
+
delta = target_size / max_size
|
| 94 |
+
new_height = max(round(height * delta), min_size)
|
| 95 |
+
new_width = max(round(width * delta), min_size)
|
| 96 |
+
|
| 97 |
+
return np_resize(
|
| 98 |
+
image,
|
| 99 |
+
size=(new_height, new_width),
|
| 100 |
+
resample=resample or self.resample,
|
| 101 |
+
data_format=ChannelDimension.FIRST,
|
| 102 |
+
input_data_format=ChannelDimension.FIRST,
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
def pad_to_square(
|
| 106 |
+
self,
|
| 107 |
+
image: np.ndarray,
|
| 108 |
+
background_color: int | tuple[int, int, int] = 0,
|
| 109 |
+
) -> np.ndarray:
|
| 110 |
+
"""Pad an image to a square based on the longest edge."""
|
| 111 |
+
height, width = image.shape[-2:]
|
| 112 |
+
num_channels = image.shape[0]
|
| 113 |
+
|
| 114 |
+
if height == width:
|
| 115 |
+
return image
|
| 116 |
+
|
| 117 |
+
max_dim = max(height, width)
|
| 118 |
+
|
| 119 |
+
if isinstance(background_color, int):
|
| 120 |
+
background_color = [background_color]
|
| 121 |
+
elif len(background_color) != num_channels:
|
| 122 |
+
raise ValueError(
|
| 123 |
+
f"background_color must have no more than {num_channels} elements to match the number of channels"
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
padded_image = np.zeros((num_channels, max_dim, max_dim), dtype=image.dtype)
|
| 127 |
+
for i, color in enumerate(background_color):
|
| 128 |
+
padded_image[i, :, :] = color
|
| 129 |
+
|
| 130 |
+
if width > height:
|
| 131 |
+
start = (max_dim - height) // 2
|
| 132 |
+
padded_image[:, start : start + height, :] = image
|
| 133 |
+
else:
|
| 134 |
+
start = (max_dim - width) // 2
|
| 135 |
+
padded_image[:, :, start : start + width] = image
|
| 136 |
+
|
| 137 |
+
return padded_image
|
| 138 |
+
|
| 139 |
+
def _preprocess(
|
| 140 |
+
self,
|
| 141 |
+
images: list[np.ndarray],
|
| 142 |
+
do_resize: bool,
|
| 143 |
+
size: SizeDict,
|
| 144 |
+
resample: PILImageResampling | None,
|
| 145 |
+
do_rescale: bool,
|
| 146 |
+
rescale_factor: float,
|
| 147 |
+
do_normalize: bool,
|
| 148 |
+
image_mean: float | list[float] | None,
|
| 149 |
+
image_std: float | list[float] | None,
|
| 150 |
+
min_size: int,
|
| 151 |
+
return_tensors: str | TensorType | None,
|
| 152 |
+
do_pad: bool = True,
|
| 153 |
+
**kwargs,
|
| 154 |
+
) -> BatchFeature:
|
| 155 |
+
processed_images = []
|
| 156 |
+
for image in images:
|
| 157 |
+
if do_resize:
|
| 158 |
+
image = self.resize(image=image, size=size, min_size=min_size, resample=resample)
|
| 159 |
+
if do_pad:
|
| 160 |
+
image = self.pad_to_square(image, background_color=self.background_color)
|
| 161 |
+
if do_rescale:
|
| 162 |
+
image = self.rescale(image, rescale_factor)
|
| 163 |
+
if do_normalize:
|
| 164 |
+
image = self.normalize(image, image_mean, image_std)
|
| 165 |
+
processed_images.append(image)
|
| 166 |
+
|
| 167 |
+
return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
|
| 168 |
+
|
| 169 |
+
def postprocess(self):
|
| 170 |
+
"""Applies post-processing to the decoded image tokens by reversing transformations applied during preprocessing."""
|
| 171 |
+
raise AttributeError("Not needed for DeepseekVL")
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
__all__ = ["DeepseekVLImageProcessorPil"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/depth_pro/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_depth_pro import *
|
| 22 |
+
from .image_processing_depth_pro import *
|
| 23 |
+
from .modeling_depth_pro import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/depth_pro/configuration_depth_pro.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
"""DepthPro model configuration"""
|
| 15 |
+
|
| 16 |
+
from copy import deepcopy
|
| 17 |
+
|
| 18 |
+
from huggingface_hub.dataclasses import strict
|
| 19 |
+
|
| 20 |
+
from ...configuration_utils import PreTrainedConfig
|
| 21 |
+
from ...utils import auto_docstring, logging
|
| 22 |
+
from ..auto.configuration_auto import CONFIG_MAPPING, AutoConfig
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@auto_docstring(checkpoint="apple/DepthPro")
|
| 29 |
+
@strict
|
| 30 |
+
class DepthProConfig(PreTrainedConfig):
|
| 31 |
+
r"""
|
| 32 |
+
fusion_hidden_size (`int`, *optional*, defaults to 256):
|
| 33 |
+
The number of channels before fusion.
|
| 34 |
+
intermediate_hook_ids (`list[int]`, *optional*, defaults to `[11, 5]`):
|
| 35 |
+
Indices of the intermediate hidden states from the patch encoder to use for fusion.
|
| 36 |
+
intermediate_feature_dims (`list[int]`, *optional*, defaults to `[256, 256]`):
|
| 37 |
+
Hidden state dimensions during upsampling for each intermediate hidden state in `intermediate_hook_ids`.
|
| 38 |
+
scaled_images_ratios (`list[float]`, *optional*, defaults to `[0.25, 0.5, 1]`):
|
| 39 |
+
Ratios of scaled images to be used by the patch encoder.
|
| 40 |
+
scaled_images_overlap_ratios (`list[float]`, *optional*, defaults to `[0.0, 0.5, 0.25]`):
|
| 41 |
+
Overlap ratios between patches for each scaled image in `scaled_images_ratios`.
|
| 42 |
+
scaled_images_feature_dims (`list[int]`, *optional*, defaults to `[1024, 1024, 512]`):
|
| 43 |
+
Hidden state dimensions during upsampling for each scaled image in `scaled_images_ratios`.
|
| 44 |
+
merge_padding_value (`int`, *optional*, defaults to 3):
|
| 45 |
+
When merging smaller patches back to the image size, overlapping sections of this size are removed.
|
| 46 |
+
use_batch_norm_in_fusion_residual (`bool`, *optional*, defaults to `False`):
|
| 47 |
+
Whether to use batch normalization in the pre-activate residual units of the fusion blocks.
|
| 48 |
+
use_bias_in_fusion_residual (`bool`, *optional*, defaults to `True`):
|
| 49 |
+
Whether to use bias in the pre-activate residual units of the fusion blocks.
|
| 50 |
+
use_fov_model (`bool`, *optional*, defaults to `False`):
|
| 51 |
+
Whether to use `DepthProFovModel` to generate the field of view.
|
| 52 |
+
num_fov_head_layers (`int`, *optional*, defaults to 2):
|
| 53 |
+
Number of convolution layers in the head of `DepthProFovModel`.
|
| 54 |
+
image_model_config (`Union[dict[str, Any], PreTrainedConfig]`, *optional*):
|
| 55 |
+
The configuration of the image encoder model, which is loaded using the [`AutoModel`] API.
|
| 56 |
+
By default, Dinov2 model is used as backbone.
|
| 57 |
+
patch_model_config (`Union[dict[str, Any], PreTrainedConfig]`, *optional*):
|
| 58 |
+
The configuration of the patch encoder model, which is loaded using the [`AutoModel`] API.
|
| 59 |
+
By default, Dinov2 model is used as backbone.
|
| 60 |
+
fov_model_config (`Union[dict[str, Any], PreTrainedConfig]`, *optional*):
|
| 61 |
+
The configuration of the fov encoder model, which is loaded using the [`AutoModel`] API.
|
| 62 |
+
By default, Dinov2 model is used as backbone.
|
| 63 |
+
|
| 64 |
+
Example:
|
| 65 |
+
|
| 66 |
+
```python
|
| 67 |
+
>>> from transformers import DepthProConfig, DepthProModel
|
| 68 |
+
|
| 69 |
+
>>> # Initializing a DepthPro apple/DepthPro style configuration
|
| 70 |
+
>>> configuration = DepthProConfig()
|
| 71 |
+
|
| 72 |
+
>>> # Initializing a model (with random weights) from the apple/DepthPro style configuration
|
| 73 |
+
>>> model = DepthProModel(configuration)
|
| 74 |
+
|
| 75 |
+
>>> # Accessing the model configuration
|
| 76 |
+
>>> configuration = model.config
|
| 77 |
+
```"""
|
| 78 |
+
|
| 79 |
+
model_type = "depth_pro"
|
| 80 |
+
sub_configs = {"image_model_config": AutoConfig, "patch_model_config": AutoConfig, "fov_model_config": AutoConfig}
|
| 81 |
+
|
| 82 |
+
fusion_hidden_size: int = 256
|
| 83 |
+
patch_size: int | list[int] | tuple[int, int] = 384
|
| 84 |
+
initializer_range: float = 0.02
|
| 85 |
+
intermediate_hook_ids: list[int] | tuple[int, ...] = (11, 5)
|
| 86 |
+
intermediate_feature_dims: list[int] | tuple[int, ...] = (256, 256)
|
| 87 |
+
scaled_images_ratios: list[int | float] | tuple[int | float, ...] = (0.25, 0.5, 1)
|
| 88 |
+
scaled_images_overlap_ratios: list[float] | tuple[float, ...] = (0.0, 0.5, 0.25)
|
| 89 |
+
scaled_images_feature_dims: list[int] | tuple[int, ...] = (1024, 1024, 512)
|
| 90 |
+
merge_padding_value: int = 3
|
| 91 |
+
use_batch_norm_in_fusion_residual: bool = False
|
| 92 |
+
use_bias_in_fusion_residual: bool = True
|
| 93 |
+
use_fov_model: bool = False
|
| 94 |
+
num_fov_head_layers: int = 2
|
| 95 |
+
image_model_config: dict | PreTrainedConfig | None = None
|
| 96 |
+
patch_model_config: dict | PreTrainedConfig | None = None
|
| 97 |
+
fov_model_config: dict | PreTrainedConfig | None = None
|
| 98 |
+
|
| 99 |
+
def __post_init__(self, **kwargs):
|
| 100 |
+
for sub_config_key in self.sub_configs:
|
| 101 |
+
sub_config = getattr(self, sub_config_key)
|
| 102 |
+
|
| 103 |
+
if sub_config is None:
|
| 104 |
+
sub_config = CONFIG_MAPPING["dinov2"](image_size=self.patch_size)
|
| 105 |
+
logger.info(
|
| 106 |
+
f"`{sub_config_key}` is `None`. Initializing `{sub_config_key}` with the `Dinov2Config` "
|
| 107 |
+
f"with default values except `{sub_config_key}.image_size` is set to `config.patch_size`."
|
| 108 |
+
)
|
| 109 |
+
elif isinstance(sub_config, dict):
|
| 110 |
+
sub_config = deepcopy(sub_config)
|
| 111 |
+
if "model_type" not in sub_config:
|
| 112 |
+
raise KeyError(
|
| 113 |
+
f"The `model_type` key is missing in the `{sub_config_key}` dictionary. Please provide the model type."
|
| 114 |
+
)
|
| 115 |
+
elif sub_config["model_type"] not in CONFIG_MAPPING:
|
| 116 |
+
raise ValueError(
|
| 117 |
+
f"The model type `{sub_config['model_type']}` in `{sub_config_key}` is not supported. Please provide a valid model type."
|
| 118 |
+
)
|
| 119 |
+
image_size = sub_config.get("image_size")
|
| 120 |
+
if image_size != self.patch_size:
|
| 121 |
+
logger.info(
|
| 122 |
+
f"The `image_size` in `{sub_config_key}` is set to `{image_size}`, "
|
| 123 |
+
f"but it does not match the required `patch_size` of `{self.patch_size}`. "
|
| 124 |
+
f"Updating `image_size` to `{self.patch_size}` for consistency. "
|
| 125 |
+
f"Ensure that `image_size` aligns with `patch_size` in the configuration."
|
| 126 |
+
)
|
| 127 |
+
sub_config.update({"image_size": self.patch_size})
|
| 128 |
+
sub_config = CONFIG_MAPPING[sub_config["model_type"]](**sub_config)
|
| 129 |
+
elif isinstance(sub_config, PreTrainedConfig):
|
| 130 |
+
image_size = getattr(sub_config, "image_size", None)
|
| 131 |
+
if image_size != self.patch_size:
|
| 132 |
+
raise ValueError(
|
| 133 |
+
f"`config.{sub_config_key}.image_size={image_size}` should match `config.patch_size={self.patch_size}`."
|
| 134 |
+
)
|
| 135 |
+
else:
|
| 136 |
+
raise TypeError(
|
| 137 |
+
f"Invalid type for `sub_config`. Expected `PreTrainedConfig`, `dict`, or `None`, but got {type(sub_config)}."
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
setattr(self, sub_config_key, sub_config)
|
| 141 |
+
|
| 142 |
+
super().__post_init__(**kwargs)
|
| 143 |
+
|
| 144 |
+
def validate_architecture(self):
|
| 145 |
+
"""Part of `@strict`-powered validation. Validates the architecture of the config."""
|
| 146 |
+
# scaled_images_ratios is sorted
|
| 147 |
+
if list(self.scaled_images_ratios) != sorted(self.scaled_images_ratios):
|
| 148 |
+
raise ValueError(
|
| 149 |
+
f"Values in scaled_images_ratios={self.scaled_images_ratios} should be sorted from low to high"
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
# scaled_images_ratios, scaled_images_overlap_ratios, scaled_images_feature_dims should be consistent
|
| 153 |
+
if not (
|
| 154 |
+
len(self.scaled_images_ratios)
|
| 155 |
+
== len(self.scaled_images_overlap_ratios)
|
| 156 |
+
== len(self.scaled_images_feature_dims)
|
| 157 |
+
):
|
| 158 |
+
raise ValueError(
|
| 159 |
+
f"len(scaled_images_ratios)={len(self.scaled_images_ratios)} and "
|
| 160 |
+
f"len(scaled_images_overlap_ratios)={len(self.scaled_images_overlap_ratios)} and "
|
| 161 |
+
f"len(scaled_images_feature_dims)={len(self.scaled_images_feature_dims)}, "
|
| 162 |
+
f"should match in config."
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
# intermediate_hook_ids, intermediate_feature_dims should be consistent
|
| 166 |
+
if not (len(self.intermediate_hook_ids) == len(self.intermediate_feature_dims)):
|
| 167 |
+
raise ValueError(
|
| 168 |
+
f"len(intermediate_hook_ids)={len(self.intermediate_hook_ids)} and "
|
| 169 |
+
f"len(intermediate_feature_dims)={len(self.intermediate_feature_dims)}, "
|
| 170 |
+
f"should match in config."
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
# fusion_hidden_size should be consistent with num_fov_head_layers
|
| 174 |
+
if self.fusion_hidden_size // 2**self.num_fov_head_layers == 0:
|
| 175 |
+
raise ValueError(
|
| 176 |
+
f"fusion_hidden_size={self.fusion_hidden_size} should be consistent with num_fov_head_layers={self.num_fov_head_layers} "
|
| 177 |
+
"i.e fusion_hidden_size // 2**num_fov_head_layers > 0"
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
__all__ = ["DepthProConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/depth_pro/image_processing_depth_pro.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Image processor class for DepthPro."""
|
| 15 |
+
|
| 16 |
+
from typing import TYPE_CHECKING
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from torchvision.transforms.v2 import functional as tvF
|
| 20 |
+
|
| 21 |
+
from ...image_processing_backends import TorchvisionBackend
|
| 22 |
+
from ...image_processing_utils import BatchFeature
|
| 23 |
+
from ...image_transforms import group_images_by_shape, reorder_images
|
| 24 |
+
from ...image_utils import (
|
| 25 |
+
IMAGENET_STANDARD_MEAN,
|
| 26 |
+
IMAGENET_STANDARD_STD,
|
| 27 |
+
PILImageResampling,
|
| 28 |
+
SizeDict,
|
| 29 |
+
pil_torch_interpolation_mapping,
|
| 30 |
+
)
|
| 31 |
+
from ...utils import (
|
| 32 |
+
TensorType,
|
| 33 |
+
auto_docstring,
|
| 34 |
+
logging,
|
| 35 |
+
requires_backends,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if TYPE_CHECKING:
|
| 40 |
+
from .modeling_depth_pro import DepthProDepthEstimatorOutput
|
| 41 |
+
|
| 42 |
+
logger = logging.get_logger(__name__)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@auto_docstring(custom_intro="Constructs a DepthPro image processor.")
|
| 46 |
+
class DepthProImageProcessor(TorchvisionBackend):
|
| 47 |
+
resample = PILImageResampling.BILINEAR
|
| 48 |
+
image_mean = IMAGENET_STANDARD_MEAN
|
| 49 |
+
image_std = IMAGENET_STANDARD_STD
|
| 50 |
+
size = {"height": 1536, "width": 1536}
|
| 51 |
+
do_resize = True
|
| 52 |
+
do_rescale = True
|
| 53 |
+
do_normalize = True
|
| 54 |
+
|
| 55 |
+
def _preprocess(
|
| 56 |
+
self,
|
| 57 |
+
images: list["torch.Tensor"],
|
| 58 |
+
do_resize: bool,
|
| 59 |
+
size: SizeDict,
|
| 60 |
+
resample: "PILImageResampling | tvF.InterpolationMode | int | None",
|
| 61 |
+
do_rescale: bool,
|
| 62 |
+
rescale_factor: float,
|
| 63 |
+
do_normalize: bool,
|
| 64 |
+
image_mean: float | list[float] | None,
|
| 65 |
+
image_std: float | list[float] | None,
|
| 66 |
+
disable_grouping: bool | None,
|
| 67 |
+
return_tensors: str | TensorType | None,
|
| 68 |
+
**kwargs,
|
| 69 |
+
) -> BatchFeature:
|
| 70 |
+
"""Custom preprocessing for DepthPro: rescale+normalize FIRST, then resize."""
|
| 71 |
+
grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
|
| 72 |
+
processed_images_grouped = {}
|
| 73 |
+
for shape, stacked_images in grouped_images.items():
|
| 74 |
+
# Rescale and normalize FIRST
|
| 75 |
+
stacked_images = self.rescale_and_normalize(
|
| 76 |
+
stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
|
| 77 |
+
)
|
| 78 |
+
# Then resize (using torch interpolation to handle negative values)
|
| 79 |
+
if do_resize:
|
| 80 |
+
stacked_images = self.resize(stacked_images, size, resample, antialias=False)
|
| 81 |
+
processed_images_grouped[shape] = stacked_images
|
| 82 |
+
processed_images = reorder_images(processed_images_grouped, grouped_images_index)
|
| 83 |
+
return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
|
| 84 |
+
|
| 85 |
+
def post_process_depth_estimation(
|
| 86 |
+
self,
|
| 87 |
+
outputs: "DepthProDepthEstimatorOutput",
|
| 88 |
+
target_sizes: TensorType | list[tuple[int, int]] | None = None,
|
| 89 |
+
) -> list[dict[str, TensorType]]:
|
| 90 |
+
"""Post-processes the raw depth predictions from the model."""
|
| 91 |
+
requires_backends(self, "torch")
|
| 92 |
+
predicted_depth = outputs.predicted_depth
|
| 93 |
+
fov = outputs.field_of_view
|
| 94 |
+
batch_size = len(predicted_depth)
|
| 95 |
+
if target_sizes is not None and batch_size != len(target_sizes):
|
| 96 |
+
raise ValueError(
|
| 97 |
+
"Make sure that you pass in as many fov values as the batch dimension of the predicted depth"
|
| 98 |
+
)
|
| 99 |
+
results = []
|
| 100 |
+
fov = [None] * batch_size if fov is None else fov
|
| 101 |
+
target_sizes = [None] * batch_size if target_sizes is None else target_sizes
|
| 102 |
+
for depth, fov_value, target_size in zip(predicted_depth, fov, target_sizes):
|
| 103 |
+
focal_length = None
|
| 104 |
+
if target_size is not None:
|
| 105 |
+
# scale image w.r.t fov
|
| 106 |
+
if fov_value is not None:
|
| 107 |
+
width = target_size[1]
|
| 108 |
+
focal_length = 0.5 * width / torch.tan(0.5 * torch.deg2rad(fov_value))
|
| 109 |
+
depth = depth * width / focal_length
|
| 110 |
+
depth = torch.nn.functional.interpolate(
|
| 111 |
+
# input should be (B, C, H, W)
|
| 112 |
+
input=depth.unsqueeze(0).unsqueeze(1),
|
| 113 |
+
size=target_size,
|
| 114 |
+
mode=pil_torch_interpolation_mapping[self.resample].value,
|
| 115 |
+
).squeeze()
|
| 116 |
+
depth = 1.0 / torch.clamp(depth, min=1e-4, max=1e4)
|
| 117 |
+
results.append(
|
| 118 |
+
{
|
| 119 |
+
"predicted_depth": depth,
|
| 120 |
+
"field_of_view": fov_value,
|
| 121 |
+
"focal_length": focal_length,
|
| 122 |
+
}
|
| 123 |
+
)
|
| 124 |
+
return results
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
__all__ = ["DepthProImageProcessor"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/depth_pro/modeling_depth_pro.py
ADDED
|
@@ -0,0 +1,1124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The Apple Research Team Authors and 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 |
+
"""PyTorch DepthPro model."""
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn.functional as F
|
| 21 |
+
from torch import nn
|
| 22 |
+
|
| 23 |
+
from ... import initialization as init
|
| 24 |
+
from ...modeling_utils import PreTrainedModel
|
| 25 |
+
from ...utils import ModelOutput, auto_docstring, logging, torch_int
|
| 26 |
+
from ..auto import AutoModel
|
| 27 |
+
from .configuration_depth_pro import DepthProConfig
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@auto_docstring(
|
| 34 |
+
custom_intro="""
|
| 35 |
+
Base class for DepthPro's outputs.
|
| 36 |
+
"""
|
| 37 |
+
)
|
| 38 |
+
@dataclass
|
| 39 |
+
class DepthProOutput(ModelOutput):
|
| 40 |
+
r"""
|
| 41 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, n_patches_per_batch, sequence_length, hidden_size)`):
|
| 42 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 43 |
+
features (`Union[torch.FloatTensor, List[torch.FloatTensor]]`, *optional*):
|
| 44 |
+
Features from encoders. Can be a single feature or a list of features.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
last_hidden_state: torch.FloatTensor | None = None
|
| 48 |
+
features: torch.FloatTensor | list[torch.FloatTensor] = None
|
| 49 |
+
hidden_states: tuple[torch.FloatTensor, ...] | None = None
|
| 50 |
+
attentions: tuple[torch.FloatTensor, ...] | None = None
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@auto_docstring(
|
| 54 |
+
custom_intro="""
|
| 55 |
+
Base class for DepthProForDepthEstimation's output.
|
| 56 |
+
"""
|
| 57 |
+
)
|
| 58 |
+
@dataclass
|
| 59 |
+
class DepthProDepthEstimatorOutput(ModelOutput):
|
| 60 |
+
r"""
|
| 61 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 62 |
+
Classification (or regression if config.num_labels==1) loss.
|
| 63 |
+
field_of_view (`torch.FloatTensor` of shape `(batch_size,)`, *optional*, returned when `use_fov_model` is provided):
|
| 64 |
+
Field of View Scaler.
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
loss: torch.FloatTensor | None = None
|
| 68 |
+
predicted_depth: torch.FloatTensor | None = None
|
| 69 |
+
field_of_view: torch.FloatTensor | None = None
|
| 70 |
+
hidden_states: tuple[torch.FloatTensor, ...] | None = None
|
| 71 |
+
attentions: tuple[torch.FloatTensor, ...] | None = None
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def split_to_patches(pixel_values: torch.Tensor, patch_size: int, overlap_ratio: float) -> torch.Tensor:
|
| 75 |
+
"""Creates Patches from Batch."""
|
| 76 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 77 |
+
|
| 78 |
+
if height == width == patch_size:
|
| 79 |
+
# create patches only if scaled image is not already equal to patch size
|
| 80 |
+
return pixel_values
|
| 81 |
+
|
| 82 |
+
stride = torch_int(patch_size * (1 - overlap_ratio))
|
| 83 |
+
|
| 84 |
+
patches = F.unfold(pixel_values, kernel_size=(patch_size, patch_size), stride=(stride, stride))
|
| 85 |
+
patches = patches.permute(2, 0, 1)
|
| 86 |
+
patches = patches.reshape(-1, num_channels, patch_size, patch_size)
|
| 87 |
+
|
| 88 |
+
return patches
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def reshape_features(hidden_states: torch.Tensor) -> torch.Tensor:
|
| 92 |
+
"""Discard class token and reshape 1D feature map to a 2D grid."""
|
| 93 |
+
n_samples, seq_len, hidden_size = hidden_states.shape
|
| 94 |
+
size = torch_int(seq_len**0.5)
|
| 95 |
+
|
| 96 |
+
hidden_states = hidden_states[:, -(size**2) :, :] # remove special tokens if there are any
|
| 97 |
+
hidden_states = hidden_states.reshape(n_samples, size, size, hidden_size)
|
| 98 |
+
hidden_states = hidden_states.permute(0, 3, 1, 2)
|
| 99 |
+
|
| 100 |
+
return hidden_states
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def merge_patches(patches: torch.Tensor, batch_size: int, padding: int) -> torch.Tensor:
|
| 104 |
+
"""Merges smaller patches into image-like feature map."""
|
| 105 |
+
n_patches, hidden_size, out_size, out_size = patches.shape
|
| 106 |
+
n_patches_per_batch = n_patches // batch_size
|
| 107 |
+
sqrt_n_patches_per_batch = torch_int(n_patches_per_batch**0.5)
|
| 108 |
+
new_out_size = sqrt_n_patches_per_batch * out_size
|
| 109 |
+
|
| 110 |
+
if n_patches == batch_size:
|
| 111 |
+
# merge only if the patches were created from scaled image
|
| 112 |
+
# patches are not created when scaled image size is equal to patch size
|
| 113 |
+
return patches
|
| 114 |
+
|
| 115 |
+
if n_patches_per_batch < 4:
|
| 116 |
+
# for each batch, at least 4 small patches are required to
|
| 117 |
+
# recreate a large square patch from merging them and later padding is applied
|
| 118 |
+
# 3 x (8x8) patches becomes 1 x ( 8x8 ) patch (extra patch ignored, no padding)
|
| 119 |
+
# 4 x (8x8) patches becomes 1 x (16x16) patch (padding later)
|
| 120 |
+
# 5 x (8x8) patches becomes 1 x (16x16) patch (extra patch ignored, padding later)
|
| 121 |
+
# 9 x (8x8) patches becomes 1 x (24x24) patch (padding later)
|
| 122 |
+
# thus the following code only rearranges the patches and removes extra ones
|
| 123 |
+
padding = 0
|
| 124 |
+
|
| 125 |
+
# make sure padding is not large enough to remove more than half of the patch
|
| 126 |
+
padding = min(out_size // 4, padding)
|
| 127 |
+
|
| 128 |
+
if padding == 0:
|
| 129 |
+
# faster when no padding is required
|
| 130 |
+
merged = patches.reshape(n_patches_per_batch, batch_size, hidden_size, out_size, out_size)
|
| 131 |
+
merged = merged.permute(1, 2, 0, 3, 4)
|
| 132 |
+
merged = merged[:, :, : sqrt_n_patches_per_batch**2, :, :]
|
| 133 |
+
merged = merged.reshape(
|
| 134 |
+
batch_size, hidden_size, sqrt_n_patches_per_batch, sqrt_n_patches_per_batch, out_size, out_size
|
| 135 |
+
)
|
| 136 |
+
merged = merged.permute(0, 1, 2, 4, 3, 5)
|
| 137 |
+
merged = merged.reshape(batch_size, hidden_size, new_out_size, new_out_size)
|
| 138 |
+
else:
|
| 139 |
+
# padding example:
|
| 140 |
+
# let out_size = 8, new_out_size = 32, padding = 2
|
| 141 |
+
# each patch is separated by "|"
|
| 142 |
+
# and padding is applied to the merging edges of each patch
|
| 143 |
+
# 00 01 02 03 04 05 06 07 | 08 09 10 11 12 13 14 15 | 16 17 18 19 20 21 22 23 | 24 25 26 27 28 29 30 31
|
| 144 |
+
# 00 01 02 03 04 05 -- -- | -- -- 10 11 12 13 -- -- | -- -- 18 19 20 21 -- -- | -- -- 26 27 28 29 30 31
|
| 145 |
+
i = 0
|
| 146 |
+
boxes = []
|
| 147 |
+
for h in range(sqrt_n_patches_per_batch):
|
| 148 |
+
boxes_in_row = []
|
| 149 |
+
for w in range(sqrt_n_patches_per_batch):
|
| 150 |
+
box = patches[batch_size * i : batch_size * (i + 1)]
|
| 151 |
+
|
| 152 |
+
# collect paddings
|
| 153 |
+
paddings = [0, 0, 0, 0]
|
| 154 |
+
if h != 0:
|
| 155 |
+
# remove pad from height if box is not at top border
|
| 156 |
+
paddings[0] = padding
|
| 157 |
+
if w != 0:
|
| 158 |
+
# remove pad from width if box is not at left border
|
| 159 |
+
paddings[2] = padding
|
| 160 |
+
if h != sqrt_n_patches_per_batch - 1:
|
| 161 |
+
# remove pad from height if box is not at bottom border
|
| 162 |
+
paddings[1] = padding
|
| 163 |
+
if w != sqrt_n_patches_per_batch - 1:
|
| 164 |
+
# remove pad from width if box is not at right border
|
| 165 |
+
paddings[3] = padding
|
| 166 |
+
|
| 167 |
+
# remove paddings
|
| 168 |
+
_, _, box_h, box_w = box.shape
|
| 169 |
+
pad_top, pad_bottom, pad_left, pad_right = paddings
|
| 170 |
+
box = box[:, :, pad_top : box_h - pad_bottom, pad_left : box_w - pad_right]
|
| 171 |
+
|
| 172 |
+
boxes_in_row.append(box)
|
| 173 |
+
i += 1
|
| 174 |
+
boxes_in_row = torch.cat(boxes_in_row, dim=-1)
|
| 175 |
+
boxes.append(boxes_in_row)
|
| 176 |
+
merged = torch.cat(boxes, dim=-2)
|
| 177 |
+
|
| 178 |
+
return merged
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def reconstruct_feature_maps(
|
| 182 |
+
hidden_state: torch.Tensor, batch_size: int, padding: int, output_size: tuple[float, float]
|
| 183 |
+
) -> torch.Tensor:
|
| 184 |
+
"""
|
| 185 |
+
Reconstructs feature maps from the hidden state produced by any of the encoder. Converts the hidden state of shape
|
| 186 |
+
`(n_patches_per_batch * batch_size, seq_len, hidden_size)` to feature maps of shape
|
| 187 |
+
`(batch_size, hidden_size, output_size[0], output_size[1])`.
|
| 188 |
+
|
| 189 |
+
Args:
|
| 190 |
+
hidden_state (torch.Tensor): Input tensor of shape `(n_patches_per_batch * batch_size, seq_len, hidden_size)`
|
| 191 |
+
representing the encoded patches.
|
| 192 |
+
batch_size (int): The number of samples in a batch.
|
| 193 |
+
padding (int): The amount of padding to be removed when merging patches.
|
| 194 |
+
output_size (tuple[float, float]): The desired output size for the feature maps, specified as `(height, width)`.
|
| 195 |
+
|
| 196 |
+
Returns:
|
| 197 |
+
torch.Tensor: Reconstructed feature maps of shape `(batch_size, hidden_size, output_size[0], output_size[1])`.
|
| 198 |
+
"""
|
| 199 |
+
# reshape back to image like
|
| 200 |
+
features = reshape_features(hidden_state)
|
| 201 |
+
|
| 202 |
+
# merge all patches in a batch to create one large patch per batch
|
| 203 |
+
features = merge_patches(
|
| 204 |
+
features,
|
| 205 |
+
batch_size=batch_size,
|
| 206 |
+
padding=padding,
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
# interpolate patches to base size
|
| 210 |
+
features = F.interpolate(
|
| 211 |
+
features,
|
| 212 |
+
size=output_size,
|
| 213 |
+
mode="bilinear",
|
| 214 |
+
align_corners=False,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
return features
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class DepthProPatchEncoder(nn.Module):
|
| 221 |
+
def __init__(self, config: DepthProConfig):
|
| 222 |
+
super().__init__()
|
| 223 |
+
self.config = config
|
| 224 |
+
|
| 225 |
+
self.intermediate_hook_ids = config.intermediate_hook_ids
|
| 226 |
+
self.intermediate_feature_dims = config.intermediate_feature_dims
|
| 227 |
+
self.scaled_images_ratios = config.scaled_images_ratios
|
| 228 |
+
self.scaled_images_overlap_ratios = config.scaled_images_overlap_ratios
|
| 229 |
+
self.scaled_images_feature_dims = config.scaled_images_feature_dims
|
| 230 |
+
self.merge_padding_value = config.merge_padding_value
|
| 231 |
+
|
| 232 |
+
self.n_scaled_images = len(config.scaled_images_ratios)
|
| 233 |
+
self.n_intermediate_hooks = len(config.intermediate_hook_ids)
|
| 234 |
+
self.out_size = config.image_model_config.image_size // config.image_model_config.patch_size
|
| 235 |
+
|
| 236 |
+
self.model = AutoModel.from_config(config.patch_model_config)
|
| 237 |
+
|
| 238 |
+
def forward(
|
| 239 |
+
self,
|
| 240 |
+
pixel_values: torch.Tensor,
|
| 241 |
+
) -> list[torch.Tensor]:
|
| 242 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 243 |
+
|
| 244 |
+
if min(self.scaled_images_ratios) * min(height, width) < self.config.patch_size:
|
| 245 |
+
raise ValueError(
|
| 246 |
+
f"Image size {height}x{width} is too small to be scaled "
|
| 247 |
+
f"with scaled_images_ratios={self.scaled_images_ratios} "
|
| 248 |
+
f"when patch_size={self.config.patch_size}."
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
# STEP 1: create 3-level image
|
| 252 |
+
|
| 253 |
+
scaled_images = []
|
| 254 |
+
for ratio in self.scaled_images_ratios:
|
| 255 |
+
scaled_images.append(
|
| 256 |
+
F.interpolate(
|
| 257 |
+
pixel_values,
|
| 258 |
+
scale_factor=ratio,
|
| 259 |
+
mode="bilinear",
|
| 260 |
+
align_corners=False,
|
| 261 |
+
)
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
# STEP 2: create patches
|
| 265 |
+
|
| 266 |
+
for i in range(self.n_scaled_images):
|
| 267 |
+
scaled_images[i] = split_to_patches(
|
| 268 |
+
scaled_images[i],
|
| 269 |
+
patch_size=self.config.patch_size,
|
| 270 |
+
overlap_ratio=self.scaled_images_overlap_ratios[i],
|
| 271 |
+
)
|
| 272 |
+
n_patches_per_scaled_image = [len(i) for i in scaled_images]
|
| 273 |
+
patches = torch.cat(scaled_images[::-1], dim=0) # -1 as patch encoder expects high res patches first
|
| 274 |
+
|
| 275 |
+
# STEP 3: apply patch encoder
|
| 276 |
+
|
| 277 |
+
encodings = self.model(
|
| 278 |
+
# each patch is processed as a separate batch
|
| 279 |
+
patches,
|
| 280 |
+
# required for intermediate features
|
| 281 |
+
output_hidden_states=self.n_intermediate_hooks > 0,
|
| 282 |
+
return_dict=True,
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
scaled_images_last_hidden_state = torch.split_with_sizes(
|
| 286 |
+
encodings.last_hidden_state, n_patches_per_scaled_image[::-1]
|
| 287 |
+
)
|
| 288 |
+
# -1 (reverse list) as patch encoder returns high res patches first, we need low res first
|
| 289 |
+
scaled_images_last_hidden_state = scaled_images_last_hidden_state[::-1]
|
| 290 |
+
|
| 291 |
+
# calculate base height and width
|
| 292 |
+
# base height and width are the dimensions of the lowest resolution features
|
| 293 |
+
exponent_value = torch_int(math.log2(width / self.out_size))
|
| 294 |
+
base_height = height // 2**exponent_value
|
| 295 |
+
base_width = width // 2**exponent_value
|
| 296 |
+
|
| 297 |
+
# STEP 4: get patch features (high_res, med_res, low_res) - (3-5) in diagram
|
| 298 |
+
|
| 299 |
+
scaled_images_features = []
|
| 300 |
+
for i in range(self.n_scaled_images):
|
| 301 |
+
hidden_state = scaled_images_last_hidden_state[i]
|
| 302 |
+
padding = torch_int(self.merge_padding_value * (1 / self.scaled_images_ratios[i]))
|
| 303 |
+
output_height = base_height * 2**i
|
| 304 |
+
output_width = base_width * 2**i
|
| 305 |
+
features = reconstruct_feature_maps(
|
| 306 |
+
hidden_state,
|
| 307 |
+
batch_size=batch_size,
|
| 308 |
+
padding=padding,
|
| 309 |
+
output_size=(output_height, output_width),
|
| 310 |
+
)
|
| 311 |
+
scaled_images_features.append(features)
|
| 312 |
+
|
| 313 |
+
# STEP 5: get intermediate features - (1-2) in diagram
|
| 314 |
+
|
| 315 |
+
intermediate_features = []
|
| 316 |
+
for i in range(self.n_intermediate_hooks):
|
| 317 |
+
# +1 to correct index position as hidden_states contain embedding output as well
|
| 318 |
+
hidden_state = encodings.hidden_states[self.intermediate_hook_ids[i] + 1]
|
| 319 |
+
padding = torch_int(self.merge_padding_value * (1 / self.scaled_images_ratios[-1]))
|
| 320 |
+
output_height = base_height * 2 ** (self.n_scaled_images - 1)
|
| 321 |
+
output_width = base_width * 2 ** (self.n_scaled_images - 1)
|
| 322 |
+
features = reconstruct_feature_maps(
|
| 323 |
+
hidden_state,
|
| 324 |
+
batch_size=batch_size,
|
| 325 |
+
padding=padding,
|
| 326 |
+
output_size=(output_height, output_width),
|
| 327 |
+
)
|
| 328 |
+
intermediate_features.append(features)
|
| 329 |
+
|
| 330 |
+
# STEP 7: combine all features
|
| 331 |
+
features = [*scaled_images_features, *intermediate_features]
|
| 332 |
+
|
| 333 |
+
return features
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
class DepthProImageEncoder(nn.Module):
|
| 337 |
+
def __init__(self, config: DepthProConfig):
|
| 338 |
+
super().__init__()
|
| 339 |
+
self.config = config
|
| 340 |
+
self.out_size = config.image_model_config.image_size // config.image_model_config.patch_size
|
| 341 |
+
|
| 342 |
+
self.model = AutoModel.from_config(config.image_model_config)
|
| 343 |
+
|
| 344 |
+
def forward(
|
| 345 |
+
self,
|
| 346 |
+
pixel_values: torch.Tensor,
|
| 347 |
+
output_attentions: bool = False,
|
| 348 |
+
output_hidden_states: bool = False,
|
| 349 |
+
return_dict: bool = True,
|
| 350 |
+
) -> tuple | DepthProOutput:
|
| 351 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 352 |
+
|
| 353 |
+
# scale the image for image_encoder
|
| 354 |
+
size = self.config.image_model_config.image_size
|
| 355 |
+
pixel_values = F.interpolate(
|
| 356 |
+
pixel_values,
|
| 357 |
+
size=(size, size),
|
| 358 |
+
mode="bilinear",
|
| 359 |
+
align_corners=False,
|
| 360 |
+
)
|
| 361 |
+
encodings = self.model(
|
| 362 |
+
pixel_values=pixel_values,
|
| 363 |
+
output_attentions=output_attentions,
|
| 364 |
+
output_hidden_states=output_hidden_states,
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
# calculate base height and width
|
| 368 |
+
# base height and width are the dimensions of the lowest resolution features
|
| 369 |
+
exponent_value = torch_int(math.log2(width / self.out_size))
|
| 370 |
+
base_height = height // 2**exponent_value
|
| 371 |
+
base_width = width // 2**exponent_value
|
| 372 |
+
|
| 373 |
+
features = reconstruct_feature_maps(
|
| 374 |
+
encodings[0],
|
| 375 |
+
batch_size=batch_size,
|
| 376 |
+
padding=0,
|
| 377 |
+
output_size=(base_height, base_width),
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
if not return_dict:
|
| 381 |
+
return (encodings[0], features) + encodings[2:] # ignore last_hidden_state and poooler output
|
| 382 |
+
|
| 383 |
+
return DepthProOutput(
|
| 384 |
+
last_hidden_state=encodings.last_hidden_state,
|
| 385 |
+
features=features,
|
| 386 |
+
hidden_states=encodings.hidden_states,
|
| 387 |
+
attentions=encodings.attentions,
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
class DepthProEncoder(nn.Module):
|
| 392 |
+
def __init__(self, config: DepthProConfig):
|
| 393 |
+
super().__init__()
|
| 394 |
+
self.config = config
|
| 395 |
+
self.intermediate_hook_ids = config.intermediate_hook_ids
|
| 396 |
+
self.intermediate_feature_dims = config.intermediate_feature_dims
|
| 397 |
+
self.scaled_images_ratios = config.scaled_images_ratios
|
| 398 |
+
self.scaled_images_overlap_ratios = config.scaled_images_overlap_ratios
|
| 399 |
+
self.scaled_images_feature_dims = config.scaled_images_feature_dims
|
| 400 |
+
self.merge_padding_value = config.merge_padding_value
|
| 401 |
+
|
| 402 |
+
self.n_scaled_images = len(self.scaled_images_ratios)
|
| 403 |
+
self.n_intermediate_hooks = len(self.intermediate_hook_ids)
|
| 404 |
+
|
| 405 |
+
self.patch_encoder = DepthProPatchEncoder(config)
|
| 406 |
+
self.image_encoder = DepthProImageEncoder(config)
|
| 407 |
+
|
| 408 |
+
def forward(
|
| 409 |
+
self,
|
| 410 |
+
pixel_values: torch.Tensor,
|
| 411 |
+
output_attentions: bool = False,
|
| 412 |
+
output_hidden_states: bool = False,
|
| 413 |
+
return_dict: bool = True,
|
| 414 |
+
) -> tuple | DepthProOutput:
|
| 415 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 416 |
+
|
| 417 |
+
patch_features = self.patch_encoder(
|
| 418 |
+
pixel_values,
|
| 419 |
+
)
|
| 420 |
+
image_encodings = self.image_encoder(
|
| 421 |
+
pixel_values,
|
| 422 |
+
output_attentions=output_attentions,
|
| 423 |
+
output_hidden_states=output_hidden_states,
|
| 424 |
+
return_dict=return_dict,
|
| 425 |
+
)
|
| 426 |
+
image_features = image_encodings[1] # index 1 contains features
|
| 427 |
+
|
| 428 |
+
features = [image_features, *patch_features]
|
| 429 |
+
|
| 430 |
+
if not return_dict:
|
| 431 |
+
return (image_encodings[0], features) + image_encodings[2:]
|
| 432 |
+
|
| 433 |
+
return DepthProOutput(
|
| 434 |
+
last_hidden_state=image_encodings.last_hidden_state,
|
| 435 |
+
features=features,
|
| 436 |
+
hidden_states=image_encodings.hidden_states,
|
| 437 |
+
attentions=image_encodings.attentions,
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
class DepthProFeatureUpsampleBlock(nn.Module):
|
| 442 |
+
def __init__(
|
| 443 |
+
self,
|
| 444 |
+
config: DepthProConfig,
|
| 445 |
+
input_dims: int,
|
| 446 |
+
intermediate_dims: int,
|
| 447 |
+
output_dims: int,
|
| 448 |
+
n_upsample_layers: int,
|
| 449 |
+
use_proj: bool = True,
|
| 450 |
+
bias: bool = False,
|
| 451 |
+
):
|
| 452 |
+
super().__init__()
|
| 453 |
+
self.config = config
|
| 454 |
+
self.layers = nn.ModuleList()
|
| 455 |
+
|
| 456 |
+
# create first projection layer
|
| 457 |
+
if use_proj:
|
| 458 |
+
proj = nn.Conv2d(
|
| 459 |
+
in_channels=input_dims,
|
| 460 |
+
out_channels=intermediate_dims,
|
| 461 |
+
kernel_size=1,
|
| 462 |
+
stride=1,
|
| 463 |
+
padding=0,
|
| 464 |
+
bias=bias,
|
| 465 |
+
)
|
| 466 |
+
self.layers.append(proj)
|
| 467 |
+
|
| 468 |
+
# create following upsample layers
|
| 469 |
+
for i in range(n_upsample_layers):
|
| 470 |
+
in_channels = intermediate_dims if i == 0 else output_dims
|
| 471 |
+
layer = nn.ConvTranspose2d(
|
| 472 |
+
in_channels=in_channels,
|
| 473 |
+
out_channels=output_dims,
|
| 474 |
+
kernel_size=2,
|
| 475 |
+
stride=2,
|
| 476 |
+
padding=0,
|
| 477 |
+
bias=bias,
|
| 478 |
+
)
|
| 479 |
+
self.layers.append(layer)
|
| 480 |
+
|
| 481 |
+
def forward(self, features: torch.Tensor) -> torch.Tensor:
|
| 482 |
+
for layer in self.layers:
|
| 483 |
+
features = layer(features)
|
| 484 |
+
return features
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
class DepthProFeatureUpsample(nn.Module):
|
| 488 |
+
def __init__(self, config: DepthProConfig):
|
| 489 |
+
super().__init__()
|
| 490 |
+
self.config = config
|
| 491 |
+
self.n_scaled_images = len(self.config.scaled_images_ratios)
|
| 492 |
+
self.n_intermediate_hooks = len(self.config.intermediate_hook_ids)
|
| 493 |
+
|
| 494 |
+
# for image_features
|
| 495 |
+
self.image_block = DepthProFeatureUpsampleBlock(
|
| 496 |
+
config=config,
|
| 497 |
+
input_dims=config.image_model_config.hidden_size,
|
| 498 |
+
intermediate_dims=config.image_model_config.hidden_size,
|
| 499 |
+
output_dims=config.scaled_images_feature_dims[0],
|
| 500 |
+
n_upsample_layers=1,
|
| 501 |
+
use_proj=False,
|
| 502 |
+
bias=True,
|
| 503 |
+
)
|
| 504 |
+
|
| 505 |
+
# for scaled_images_features
|
| 506 |
+
self.scaled_images = nn.ModuleList()
|
| 507 |
+
for i, feature_dims in enumerate(config.scaled_images_feature_dims):
|
| 508 |
+
block = DepthProFeatureUpsampleBlock(
|
| 509 |
+
config=config,
|
| 510 |
+
input_dims=config.patch_model_config.hidden_size,
|
| 511 |
+
intermediate_dims=feature_dims,
|
| 512 |
+
output_dims=feature_dims,
|
| 513 |
+
n_upsample_layers=1,
|
| 514 |
+
)
|
| 515 |
+
self.scaled_images.append(block)
|
| 516 |
+
|
| 517 |
+
# for intermediate_features
|
| 518 |
+
self.intermediate = nn.ModuleList()
|
| 519 |
+
for i, feature_dims in enumerate(config.intermediate_feature_dims):
|
| 520 |
+
intermediate_dims = config.fusion_hidden_size if i == 0 else feature_dims
|
| 521 |
+
block = DepthProFeatureUpsampleBlock(
|
| 522 |
+
config=config,
|
| 523 |
+
input_dims=config.patch_model_config.hidden_size,
|
| 524 |
+
intermediate_dims=intermediate_dims,
|
| 525 |
+
output_dims=feature_dims,
|
| 526 |
+
n_upsample_layers=2 + i,
|
| 527 |
+
)
|
| 528 |
+
self.intermediate.append(block)
|
| 529 |
+
|
| 530 |
+
def forward(self, features: list[torch.Tensor]) -> list[torch.Tensor]:
|
| 531 |
+
features[0] = self.image_block(features[0])
|
| 532 |
+
|
| 533 |
+
for i in range(self.n_scaled_images):
|
| 534 |
+
features[i + 1] = self.scaled_images[i](features[i + 1])
|
| 535 |
+
|
| 536 |
+
for i in range(self.n_intermediate_hooks):
|
| 537 |
+
features[self.n_scaled_images + i + 1] = self.intermediate[i](features[self.n_scaled_images + i + 1])
|
| 538 |
+
|
| 539 |
+
return features
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
class DepthProFeatureProjection(nn.Module):
|
| 543 |
+
def __init__(self, config: DepthProConfig):
|
| 544 |
+
super().__init__()
|
| 545 |
+
self.config = config
|
| 546 |
+
|
| 547 |
+
combined_feature_dims = config.scaled_images_feature_dims + config.intermediate_feature_dims
|
| 548 |
+
self.projections = nn.ModuleList()
|
| 549 |
+
for i, in_channels in enumerate(combined_feature_dims):
|
| 550 |
+
if i == len(combined_feature_dims) - 1 and in_channels == config.fusion_hidden_size:
|
| 551 |
+
# projection for last layer can be ignored if input and output channels already match
|
| 552 |
+
self.projections.append(nn.Identity())
|
| 553 |
+
else:
|
| 554 |
+
self.projections.append(
|
| 555 |
+
nn.Conv2d(
|
| 556 |
+
in_channels=in_channels,
|
| 557 |
+
out_channels=config.fusion_hidden_size,
|
| 558 |
+
kernel_size=3,
|
| 559 |
+
stride=1,
|
| 560 |
+
padding=1,
|
| 561 |
+
bias=False,
|
| 562 |
+
)
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
def forward(self, features: list[torch.Tensor]) -> list[torch.Tensor]:
|
| 566 |
+
projected_features = []
|
| 567 |
+
for i, projection in enumerate(self.projections):
|
| 568 |
+
upsampled_feature = projection(features[i])
|
| 569 |
+
projected_features.append(upsampled_feature)
|
| 570 |
+
return projected_features
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
class DepthProNeck(nn.Module):
|
| 574 |
+
def __init__(self, config: DepthProConfig):
|
| 575 |
+
super().__init__()
|
| 576 |
+
self.config = config
|
| 577 |
+
|
| 578 |
+
self.feature_upsample = DepthProFeatureUpsample(config)
|
| 579 |
+
self.fuse_image_with_low_res = nn.Conv2d(
|
| 580 |
+
in_channels=config.scaled_images_feature_dims[0] * 2,
|
| 581 |
+
out_channels=config.scaled_images_feature_dims[0],
|
| 582 |
+
kernel_size=1,
|
| 583 |
+
stride=1,
|
| 584 |
+
padding=0,
|
| 585 |
+
bias=True,
|
| 586 |
+
)
|
| 587 |
+
self.feature_projection = DepthProFeatureProjection(config)
|
| 588 |
+
|
| 589 |
+
def forward(self, features: list[torch.Tensor]) -> list[torch.Tensor]:
|
| 590 |
+
features = self.feature_upsample(features)
|
| 591 |
+
# global features = low res features + image features
|
| 592 |
+
global_features = torch.cat((features[1], features[0]), dim=1)
|
| 593 |
+
global_features = self.fuse_image_with_low_res(global_features)
|
| 594 |
+
features = [global_features, *features[2:]]
|
| 595 |
+
features = self.feature_projection(features)
|
| 596 |
+
return features
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
# General docstring
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
@auto_docstring
|
| 603 |
+
class DepthProPreTrainedModel(PreTrainedModel):
|
| 604 |
+
config: DepthProConfig
|
| 605 |
+
base_model_prefix = "depth_pro"
|
| 606 |
+
main_input_name = "pixel_values"
|
| 607 |
+
input_modalities = ("image",)
|
| 608 |
+
supports_gradient_checkpointing = True
|
| 609 |
+
_supports_sdpa = True
|
| 610 |
+
_no_split_modules = ["DepthProPreActResidualLayer"]
|
| 611 |
+
_keys_to_ignore_on_load_unexpected = ["fov_model.*"]
|
| 612 |
+
|
| 613 |
+
@torch.no_grad()
|
| 614 |
+
def _init_weights(self, module):
|
| 615 |
+
"""Initialize the weights"""
|
| 616 |
+
if isinstance(module, nn.Linear):
|
| 617 |
+
init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 618 |
+
if module.bias is not None:
|
| 619 |
+
init.zeros_(module.bias)
|
| 620 |
+
elif isinstance(module, nn.LayerNorm):
|
| 621 |
+
init.zeros_(module.bias)
|
| 622 |
+
init.ones_(module.weight)
|
| 623 |
+
elif isinstance(module, (nn.Conv2d, nn.ConvTranspose2d)):
|
| 624 |
+
init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu")
|
| 625 |
+
if module.bias is not None:
|
| 626 |
+
init.zeros_(module.bias)
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
@auto_docstring
|
| 630 |
+
class DepthProModel(DepthProPreTrainedModel):
|
| 631 |
+
def __init__(self, config):
|
| 632 |
+
super().__init__(config)
|
| 633 |
+
self.config = config
|
| 634 |
+
self.encoder = DepthProEncoder(config)
|
| 635 |
+
self.neck = DepthProNeck(config)
|
| 636 |
+
# Initialize weights and apply final processing
|
| 637 |
+
self.post_init()
|
| 638 |
+
|
| 639 |
+
def get_input_embeddings(self):
|
| 640 |
+
return self.encoder.image_encoder.model.get_input_embeddings()
|
| 641 |
+
|
| 642 |
+
@auto_docstring
|
| 643 |
+
def forward(
|
| 644 |
+
self,
|
| 645 |
+
pixel_values: torch.FloatTensor,
|
| 646 |
+
output_attentions: bool | None = None,
|
| 647 |
+
output_hidden_states: bool | None = None,
|
| 648 |
+
return_dict: bool | None = None,
|
| 649 |
+
**kwargs,
|
| 650 |
+
) -> tuple | DepthProOutput:
|
| 651 |
+
r"""
|
| 652 |
+
Examples:
|
| 653 |
+
|
| 654 |
+
```python
|
| 655 |
+
>>> import torch
|
| 656 |
+
>>> from PIL import Image
|
| 657 |
+
>>> import httpx
|
| 658 |
+
>>> from io import BytesIO
|
| 659 |
+
>>> from transformers import AutoProcessor, DepthProModel
|
| 660 |
+
|
| 661 |
+
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
| 662 |
+
>>> with httpx.stream("GET", url) as response:
|
| 663 |
+
... image = Image.open(BytesIO(response.read()))
|
| 664 |
+
|
| 665 |
+
>>> checkpoint = "apple/DepthPro-hf"
|
| 666 |
+
>>> processor = AutoProcessor.from_pretrained(checkpoint)
|
| 667 |
+
>>> model = DepthProModel.from_pretrained(checkpoint)
|
| 668 |
+
|
| 669 |
+
>>> # prepare image for the model
|
| 670 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 671 |
+
|
| 672 |
+
>>> with torch.no_grad():
|
| 673 |
+
... output = model(**inputs)
|
| 674 |
+
|
| 675 |
+
>>> output.last_hidden_state.shape
|
| 676 |
+
torch.Size([1, 35, 577, 1024])
|
| 677 |
+
```"""
|
| 678 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 679 |
+
output_hidden_states = (
|
| 680 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 681 |
+
)
|
| 682 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 683 |
+
|
| 684 |
+
encodings = self.encoder(
|
| 685 |
+
pixel_values,
|
| 686 |
+
output_attentions=output_attentions,
|
| 687 |
+
output_hidden_states=output_hidden_states,
|
| 688 |
+
return_dict=return_dict,
|
| 689 |
+
)
|
| 690 |
+
features = encodings[1] # index 1 contains features
|
| 691 |
+
features = self.neck(features)
|
| 692 |
+
|
| 693 |
+
if not return_dict:
|
| 694 |
+
return (encodings[0], features) + encodings[2:]
|
| 695 |
+
|
| 696 |
+
return DepthProOutput(
|
| 697 |
+
last_hidden_state=encodings.last_hidden_state,
|
| 698 |
+
features=features,
|
| 699 |
+
hidden_states=encodings.hidden_states,
|
| 700 |
+
attentions=encodings.attentions,
|
| 701 |
+
)
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
# Copied from transformers.models.dpt.modeling_dpt.DPTPreActResidualLayer DPT->DepthPro
|
| 705 |
+
class DepthProPreActResidualLayer(nn.Module):
|
| 706 |
+
"""
|
| 707 |
+
ResidualConvUnit, pre-activate residual unit.
|
| 708 |
+
|
| 709 |
+
Args:
|
| 710 |
+
config (`[DepthProConfig]`):
|
| 711 |
+
Model configuration class defining the model architecture.
|
| 712 |
+
"""
|
| 713 |
+
|
| 714 |
+
def __init__(self, config: DepthProConfig):
|
| 715 |
+
super().__init__()
|
| 716 |
+
|
| 717 |
+
self.use_batch_norm = config.use_batch_norm_in_fusion_residual
|
| 718 |
+
use_bias_in_fusion_residual = (
|
| 719 |
+
config.use_bias_in_fusion_residual
|
| 720 |
+
if config.use_bias_in_fusion_residual is not None
|
| 721 |
+
else not self.use_batch_norm
|
| 722 |
+
)
|
| 723 |
+
|
| 724 |
+
self.activation1 = nn.ReLU()
|
| 725 |
+
self.convolution1 = nn.Conv2d(
|
| 726 |
+
config.fusion_hidden_size,
|
| 727 |
+
config.fusion_hidden_size,
|
| 728 |
+
kernel_size=3,
|
| 729 |
+
stride=1,
|
| 730 |
+
padding=1,
|
| 731 |
+
bias=use_bias_in_fusion_residual,
|
| 732 |
+
)
|
| 733 |
+
|
| 734 |
+
self.activation2 = nn.ReLU()
|
| 735 |
+
self.convolution2 = nn.Conv2d(
|
| 736 |
+
config.fusion_hidden_size,
|
| 737 |
+
config.fusion_hidden_size,
|
| 738 |
+
kernel_size=3,
|
| 739 |
+
stride=1,
|
| 740 |
+
padding=1,
|
| 741 |
+
bias=use_bias_in_fusion_residual,
|
| 742 |
+
)
|
| 743 |
+
|
| 744 |
+
if self.use_batch_norm:
|
| 745 |
+
self.batch_norm1 = nn.BatchNorm2d(config.fusion_hidden_size)
|
| 746 |
+
self.batch_norm2 = nn.BatchNorm2d(config.fusion_hidden_size)
|
| 747 |
+
|
| 748 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 749 |
+
residual = hidden_state
|
| 750 |
+
hidden_state = self.activation1(hidden_state)
|
| 751 |
+
|
| 752 |
+
hidden_state = self.convolution1(hidden_state)
|
| 753 |
+
|
| 754 |
+
if self.use_batch_norm:
|
| 755 |
+
hidden_state = self.batch_norm1(hidden_state)
|
| 756 |
+
|
| 757 |
+
hidden_state = self.activation2(hidden_state)
|
| 758 |
+
hidden_state = self.convolution2(hidden_state)
|
| 759 |
+
|
| 760 |
+
if self.use_batch_norm:
|
| 761 |
+
hidden_state = self.batch_norm2(hidden_state)
|
| 762 |
+
|
| 763 |
+
return hidden_state + residual
|
| 764 |
+
|
| 765 |
+
|
| 766 |
+
# Modified from transformers.models.dpt.modeling_dpt.DPTFeatureFusionLayer
|
| 767 |
+
# except it uses deconv and skip_add and needs no interpolation
|
| 768 |
+
class DepthProFeatureFusionLayer(nn.Module):
|
| 769 |
+
def __init__(self, config: DepthProConfig, use_deconv: bool = True):
|
| 770 |
+
super().__init__()
|
| 771 |
+
self.config = config
|
| 772 |
+
self.use_deconv = use_deconv
|
| 773 |
+
|
| 774 |
+
self.residual_layer1 = DepthProPreActResidualLayer(config)
|
| 775 |
+
self.residual_layer2 = DepthProPreActResidualLayer(config)
|
| 776 |
+
|
| 777 |
+
if self.use_deconv:
|
| 778 |
+
self.deconv = nn.ConvTranspose2d(
|
| 779 |
+
in_channels=config.fusion_hidden_size,
|
| 780 |
+
out_channels=config.fusion_hidden_size,
|
| 781 |
+
kernel_size=2,
|
| 782 |
+
stride=2,
|
| 783 |
+
padding=0,
|
| 784 |
+
bias=False,
|
| 785 |
+
)
|
| 786 |
+
|
| 787 |
+
self.projection = nn.Conv2d(config.fusion_hidden_size, config.fusion_hidden_size, kernel_size=1, bias=True)
|
| 788 |
+
|
| 789 |
+
def forward(self, hidden_state: torch.Tensor, residual: torch.Tensor | None = None) -> torch.Tensor:
|
| 790 |
+
if residual is not None:
|
| 791 |
+
residual = self.residual_layer1(residual)
|
| 792 |
+
hidden_state = hidden_state + residual
|
| 793 |
+
|
| 794 |
+
hidden_state = self.residual_layer2(hidden_state)
|
| 795 |
+
if self.use_deconv:
|
| 796 |
+
hidden_state = self.deconv(hidden_state)
|
| 797 |
+
hidden_state = self.projection(hidden_state)
|
| 798 |
+
|
| 799 |
+
return hidden_state
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
# Modified from transformers.models.dpt.modeling_dpt.DPTFeatureFusionStage with DPT->DepthPro
|
| 803 |
+
# with deconv and reversed layers
|
| 804 |
+
class DepthProFeatureFusionStage(nn.Module):
|
| 805 |
+
def __init__(self, config):
|
| 806 |
+
super().__init__()
|
| 807 |
+
self.config = config
|
| 808 |
+
|
| 809 |
+
self.num_layers = len(config.intermediate_hook_ids) + len(config.scaled_images_ratios)
|
| 810 |
+
self.intermediate = nn.ModuleList()
|
| 811 |
+
for _ in range(self.num_layers - 1):
|
| 812 |
+
self.intermediate.append(DepthProFeatureFusionLayer(config))
|
| 813 |
+
|
| 814 |
+
# final layer does not require deconvolution
|
| 815 |
+
self.final = DepthProFeatureFusionLayer(config, use_deconv=False)
|
| 816 |
+
|
| 817 |
+
def forward(self, hidden_states: list[torch.Tensor]) -> list[torch.Tensor]:
|
| 818 |
+
if self.num_layers != len(hidden_states):
|
| 819 |
+
raise ValueError(
|
| 820 |
+
f"num_layers={self.num_layers} in DepthProFeatureFusionStage"
|
| 821 |
+
f"does not match len(hidden_states)={len(hidden_states)}"
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
fused_hidden_states = []
|
| 825 |
+
fused_hidden_state = None
|
| 826 |
+
for hidden_state, layer in zip(hidden_states[:-1], self.intermediate):
|
| 827 |
+
if fused_hidden_state is None:
|
| 828 |
+
# first layer only uses the last hidden_state
|
| 829 |
+
fused_hidden_state = layer(hidden_state)
|
| 830 |
+
else:
|
| 831 |
+
fused_hidden_state = layer(fused_hidden_state, hidden_state)
|
| 832 |
+
fused_hidden_states.append(fused_hidden_state)
|
| 833 |
+
|
| 834 |
+
hidden_state = hidden_states[-1]
|
| 835 |
+
fused_hidden_state = self.final(fused_hidden_state, hidden_state)
|
| 836 |
+
fused_hidden_states.append(fused_hidden_state)
|
| 837 |
+
|
| 838 |
+
return fused_hidden_states
|
| 839 |
+
|
| 840 |
+
|
| 841 |
+
class DepthProFovEncoder(nn.Module):
|
| 842 |
+
def __init__(self, config: DepthProConfig):
|
| 843 |
+
super().__init__()
|
| 844 |
+
self.config = config
|
| 845 |
+
self.out_size = config.image_model_config.image_size // config.image_model_config.patch_size
|
| 846 |
+
|
| 847 |
+
self.model = AutoModel.from_config(config.fov_model_config)
|
| 848 |
+
self.neck = nn.Linear(config.fov_model_config.hidden_size, config.fusion_hidden_size // 2)
|
| 849 |
+
|
| 850 |
+
def forward(
|
| 851 |
+
self,
|
| 852 |
+
pixel_values: torch.Tensor,
|
| 853 |
+
) -> torch.Tensor:
|
| 854 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 855 |
+
|
| 856 |
+
# scale the image for fov_encoder
|
| 857 |
+
size = self.config.fov_model_config.image_size
|
| 858 |
+
pixel_values = F.interpolate(
|
| 859 |
+
pixel_values,
|
| 860 |
+
size=(size, size),
|
| 861 |
+
mode="bilinear",
|
| 862 |
+
align_corners=False,
|
| 863 |
+
)
|
| 864 |
+
encodings = self.model(
|
| 865 |
+
pixel_values=pixel_values,
|
| 866 |
+
)
|
| 867 |
+
hidden_state = encodings[0]
|
| 868 |
+
hidden_state = self.neck(hidden_state)
|
| 869 |
+
|
| 870 |
+
# calculate base height and width
|
| 871 |
+
# base height and width are the dimensions of the lowest resolution features
|
| 872 |
+
exponent_value = torch_int(math.log2(width / self.out_size))
|
| 873 |
+
base_height = height // 2**exponent_value
|
| 874 |
+
base_width = width // 2**exponent_value
|
| 875 |
+
|
| 876 |
+
features = reconstruct_feature_maps(
|
| 877 |
+
hidden_state,
|
| 878 |
+
batch_size=batch_size,
|
| 879 |
+
padding=0,
|
| 880 |
+
output_size=(base_height, base_width),
|
| 881 |
+
)
|
| 882 |
+
|
| 883 |
+
return features
|
| 884 |
+
|
| 885 |
+
|
| 886 |
+
class DepthProFovHead(nn.Module):
|
| 887 |
+
def __init__(self, config: DepthProConfig):
|
| 888 |
+
super().__init__()
|
| 889 |
+
self.config = config
|
| 890 |
+
self.fusion_hidden_size = config.fusion_hidden_size
|
| 891 |
+
self.out_size = config.image_model_config.image_size // config.image_model_config.patch_size
|
| 892 |
+
|
| 893 |
+
# create initial head layers
|
| 894 |
+
self.layers = nn.ModuleList()
|
| 895 |
+
for i in range(config.num_fov_head_layers):
|
| 896 |
+
self.layers.append(
|
| 897 |
+
nn.Conv2d(
|
| 898 |
+
math.ceil(self.fusion_hidden_size / 2 ** (i + 1)),
|
| 899 |
+
math.ceil(self.fusion_hidden_size / 2 ** (i + 2)),
|
| 900 |
+
kernel_size=3,
|
| 901 |
+
stride=2,
|
| 902 |
+
padding=1,
|
| 903 |
+
)
|
| 904 |
+
)
|
| 905 |
+
self.layers.append(nn.ReLU(True))
|
| 906 |
+
# calculate expected shapes to finally generate a scalar output from final head layer
|
| 907 |
+
final_in_channels = math.ceil(self.fusion_hidden_size / 2 ** (config.num_fov_head_layers + 1))
|
| 908 |
+
final_kernel_size = torch_int((self.out_size - 1) / 2**config.num_fov_head_layers + 1)
|
| 909 |
+
self.layers.append(
|
| 910 |
+
nn.Conv2d(
|
| 911 |
+
in_channels=final_in_channels, out_channels=1, kernel_size=final_kernel_size, stride=1, padding=0
|
| 912 |
+
)
|
| 913 |
+
)
|
| 914 |
+
|
| 915 |
+
def forward(self, features: torch.Tensor) -> torch.Tensor:
|
| 916 |
+
features = F.interpolate(
|
| 917 |
+
features,
|
| 918 |
+
size=(self.out_size, self.out_size),
|
| 919 |
+
mode="bilinear",
|
| 920 |
+
align_corners=False,
|
| 921 |
+
)
|
| 922 |
+
for layer in self.layers:
|
| 923 |
+
features = layer(features)
|
| 924 |
+
return features
|
| 925 |
+
|
| 926 |
+
|
| 927 |
+
class DepthProFovModel(nn.Module):
|
| 928 |
+
def __init__(self, config: DepthProConfig):
|
| 929 |
+
super().__init__()
|
| 930 |
+
self.config = config
|
| 931 |
+
self.fusion_hidden_size = config.fusion_hidden_size
|
| 932 |
+
|
| 933 |
+
self.fov_encoder = DepthProFovEncoder(config)
|
| 934 |
+
self.conv = nn.Conv2d(
|
| 935 |
+
self.fusion_hidden_size, self.fusion_hidden_size // 2, kernel_size=3, stride=2, padding=1
|
| 936 |
+
)
|
| 937 |
+
self.activation = nn.ReLU(inplace=True)
|
| 938 |
+
self.head = DepthProFovHead(config)
|
| 939 |
+
|
| 940 |
+
def forward(
|
| 941 |
+
self,
|
| 942 |
+
pixel_values: torch.Tensor,
|
| 943 |
+
global_features: torch.Tensor,
|
| 944 |
+
) -> torch.Tensor:
|
| 945 |
+
fov_features = self.fov_encoder(pixel_values)
|
| 946 |
+
|
| 947 |
+
global_features = self.conv(global_features)
|
| 948 |
+
global_features = self.activation(global_features)
|
| 949 |
+
|
| 950 |
+
fov_features = fov_features + global_features
|
| 951 |
+
fov_output = self.head(fov_features)
|
| 952 |
+
fov_output = fov_output.flatten()
|
| 953 |
+
|
| 954 |
+
return fov_output
|
| 955 |
+
|
| 956 |
+
|
| 957 |
+
class DepthProDepthEstimationHead(nn.Module):
|
| 958 |
+
"""
|
| 959 |
+
The DepthProDepthEstimationHead module serves as the output head for depth estimation tasks.
|
| 960 |
+
This module comprises a sequence of convolutional and transposed convolutional layers
|
| 961 |
+
that process the feature map from the fusion to produce a single-channel depth map.
|
| 962 |
+
Key operations include dimensionality reduction and upsampling to match the input resolution.
|
| 963 |
+
"""
|
| 964 |
+
|
| 965 |
+
def __init__(self, config):
|
| 966 |
+
super().__init__()
|
| 967 |
+
self.config = config
|
| 968 |
+
|
| 969 |
+
features = config.fusion_hidden_size
|
| 970 |
+
self.layers = nn.ModuleList(
|
| 971 |
+
[
|
| 972 |
+
nn.Conv2d(features, features // 2, kernel_size=3, stride=1, padding=1),
|
| 973 |
+
nn.ConvTranspose2d(
|
| 974 |
+
in_channels=features // 2,
|
| 975 |
+
out_channels=features // 2,
|
| 976 |
+
kernel_size=2,
|
| 977 |
+
stride=2,
|
| 978 |
+
padding=0,
|
| 979 |
+
bias=True,
|
| 980 |
+
),
|
| 981 |
+
nn.Conv2d(features // 2, 32, kernel_size=3, stride=1, padding=1),
|
| 982 |
+
nn.ReLU(True),
|
| 983 |
+
nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0),
|
| 984 |
+
nn.ReLU(),
|
| 985 |
+
]
|
| 986 |
+
)
|
| 987 |
+
|
| 988 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 989 |
+
for layer in self.layers:
|
| 990 |
+
hidden_states = layer(hidden_states)
|
| 991 |
+
|
| 992 |
+
predicted_depth = hidden_states.squeeze(dim=1)
|
| 993 |
+
return predicted_depth
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
@auto_docstring(
|
| 997 |
+
custom_intro="""
|
| 998 |
+
DepthPro Model with a depth estimation head on top (consisting of 3 convolutional layers).
|
| 999 |
+
"""
|
| 1000 |
+
)
|
| 1001 |
+
class DepthProForDepthEstimation(DepthProPreTrainedModel):
|
| 1002 |
+
def __init__(self, config, use_fov_model=None):
|
| 1003 |
+
r"""
|
| 1004 |
+
use_fov_model (bool, *optional*):
|
| 1005 |
+
Whether to use the field of view model.
|
| 1006 |
+
"""
|
| 1007 |
+
super().__init__(config)
|
| 1008 |
+
self.config = config
|
| 1009 |
+
self.use_fov_model = use_fov_model if use_fov_model is not None else self.config.use_fov_model
|
| 1010 |
+
|
| 1011 |
+
# dinov2 (vit) like encoders
|
| 1012 |
+
self.depth_pro = DepthProModel(config)
|
| 1013 |
+
|
| 1014 |
+
# dpt (vit) like fusion stage
|
| 1015 |
+
self.fusion_stage = DepthProFeatureFusionStage(config)
|
| 1016 |
+
|
| 1017 |
+
# depth estimation head
|
| 1018 |
+
self.head = DepthProDepthEstimationHead(config)
|
| 1019 |
+
|
| 1020 |
+
# dinov2 (vit) like encoder
|
| 1021 |
+
self.fov_model = DepthProFovModel(config) if self.use_fov_model else None
|
| 1022 |
+
|
| 1023 |
+
# Initialize weights and apply final processing
|
| 1024 |
+
self.post_init()
|
| 1025 |
+
|
| 1026 |
+
@auto_docstring
|
| 1027 |
+
def forward(
|
| 1028 |
+
self,
|
| 1029 |
+
pixel_values: torch.FloatTensor,
|
| 1030 |
+
labels: torch.LongTensor | None = None,
|
| 1031 |
+
output_attentions: bool | None = None,
|
| 1032 |
+
output_hidden_states: bool | None = None,
|
| 1033 |
+
return_dict: bool | None = None,
|
| 1034 |
+
**kwargs,
|
| 1035 |
+
) -> tuple[torch.Tensor] | DepthProDepthEstimatorOutput:
|
| 1036 |
+
r"""
|
| 1037 |
+
labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
|
| 1038 |
+
Ground truth depth estimation maps for computing the loss.
|
| 1039 |
+
|
| 1040 |
+
Examples:
|
| 1041 |
+
|
| 1042 |
+
```python
|
| 1043 |
+
>>> from transformers import AutoImageProcessor, DepthProForDepthEstimation
|
| 1044 |
+
>>> import torch
|
| 1045 |
+
>>> from PIL import Image
|
| 1046 |
+
>>> import httpx
|
| 1047 |
+
>>> from io import BytesIO
|
| 1048 |
+
|
| 1049 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1050 |
+
>>> with httpx.stream("GET", url) as response:
|
| 1051 |
+
... image = Image.open(BytesIO(response.read()))
|
| 1052 |
+
|
| 1053 |
+
>>> checkpoint = "apple/DepthPro-hf"
|
| 1054 |
+
>>> processor = AutoImageProcessor.from_pretrained(checkpoint)
|
| 1055 |
+
>>> model = DepthProForDepthEstimation.from_pretrained(checkpoint)
|
| 1056 |
+
|
| 1057 |
+
>>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 1058 |
+
>>> model.to(device)
|
| 1059 |
+
|
| 1060 |
+
>>> # prepare image for the model
|
| 1061 |
+
>>> inputs = processor(images=image, return_tensors="pt").to(device)
|
| 1062 |
+
|
| 1063 |
+
>>> with torch.no_grad():
|
| 1064 |
+
... outputs = model(**inputs)
|
| 1065 |
+
|
| 1066 |
+
>>> # interpolate to original size
|
| 1067 |
+
>>> post_processed_output = processor.post_process_depth_estimation(
|
| 1068 |
+
... outputs, target_sizes=[(image.height, image.width)],
|
| 1069 |
+
... )
|
| 1070 |
+
|
| 1071 |
+
>>> # get the field of view (fov) predictions
|
| 1072 |
+
>>> field_of_view = post_processed_output[0]["field_of_view"]
|
| 1073 |
+
>>> focal_length = post_processed_output[0]["focal_length"]
|
| 1074 |
+
|
| 1075 |
+
>>> # visualize the prediction
|
| 1076 |
+
>>> predicted_depth = post_processed_output[0]["predicted_depth"]
|
| 1077 |
+
>>> depth = predicted_depth * 255 / predicted_depth.max()
|
| 1078 |
+
>>> depth = depth.detach().cpu().numpy()
|
| 1079 |
+
>>> depth = Image.fromarray(depth.astype("uint8"))
|
| 1080 |
+
```"""
|
| 1081 |
+
loss = None
|
| 1082 |
+
if labels is not None:
|
| 1083 |
+
raise NotImplementedError("Training is not implemented yet")
|
| 1084 |
+
|
| 1085 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1086 |
+
output_hidden_states = (
|
| 1087 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1088 |
+
)
|
| 1089 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1090 |
+
|
| 1091 |
+
depth_pro_outputs = self.depth_pro(
|
| 1092 |
+
pixel_values=pixel_values,
|
| 1093 |
+
output_attentions=output_attentions,
|
| 1094 |
+
output_hidden_states=output_hidden_states,
|
| 1095 |
+
return_dict=True,
|
| 1096 |
+
)
|
| 1097 |
+
features = depth_pro_outputs.features
|
| 1098 |
+
fused_hidden_states = self.fusion_stage(features)
|
| 1099 |
+
predicted_depth = self.head(fused_hidden_states[-1])
|
| 1100 |
+
|
| 1101 |
+
if self.use_fov_model:
|
| 1102 |
+
# frozen features from encoder are used
|
| 1103 |
+
features_for_fov = features[0].detach()
|
| 1104 |
+
fov = self.fov_model(
|
| 1105 |
+
pixel_values=pixel_values,
|
| 1106 |
+
global_features=features_for_fov,
|
| 1107 |
+
)
|
| 1108 |
+
else:
|
| 1109 |
+
fov = None
|
| 1110 |
+
|
| 1111 |
+
if not return_dict:
|
| 1112 |
+
outputs = [loss, predicted_depth, fov, depth_pro_outputs.hidden_states, depth_pro_outputs.attentions]
|
| 1113 |
+
return tuple(v for v in outputs if v is not None)
|
| 1114 |
+
|
| 1115 |
+
return DepthProDepthEstimatorOutput(
|
| 1116 |
+
loss=loss,
|
| 1117 |
+
predicted_depth=predicted_depth,
|
| 1118 |
+
field_of_view=fov,
|
| 1119 |
+
hidden_states=depth_pro_outputs.hidden_states,
|
| 1120 |
+
attentions=depth_pro_outputs.attentions,
|
| 1121 |
+
)
|
| 1122 |
+
|
| 1123 |
+
|
| 1124 |
+
__all__ = ["DepthProPreTrainedModel", "DepthProModel", "DepthProForDepthEstimation"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mt5/configuration_mt5.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020, The T5 Authors and HuggingFace Inc.
|
| 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 |
+
"""mT5 model configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...utils import auto_docstring
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@auto_docstring(checkpoint="google/mt5-small")
|
| 23 |
+
@strict
|
| 24 |
+
class MT5Config(PreTrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
relative_attention_num_buckets (`int`, *optional*, defaults to 32):
|
| 27 |
+
The number of buckets to use for each attention layer.
|
| 28 |
+
relative_attention_max_distance (`int`, *optional*, defaults to 128):
|
| 29 |
+
The maximum distance of the longer sequences for the bucket separation.
|
| 30 |
+
feed_forward_proj (`str`, *optional*, defaults to `"gated-gelu"`):
|
| 31 |
+
Type of feed forward layer to be used. Should be one of `"relu"` or `"gated-gelu"`.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
model_type = "mt5"
|
| 35 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 36 |
+
attribute_map = {
|
| 37 |
+
"hidden_size": "d_model",
|
| 38 |
+
"num_attention_heads": "num_heads",
|
| 39 |
+
"num_hidden_layers": "num_layers",
|
| 40 |
+
"head_dim": "d_kv",
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
vocab_size: int = 250112
|
| 44 |
+
d_model: int = 512
|
| 45 |
+
d_kv: int = 64
|
| 46 |
+
d_ff: int = 1024
|
| 47 |
+
num_layers: int = 8
|
| 48 |
+
num_decoder_layers: int | None = None
|
| 49 |
+
num_heads: int = 6
|
| 50 |
+
relative_attention_num_buckets: int = 32
|
| 51 |
+
relative_attention_max_distance: int = 128
|
| 52 |
+
dropout_rate: float | int = 0.1
|
| 53 |
+
layer_norm_epsilon: float = 1e-6
|
| 54 |
+
initializer_factor: float = 1.0
|
| 55 |
+
feed_forward_proj: str = "gated-gelu"
|
| 56 |
+
is_encoder_decoder: bool = True
|
| 57 |
+
use_cache: bool = True
|
| 58 |
+
tie_word_embeddings: bool = True
|
| 59 |
+
bos_token_id: int | None = None
|
| 60 |
+
pad_token_id: int | None = 0
|
| 61 |
+
eos_token_id: int | list[int] | None = 1
|
| 62 |
+
decoder_start_token_id: int | None = 0
|
| 63 |
+
classifier_dropout: float | int = 0.0
|
| 64 |
+
is_decoder: bool = False
|
| 65 |
+
|
| 66 |
+
def __post_init__(self, **kwargs):
|
| 67 |
+
self.num_decoder_layers = (
|
| 68 |
+
self.num_decoder_layers if self.num_decoder_layers is not None else self.num_layers
|
| 69 |
+
) # default = symmetry
|
| 70 |
+
|
| 71 |
+
act_info = self.feed_forward_proj.split("-")
|
| 72 |
+
self.dense_act_fn = act_info[-1]
|
| 73 |
+
self.is_gated_act = act_info[0] == "gated"
|
| 74 |
+
|
| 75 |
+
if self.feed_forward_proj == "gated-gelu":
|
| 76 |
+
self.dense_act_fn = "gelu_new"
|
| 77 |
+
|
| 78 |
+
# Force because official weights have False serialized, but we have to tie always
|
| 79 |
+
kwargs.pop("tie_word_embeddings", None)
|
| 80 |
+
self.tie_word_embeddings = True
|
| 81 |
+
super().__post_init__(**kwargs)
|
| 82 |
+
|
| 83 |
+
def validate_architecture(self):
|
| 84 |
+
"""Part of `@strict`-powered validation. Validates the architecture of the config."""
|
| 85 |
+
act_info = self.feed_forward_proj.split("-")
|
| 86 |
+
|
| 87 |
+
if len(act_info) > 1 and act_info[0] != "gated" or len(act_info) > 2:
|
| 88 |
+
raise ValueError(
|
| 89 |
+
f"`feed_forward_proj`: {self.feed_forward_proj} is not a valid activation function of the dense layer. "
|
| 90 |
+
"Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. "
|
| 91 |
+
"'gated-gelu' or 'relu'"
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
__all__ = ["MT5Config"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/plbart/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_plbart import *
|
| 22 |
+
from .modeling_plbart import *
|
| 23 |
+
from .tokenization_plbart import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/plbart/configuration_plbart.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022, UCLA NLP, The Facebook AI Research Team and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PLBART model configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...utils import auto_docstring
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@auto_docstring(checkpoint="uclanlp/plbart-base")
|
| 23 |
+
@strict
|
| 24 |
+
class PLBartConfig(PreTrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
Example:
|
| 27 |
+
|
| 28 |
+
```python
|
| 29 |
+
>>> from transformers import PLBartConfig, PLBartModel
|
| 30 |
+
|
| 31 |
+
>>> # Initializing a PLBART uclanlp/plbart-base style configuration
|
| 32 |
+
>>> configuration = PLBartConfig()
|
| 33 |
+
|
| 34 |
+
>>> # Initializing a model (with random weights) from the uclanlp/plbart-base style configuration
|
| 35 |
+
>>> model = PLBartModel(configuration)
|
| 36 |
+
|
| 37 |
+
>>> # Accessing the model configuration
|
| 38 |
+
>>> configuration = model.config
|
| 39 |
+
```"""
|
| 40 |
+
|
| 41 |
+
model_type = "plbart"
|
| 42 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 43 |
+
attribute_map = {
|
| 44 |
+
"num_attention_heads": "encoder_attention_heads",
|
| 45 |
+
"hidden_size": "d_model",
|
| 46 |
+
"initializer_range": "init_std",
|
| 47 |
+
"num_hidden_layers": "encoder_layers",
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
vocab_size: int = 50005
|
| 51 |
+
max_position_embeddings: int = 1024
|
| 52 |
+
encoder_layers: int = 6
|
| 53 |
+
encoder_ffn_dim: int = 3072
|
| 54 |
+
encoder_attention_heads: int = 12
|
| 55 |
+
decoder_layers: int = 6
|
| 56 |
+
decoder_ffn_dim: int = 3072
|
| 57 |
+
decoder_attention_heads: int = 12
|
| 58 |
+
encoder_layerdrop: float | int = 0.0
|
| 59 |
+
decoder_layerdrop: float | int = 0.0
|
| 60 |
+
use_cache: bool = True
|
| 61 |
+
is_encoder_decoder: bool = True
|
| 62 |
+
activation_function: str = "gelu"
|
| 63 |
+
d_model: int = 768
|
| 64 |
+
dropout: float | int = 0.1
|
| 65 |
+
attention_dropout: float | int = 0.1
|
| 66 |
+
activation_dropout: float | int = 0.0
|
| 67 |
+
init_std: float = 0.02
|
| 68 |
+
classifier_dropout: float | int = 0.0
|
| 69 |
+
scale_embedding: bool = True
|
| 70 |
+
pad_token_id: int | None = 1
|
| 71 |
+
bos_token_id: int | None = 0
|
| 72 |
+
eos_token_id: int | list[int] | None = 2
|
| 73 |
+
forced_eos_token_id: int | list[int] | None = 2
|
| 74 |
+
is_decoder: bool = False
|
| 75 |
+
tie_word_embeddings: bool = True
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
__all__ = ["PLBartConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/plbart/modular_plbart.py
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022, UCLA NLP, The Facebook AI Research Team and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PyTorch PLBART model."""
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from torch import nn
|
| 20 |
+
from torch.nn import CrossEntropyLoss
|
| 21 |
+
|
| 22 |
+
from ... import initialization as init
|
| 23 |
+
from ...cache_utils import Cache
|
| 24 |
+
from ...generation import GenerationMixin
|
| 25 |
+
from ...modeling_outputs import (
|
| 26 |
+
BaseModelOutput,
|
| 27 |
+
Seq2SeqLMOutput,
|
| 28 |
+
Seq2SeqModelOutput,
|
| 29 |
+
)
|
| 30 |
+
from ...modeling_utils import PreTrainedModel
|
| 31 |
+
from ...processing_utils import Unpack
|
| 32 |
+
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
|
| 33 |
+
from ...utils.generic import merge_with_config_defaults
|
| 34 |
+
from ...utils.output_capturing import capture_outputs
|
| 35 |
+
from ..bart.modeling_bart import (
|
| 36 |
+
BartClassificationHead,
|
| 37 |
+
BartDecoder,
|
| 38 |
+
BartEncoder,
|
| 39 |
+
BartForCausalLM,
|
| 40 |
+
BartScaledWordEmbedding,
|
| 41 |
+
)
|
| 42 |
+
from ..bigbird_pegasus.modeling_bigbird_pegasus import BigBirdPegasusForSequenceClassification
|
| 43 |
+
from ..mbart.modeling_mbart import shift_tokens_right
|
| 44 |
+
from .configuration_plbart import PLBartConfig
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class PLBartScaledWordEmbedding(BartScaledWordEmbedding):
|
| 48 |
+
pass
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@auto_docstring
|
| 52 |
+
class PLBartPreTrainedModel(PreTrainedModel):
|
| 53 |
+
config: PLBartConfig
|
| 54 |
+
base_model_prefix = "model"
|
| 55 |
+
supports_gradient_checkpointing = True
|
| 56 |
+
_no_split_modules = ["PLBartDecoderLayer", "PLBartEncoderLayer"]
|
| 57 |
+
_supports_flash_attn = True
|
| 58 |
+
_supports_sdpa = True
|
| 59 |
+
_supports_flex_attn = True
|
| 60 |
+
|
| 61 |
+
def _init_weights(self, module):
|
| 62 |
+
super()._init_weights(module)
|
| 63 |
+
if isinstance(module, PLBartForConditionalGeneration):
|
| 64 |
+
init.zeros_(module.final_logits_bias)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class PLBartEncoder(BartEncoder):
|
| 68 |
+
pass
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class PLBartDecoder(BartDecoder):
|
| 72 |
+
pass
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@auto_docstring
|
| 76 |
+
class PLBartModel(PLBartPreTrainedModel):
|
| 77 |
+
_tied_weights_keys = {
|
| 78 |
+
"encoder.embed_tokens.weight": "shared.weight",
|
| 79 |
+
"decoder.embed_tokens.weight": "shared.weight",
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
def __init__(self, config: PLBartConfig):
|
| 83 |
+
super().__init__(config)
|
| 84 |
+
|
| 85 |
+
padding_idx, vocab_size = config.pad_token_id, config.vocab_size
|
| 86 |
+
embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 87 |
+
self.shared = PLBartScaledWordEmbedding(vocab_size, config.d_model, padding_idx, embed_scale=embed_scale)
|
| 88 |
+
|
| 89 |
+
self.encoder = PLBartEncoder(config)
|
| 90 |
+
self.decoder = PLBartDecoder(config)
|
| 91 |
+
|
| 92 |
+
self.post_init()
|
| 93 |
+
|
| 94 |
+
def get_input_embeddings(self):
|
| 95 |
+
return self.shared
|
| 96 |
+
|
| 97 |
+
def set_input_embeddings(self, value):
|
| 98 |
+
self.shared = value
|
| 99 |
+
self.encoder.embed_tokens = self.shared
|
| 100 |
+
self.decoder.embed_tokens = self.shared
|
| 101 |
+
|
| 102 |
+
@merge_with_config_defaults
|
| 103 |
+
@capture_outputs
|
| 104 |
+
@auto_docstring
|
| 105 |
+
def forward(
|
| 106 |
+
self,
|
| 107 |
+
input_ids: torch.LongTensor | None = None,
|
| 108 |
+
attention_mask: torch.LongTensor | None = None,
|
| 109 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 110 |
+
decoder_attention_mask: torch.Tensor | None = None,
|
| 111 |
+
encoder_outputs: list[torch.FloatTensor] | None = None,
|
| 112 |
+
past_key_values: Cache | None = None,
|
| 113 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 114 |
+
decoder_inputs_embeds: torch.FloatTensor | None = None,
|
| 115 |
+
use_cache: bool | None = None,
|
| 116 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 117 |
+
) -> tuple[torch.Tensor] | Seq2SeqModelOutput:
|
| 118 |
+
r"""
|
| 119 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 120 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 121 |
+
|
| 122 |
+
Indices can be obtained using [`AutoTokenizer`] or [`PLBartMultiTokenizer`] depending on the checkpoint.
|
| 123 |
+
See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.
|
| 124 |
+
|
| 125 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 126 |
+
|
| 127 |
+
PLBart uses a specific language id token as the starting token for `decoder_input_ids` generation that
|
| 128 |
+
varies according to source and target language, *e.g.* 50003 for *en_XX*, and 50001 for *java*. If
|
| 129 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 130 |
+
`past_key_values`).
|
| 131 |
+
|
| 132 |
+
For translation and summarization training, `decoder_input_ids` should be provided. If no
|
| 133 |
+
`decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
|
| 134 |
+
for denoising pre-training following the paper.
|
| 135 |
+
decoder_attention_mask (:
|
| 136 |
+
obj:*torch.LongTensor* of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 137 |
+
Default behavior:
|
| 138 |
+
generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also be used by default.
|
| 139 |
+
"""
|
| 140 |
+
# different to other models, PLBart automatically creates decoder_input_ids from
|
| 141 |
+
# input_ids if no decoder_input_ids are provided
|
| 142 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 143 |
+
decoder_input_ids = shift_tokens_right(input_ids, self.config.pad_token_id)
|
| 144 |
+
|
| 145 |
+
if encoder_outputs is None:
|
| 146 |
+
encoder_outputs: BaseModelOutput = self.encoder(
|
| 147 |
+
input_ids=input_ids,
|
| 148 |
+
attention_mask=attention_mask,
|
| 149 |
+
inputs_embeds=inputs_embeds,
|
| 150 |
+
**kwargs,
|
| 151 |
+
)
|
| 152 |
+
elif not isinstance(encoder_outputs, BaseModelOutput):
|
| 153 |
+
encoder_outputs = BaseModelOutput(
|
| 154 |
+
last_hidden_state=encoder_outputs[0],
|
| 155 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 156 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
decoder_outputs = self.decoder(
|
| 160 |
+
input_ids=decoder_input_ids,
|
| 161 |
+
attention_mask=decoder_attention_mask,
|
| 162 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 163 |
+
encoder_attention_mask=attention_mask,
|
| 164 |
+
past_key_values=past_key_values,
|
| 165 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 166 |
+
use_cache=use_cache,
|
| 167 |
+
**kwargs,
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
return Seq2SeqModelOutput(
|
| 171 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 172 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 173 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 174 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 175 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 176 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 177 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 178 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@auto_docstring(
|
| 183 |
+
custom_intro="""
|
| 184 |
+
The PLBART Model with a language modeling head. Can be used for code-to-text, text-to-code and code-to-code.
|
| 185 |
+
"""
|
| 186 |
+
)
|
| 187 |
+
class PLBartForConditionalGeneration(PLBartPreTrainedModel, GenerationMixin):
|
| 188 |
+
base_model_prefix = "model"
|
| 189 |
+
_keys_to_ignore_on_load_missing = ["final_logits_bias"]
|
| 190 |
+
_tied_weights_keys = {
|
| 191 |
+
"lm_head.weight": "model.shared.weight",
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
def __init__(self, config: PLBartConfig):
|
| 195 |
+
super().__init__(config)
|
| 196 |
+
self.model = PLBartModel(config)
|
| 197 |
+
self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
|
| 198 |
+
self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
|
| 199 |
+
|
| 200 |
+
self.post_init()
|
| 201 |
+
|
| 202 |
+
def resize_token_embeddings(
|
| 203 |
+
self, new_num_tokens: int, pad_to_multiple_of: int | None = None, mean_resizing: bool = True
|
| 204 |
+
) -> nn.Embedding:
|
| 205 |
+
new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
|
| 206 |
+
self._resize_final_logits_bias(new_embeddings.weight.shape[0])
|
| 207 |
+
return new_embeddings
|
| 208 |
+
|
| 209 |
+
def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
|
| 210 |
+
old_num_tokens = self.final_logits_bias.shape[-1]
|
| 211 |
+
if new_num_tokens <= old_num_tokens:
|
| 212 |
+
new_bias = self.final_logits_bias[:, :new_num_tokens]
|
| 213 |
+
else:
|
| 214 |
+
extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
|
| 215 |
+
new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
|
| 216 |
+
self.register_buffer("final_logits_bias", new_bias)
|
| 217 |
+
|
| 218 |
+
@merge_with_config_defaults
|
| 219 |
+
@capture_outputs
|
| 220 |
+
@auto_docstring
|
| 221 |
+
def forward(
|
| 222 |
+
self,
|
| 223 |
+
input_ids: torch.LongTensor | None = None,
|
| 224 |
+
attention_mask: torch.LongTensor | None = None,
|
| 225 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 226 |
+
decoder_attention_mask: torch.Tensor | None = None,
|
| 227 |
+
encoder_outputs: list[torch.FloatTensor] | None = None,
|
| 228 |
+
past_key_values: Cache | None = None,
|
| 229 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 230 |
+
decoder_inputs_embeds: torch.FloatTensor | None = None,
|
| 231 |
+
labels: torch.Tensor | None = None,
|
| 232 |
+
use_cache: bool | None = None,
|
| 233 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 234 |
+
) -> tuple[torch.Tensor] | Seq2SeqLMOutput:
|
| 235 |
+
r"""
|
| 236 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 237 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 238 |
+
|
| 239 |
+
Indices can be obtained using [`AutoTokenizer`] or [`PLBartMultiTokenizer`] depending on the checkpoint.
|
| 240 |
+
See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.
|
| 241 |
+
|
| 242 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 243 |
+
|
| 244 |
+
PLBart uses a specific language id token as the starting token for `decoder_input_ids` generation that
|
| 245 |
+
varies according to source and target language, *e.g.* 50003 for *en_XX*, and 50001 for *java*. If
|
| 246 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 247 |
+
`past_key_values`).
|
| 248 |
+
|
| 249 |
+
For translation and summarization training, `decoder_input_ids` should be provided. If no
|
| 250 |
+
`decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
|
| 251 |
+
for denoising pre-training following the paper.
|
| 252 |
+
decoder_attention_mask (:
|
| 253 |
+
obj:*torch.LongTensor* of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 254 |
+
Default behavior:
|
| 255 |
+
generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also be used by default.
|
| 256 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 257 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 258 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 259 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 260 |
+
|
| 261 |
+
Example Mask-filling:
|
| 262 |
+
|
| 263 |
+
```python
|
| 264 |
+
>>> from transformers import AutoTokenizer, PLBartForConditionalGeneration
|
| 265 |
+
|
| 266 |
+
>>> model = PLBartForConditionalGeneration.from_pretrained("uclanlp/plbart-base")
|
| 267 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("uclanlp/plbart-base")
|
| 268 |
+
|
| 269 |
+
>>> # en_XX is the language symbol id <LID> for English
|
| 270 |
+
>>> TXT = "<s> Is 0 the <mask> Fibonacci number ? </s> en_XX"
|
| 271 |
+
>>> input_ids = tokenizer([TXT], add_special_tokens=False, return_tensors="pt").input_ids
|
| 272 |
+
|
| 273 |
+
>>> logits = model(input_ids).logits
|
| 274 |
+
>>> masked_index = (input_ids[0] == tokenizer.mask_token_id).nonzero().item()
|
| 275 |
+
>>> probs = logits[0, masked_index].softmax(dim=0)
|
| 276 |
+
>>> values, predictions = probs.topk(5)
|
| 277 |
+
|
| 278 |
+
>>> tokenizer.decode(predictions).split()
|
| 279 |
+
['first', 'same', 'highest', 'result', 'number']
|
| 280 |
+
```
|
| 281 |
+
"""
|
| 282 |
+
if labels is not None:
|
| 283 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 284 |
+
decoder_input_ids = shift_tokens_right(labels, self.config.pad_token_id)
|
| 285 |
+
|
| 286 |
+
outputs: Seq2SeqModelOutput = self.model(
|
| 287 |
+
input_ids,
|
| 288 |
+
attention_mask=attention_mask,
|
| 289 |
+
decoder_input_ids=decoder_input_ids,
|
| 290 |
+
encoder_outputs=encoder_outputs,
|
| 291 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 292 |
+
past_key_values=past_key_values,
|
| 293 |
+
inputs_embeds=inputs_embeds,
|
| 294 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 295 |
+
use_cache=use_cache,
|
| 296 |
+
**kwargs,
|
| 297 |
+
)
|
| 298 |
+
lm_logits = self.lm_head(outputs.last_hidden_state)
|
| 299 |
+
lm_logits = lm_logits + self.final_logits_bias.to(lm_logits.device)
|
| 300 |
+
|
| 301 |
+
masked_lm_loss = None
|
| 302 |
+
if labels is not None:
|
| 303 |
+
loss_fct = CrossEntropyLoss()
|
| 304 |
+
masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 305 |
+
|
| 306 |
+
return Seq2SeqLMOutput(
|
| 307 |
+
loss=masked_lm_loss,
|
| 308 |
+
logits=lm_logits,
|
| 309 |
+
past_key_values=outputs.past_key_values,
|
| 310 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 311 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 312 |
+
cross_attentions=outputs.cross_attentions,
|
| 313 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 314 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 315 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
|
| 319 |
+
return shift_tokens_right(labels, self.config.pad_token_id)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
class PLBartClassificationHead(BartClassificationHead):
|
| 323 |
+
pass
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
class PLBartForSequenceClassification(BigBirdPegasusForSequenceClassification):
|
| 327 |
+
def forward(**super_kwargs):
|
| 328 |
+
r"""
|
| 329 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 330 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 331 |
+
|
| 332 |
+
Indices can be obtained using [`AutoTokenizer`] or [`PLBartMultiTokenizer`] depending on the checkpoint.
|
| 333 |
+
See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.
|
| 334 |
+
|
| 335 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 336 |
+
|
| 337 |
+
PLBart uses a specific language id token as the starting token for `decoder_input_ids` generation that
|
| 338 |
+
varies according to source and target language, *e.g.* 50003 for *en_XX*, and 50001 for *java*. If
|
| 339 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 340 |
+
`past_key_values`).
|
| 341 |
+
|
| 342 |
+
For translation and summarization training, `decoder_input_ids` should be provided. If no
|
| 343 |
+
`decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
|
| 344 |
+
for denoising pre-training following the paper.
|
| 345 |
+
decoder_attention_mask (:
|
| 346 |
+
obj:*torch.LongTensor* of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 347 |
+
Default behavior:
|
| 348 |
+
generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also be used by default.
|
| 349 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 350 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 351 |
+
config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 352 |
+
"""
|
| 353 |
+
super().forward(**super_kwargs)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
class PLBartForCausalLM(BartForCausalLM):
|
| 357 |
+
@can_return_tuple
|
| 358 |
+
@auto_docstring
|
| 359 |
+
def forward(**super_kwargs):
|
| 360 |
+
r"""
|
| 361 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 362 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 363 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 364 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 365 |
+
|
| 366 |
+
Example:
|
| 367 |
+
|
| 368 |
+
```python
|
| 369 |
+
>>> from transformers import AutoTokenizer, PLBartForCausalLM
|
| 370 |
+
|
| 371 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("uclanlp/plbart-base")
|
| 372 |
+
>>> model = PLBartForCausalLM.from_pretrained("uclanlp/plbart-base")
|
| 373 |
+
>>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
|
| 374 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
| 375 |
+
>>> outputs = model(**inputs)
|
| 376 |
+
|
| 377 |
+
>>> logits = outputs.logits
|
| 378 |
+
>>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
|
| 379 |
+
>>> list(logits.shape) == expected_shape
|
| 380 |
+
True
|
| 381 |
+
```"""
|
| 382 |
+
super().forward(**super_kwargs)
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
__all__ = [
|
| 386 |
+
"PLBartForCausalLM",
|
| 387 |
+
"PLBartForConditionalGeneration",
|
| 388 |
+
"PLBartForSequenceClassification",
|
| 389 |
+
"PLBartModel",
|
| 390 |
+
"PLBartPreTrainedModel",
|
| 391 |
+
]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/plbart/tokenization_plbart.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022, UCLA NLP, The Facebook AI Research Team Authors and The HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
from ...tokenization_python import BatchEncoding
|
| 18 |
+
from ...tokenization_utils_base import AddedToken
|
| 19 |
+
from ...tokenization_utils_sentencepiece import SentencePieceBackend
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
from ...utils.import_utils import requires
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
SPIECE_UNDERLINE = "▁"
|
| 27 |
+
|
| 28 |
+
VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
FAIRSEQ_LANGUAGE_CODES = {
|
| 32 |
+
"base": ["__java__", "__python__", "__en_XX__"],
|
| 33 |
+
"multi": ["__java__", "__python__", "__en_XX__", "__javascript__", "__php__", "__ruby__", "__go__"],
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
FAIRSEQ_LANGUAGE_CODES_MAP = {
|
| 37 |
+
"java": "__java__",
|
| 38 |
+
"python": "__python__",
|
| 39 |
+
"en_XX": "__en_XX__",
|
| 40 |
+
"javascript": "__javascript__",
|
| 41 |
+
"php": "__php__",
|
| 42 |
+
"ruby": "__ruby__",
|
| 43 |
+
"go": "__go__",
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@requires(backends=("sentencepiece",))
|
| 48 |
+
class PLBartTokenizer(SentencePieceBackend):
|
| 49 |
+
"""
|
| 50 |
+
Construct an PLBART tokenizer.
|
| 51 |
+
|
| 52 |
+
Adapted from [`RobertaTokenizer`] and [`XLNetTokenizer`]. Based on
|
| 53 |
+
[SentencePiece](https://github.com/google/sentencepiece).
|
| 54 |
+
|
| 55 |
+
The tokenization method is `<tokens> <eos> <language code>` for source language documents, and `<language code>
|
| 56 |
+
<tokens> <eos>` for target language documents.
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
vocab_file (`str`):
|
| 60 |
+
Path to the vocabulary file.
|
| 61 |
+
src_lang (`str`, *optional*):
|
| 62 |
+
A string representing the source language.
|
| 63 |
+
tgt_lang (`str`, *optional*):
|
| 64 |
+
A string representing the target language.
|
| 65 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 66 |
+
The start of sequence token.
|
| 67 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 68 |
+
The end of sequence token.
|
| 69 |
+
sep_token (`str`, *optional*, defaults to `"</s>"`):
|
| 70 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 71 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 72 |
+
token of a sequence built with special tokens.
|
| 73 |
+
cls_token (`str`, *optional*, defaults to `"<s>"`):
|
| 74 |
+
The cls token, which is a special token used as the first token for all tasks.
|
| 75 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 76 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 77 |
+
token instead.
|
| 78 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 79 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 80 |
+
mask_token(`str`, *optional*, defaults to `"<mask>"`):
|
| 81 |
+
The token used for masking values. This is the token used when training this model with masking tasks. This
|
| 82 |
+
is only used in the `"base"` tokenizer type. For `"multi"` tokenizer, masking is never done for the
|
| 83 |
+
downstream tasks.
|
| 84 |
+
language_codes (`str`, *optional*, defaults to `"base"`):
|
| 85 |
+
What language codes to use. Should be one of `"base"` or `"multi"`.
|
| 86 |
+
sp_model_kwargs (`dict`, *optional*):
|
| 87 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
| 88 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
| 89 |
+
to set:
|
| 90 |
+
- `enable_sampling`: Enable subword regularization.
|
| 91 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
| 92 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
| 93 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
| 94 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
| 95 |
+
using forward-filtering-and-backward-sampling algorithm.
|
| 96 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
| 97 |
+
BPE-dropout.
|
| 98 |
+
|
| 99 |
+
Examples:
|
| 100 |
+
|
| 101 |
+
```python
|
| 102 |
+
>>> from transformers import PLBartTokenizer
|
| 103 |
+
|
| 104 |
+
>>> tokenizer = PLBartTokenizer.from_pretrained("uclanlp/plbart-python-en_XX", src_lang="python", tgt_lang="en_XX")
|
| 105 |
+
>>> example_python_phrase = "def maximum(a,b,c):NEW_LINE_INDENTreturn max([a,b,c])"
|
| 106 |
+
>>> expected_translation_english = "Returns the maximum value of a b c."
|
| 107 |
+
>>> inputs = tokenizer(example_python_phrase, text_target=expected_translation_english, return_tensors="pt")
|
| 108 |
+
```"""
|
| 109 |
+
|
| 110 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 111 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 112 |
+
|
| 113 |
+
prefix_tokens: list[int] = []
|
| 114 |
+
suffix_tokens: list[int] = []
|
| 115 |
+
|
| 116 |
+
def __init__(
|
| 117 |
+
self,
|
| 118 |
+
vocab_file,
|
| 119 |
+
bos_token="<s>",
|
| 120 |
+
eos_token="</s>",
|
| 121 |
+
sep_token="</s>",
|
| 122 |
+
cls_token="<s>",
|
| 123 |
+
unk_token="<unk>",
|
| 124 |
+
pad_token="<pad>",
|
| 125 |
+
mask_token="<mask>",
|
| 126 |
+
language_codes="base",
|
| 127 |
+
src_lang=None,
|
| 128 |
+
tgt_lang=None,
|
| 129 |
+
sp_model_kwargs: dict[str, Any] | None = None,
|
| 130 |
+
additional_special_tokens=None,
|
| 131 |
+
clean_up_tokenization_spaces=True,
|
| 132 |
+
**kwargs,
|
| 133 |
+
):
|
| 134 |
+
# Mask token behave like a normal word, i.e. include the space before it
|
| 135 |
+
mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
|
| 136 |
+
|
| 137 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 138 |
+
src_lang = self._convert_lang_code_special_format(src_lang)
|
| 139 |
+
tgt_lang = self._convert_lang_code_special_format(tgt_lang)
|
| 140 |
+
self.language_codes = language_codes
|
| 141 |
+
fairseq_language_codes = FAIRSEQ_LANGUAGE_CODES[self.language_codes]
|
| 142 |
+
|
| 143 |
+
# Original fairseq vocab and spm vocab must be "aligned":
|
| 144 |
+
# Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
|
| 145 |
+
# -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
|
| 146 |
+
# fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-'
|
| 147 |
+
# spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a'
|
| 148 |
+
|
| 149 |
+
# Mimic fairseq token-to-id alignment for the first 4 token
|
| 150 |
+
self.vocab_file = vocab_file
|
| 151 |
+
self.lang_code_to_id = {}
|
| 152 |
+
self.id_to_lang_code = {}
|
| 153 |
+
self.fairseq_tokens_to_ids = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3}
|
| 154 |
+
self.fairseq_ids_to_tokens = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
|
| 155 |
+
self.fairseq_offset = 1
|
| 156 |
+
_additional_special_tokens = list(fairseq_language_codes)
|
| 157 |
+
|
| 158 |
+
if additional_special_tokens is not None:
|
| 159 |
+
_additional_special_tokens.extend(
|
| 160 |
+
[t for t in additional_special_tokens if t not in _additional_special_tokens]
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
super().__init__(
|
| 164 |
+
vocab_file=vocab_file,
|
| 165 |
+
bos_token=bos_token,
|
| 166 |
+
eos_token=eos_token,
|
| 167 |
+
unk_token=unk_token,
|
| 168 |
+
sep_token=sep_token,
|
| 169 |
+
cls_token=cls_token,
|
| 170 |
+
pad_token=pad_token,
|
| 171 |
+
mask_token=mask_token,
|
| 172 |
+
src_lang=src_lang,
|
| 173 |
+
tgt_lang=tgt_lang,
|
| 174 |
+
additional_special_tokens=_additional_special_tokens,
|
| 175 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 176 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 177 |
+
language_codes=language_codes,
|
| 178 |
+
special_tokens_pattern="prefix_suffix",
|
| 179 |
+
token_type_ids_pattern="all_zeros",
|
| 180 |
+
**kwargs,
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
|
| 184 |
+
self.sp_model_size = len(self.sp_model)
|
| 185 |
+
self.lang_code_to_id = {
|
| 186 |
+
code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(fairseq_language_codes)
|
| 187 |
+
}
|
| 188 |
+
self.id_to_lang_code = {v: k for k, v in self.lang_code_to_id.items()}
|
| 189 |
+
self.fairseq_tokens_to_ids = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3}
|
| 190 |
+
|
| 191 |
+
if self.language_codes == "base":
|
| 192 |
+
self.fairseq_tokens_to_ids["<mask>"] = len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset
|
| 193 |
+
|
| 194 |
+
self.fairseq_tokens_to_ids.update(self.lang_code_to_id)
|
| 195 |
+
self.fairseq_ids_to_tokens = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
|
| 196 |
+
reserved_tokens = {"<s>", "<pad>", "</s>", "<unk>", "<mask>"}
|
| 197 |
+
reserved_tokens.update(FAIRSEQ_LANGUAGE_CODES[self.language_codes])
|
| 198 |
+
|
| 199 |
+
removed = False
|
| 200 |
+
for token in reserved_tokens:
|
| 201 |
+
idx = self._added_tokens_encoder.pop(token, None)
|
| 202 |
+
if idx is not None:
|
| 203 |
+
self._added_tokens_decoder.pop(idx, None)
|
| 204 |
+
removed = True
|
| 205 |
+
if removed:
|
| 206 |
+
self._update_trie()
|
| 207 |
+
self._update_total_vocab_size()
|
| 208 |
+
|
| 209 |
+
synced = False
|
| 210 |
+
for token, idx in self._added_tokens_encoder.items():
|
| 211 |
+
if idx in self._added_tokens_decoder:
|
| 212 |
+
continue
|
| 213 |
+
self._added_tokens_decoder[idx] = AddedToken(
|
| 214 |
+
token, special=True, normalized=False, lstrip=False, rstrip=False
|
| 215 |
+
)
|
| 216 |
+
synced = True
|
| 217 |
+
if synced:
|
| 218 |
+
self._update_trie()
|
| 219 |
+
self._update_total_vocab_size()
|
| 220 |
+
|
| 221 |
+
if self.language_codes == "base":
|
| 222 |
+
self._src_lang = src_lang
|
| 223 |
+
self.cur_lang_code_id = (
|
| 224 |
+
self.lang_code_to_id[self._src_lang] if self._src_lang is not None else self._src_lang
|
| 225 |
+
)
|
| 226 |
+
else:
|
| 227 |
+
self._src_lang = src_lang if src_lang is not None else "__en_XX__"
|
| 228 |
+
self.cur_lang_code_id = self.lang_code_to_id[self._src_lang]
|
| 229 |
+
|
| 230 |
+
self.tgt_lang = tgt_lang
|
| 231 |
+
self.set_src_lang_special_tokens(self._src_lang)
|
| 232 |
+
|
| 233 |
+
@property
|
| 234 |
+
def vocab_size(self):
|
| 235 |
+
lang_code_count = len(getattr(self, "lang_code_to_id", {}))
|
| 236 |
+
fairseq_offset = getattr(self, "fairseq_offset", 1)
|
| 237 |
+
base_vocab = len(self.sp_model) if hasattr(self, "sp_model") else 0
|
| 238 |
+
if getattr(self, "language_codes", "base") == "base":
|
| 239 |
+
return base_vocab + lang_code_count + fairseq_offset + 1 # +1 for mask token
|
| 240 |
+
return base_vocab + lang_code_count + fairseq_offset
|
| 241 |
+
|
| 242 |
+
def get_vocab(self):
|
| 243 |
+
"""Override to use fairseq vocabulary structure"""
|
| 244 |
+
vocab = self.fairseq_tokens_to_ids.copy()
|
| 245 |
+
for i in range(self.sp_model.get_piece_size()):
|
| 246 |
+
sp_token = self.sp_model.IdToPiece(i)
|
| 247 |
+
# Map SP token to fairseq ID: SP ID 0 maps to unk_token_id, others map to SP_ID + fairseq_offset
|
| 248 |
+
vocab_id = self.unk_token_id if i == 0 else (i + self.fairseq_offset)
|
| 249 |
+
if sp_token not in vocab:
|
| 250 |
+
vocab[sp_token] = vocab_id
|
| 251 |
+
# Add any additional tokens
|
| 252 |
+
vocab.update({token: idx for token, idx in self._added_tokens_encoder.items() if token not in vocab})
|
| 253 |
+
return vocab
|
| 254 |
+
|
| 255 |
+
@property
|
| 256 |
+
def src_lang(self) -> str:
|
| 257 |
+
return self._src_lang
|
| 258 |
+
|
| 259 |
+
@src_lang.setter
|
| 260 |
+
def src_lang(self, new_src_lang: str) -> None:
|
| 261 |
+
new_src_lang = self._convert_lang_code_special_format(new_src_lang)
|
| 262 |
+
self._src_lang = new_src_lang
|
| 263 |
+
self.set_src_lang_special_tokens(self._src_lang)
|
| 264 |
+
|
| 265 |
+
def _build_translation_inputs(
|
| 266 |
+
self, raw_inputs, return_tensors: str, src_lang: str | None, tgt_lang: str | None, **extra_kwargs
|
| 267 |
+
):
|
| 268 |
+
"""Used by translation pipeline, to prepare inputs for the generate function"""
|
| 269 |
+
if src_lang is None or tgt_lang is None:
|
| 270 |
+
raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model")
|
| 271 |
+
self.src_lang = self._convert_lang_code_special_format(src_lang)
|
| 272 |
+
self.tgt_lang = self._convert_lang_code_special_format(tgt_lang)
|
| 273 |
+
inputs = self(raw_inputs, add_special_tokens=True, return_tensors=return_tensors, **extra_kwargs)
|
| 274 |
+
tgt_lang_id = self.convert_tokens_to_ids(self.tgt_lang)
|
| 275 |
+
inputs["forced_bos_token_id"] = tgt_lang_id
|
| 276 |
+
return inputs
|
| 277 |
+
|
| 278 |
+
def _convert_token_to_id(self, token):
|
| 279 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 280 |
+
if token in self.fairseq_tokens_to_ids:
|
| 281 |
+
return self.fairseq_tokens_to_ids[token]
|
| 282 |
+
spm_id = self.sp_model.PieceToId(token)
|
| 283 |
+
|
| 284 |
+
# Need to return unknown token if the SP model returned 0
|
| 285 |
+
return spm_id + self.fairseq_offset if spm_id else self.unk_token_id
|
| 286 |
+
|
| 287 |
+
def _convert_id_to_token(self, index):
|
| 288 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 289 |
+
if index in self.fairseq_ids_to_tokens:
|
| 290 |
+
return self.fairseq_ids_to_tokens[index]
|
| 291 |
+
return self.sp_model.IdToPiece(index - self.fairseq_offset)
|
| 292 |
+
|
| 293 |
+
def prepare_seq2seq_batch(
|
| 294 |
+
self,
|
| 295 |
+
src_texts: list[str],
|
| 296 |
+
src_lang: str = "en_XX",
|
| 297 |
+
tgt_texts: list[str] | None = None,
|
| 298 |
+
tgt_lang: str = "python",
|
| 299 |
+
**kwargs,
|
| 300 |
+
) -> BatchEncoding:
|
| 301 |
+
self.src_lang = self._convert_lang_code_special_format(src_lang)
|
| 302 |
+
self.tgt_lang = self._convert_lang_code_special_format(tgt_lang)
|
| 303 |
+
return super().prepare_seq2seq_batch(src_texts, tgt_texts, **kwargs)
|
| 304 |
+
|
| 305 |
+
def _switch_to_input_mode(self):
|
| 306 |
+
return self.set_src_lang_special_tokens(self.src_lang)
|
| 307 |
+
|
| 308 |
+
def _switch_to_target_mode(self):
|
| 309 |
+
return self.set_tgt_lang_special_tokens(self.tgt_lang)
|
| 310 |
+
|
| 311 |
+
def set_src_lang_special_tokens(self, src_lang) -> None:
|
| 312 |
+
"""Reset the special tokens to the source lang setting. No prefix and suffix=[eos, src_lang_code]."""
|
| 313 |
+
src_lang = self._convert_lang_code_special_format(src_lang)
|
| 314 |
+
self.cur_lang_code = self.lang_code_to_id[src_lang] if src_lang is not None else None
|
| 315 |
+
self.prefix_tokens = []
|
| 316 |
+
if self.cur_lang_code is not None:
|
| 317 |
+
self.suffix_tokens = [self.eos_token_id, self.cur_lang_code]
|
| 318 |
+
else:
|
| 319 |
+
self.suffix_tokens = [self.eos_token_id]
|
| 320 |
+
|
| 321 |
+
def set_tgt_lang_special_tokens(self, lang: str) -> None:
|
| 322 |
+
"""Reset the special tokens to the target language setting. No prefix and suffix=[eos, tgt_lang_code]."""
|
| 323 |
+
lang = self._convert_lang_code_special_format(lang)
|
| 324 |
+
|
| 325 |
+
self.cur_lang_code = self.lang_code_to_id[lang] if lang is not None else None
|
| 326 |
+
self.prefix_tokens = []
|
| 327 |
+
if self.cur_lang_code is not None:
|
| 328 |
+
self.suffix_tokens = [self.eos_token_id, self.cur_lang_code]
|
| 329 |
+
else:
|
| 330 |
+
self.suffix_tokens = [self.eos_token_id]
|
| 331 |
+
|
| 332 |
+
def _convert_lang_code_special_format(self, lang: str) -> str:
|
| 333 |
+
"""Convert Language Codes to format tokenizer uses if required"""
|
| 334 |
+
lang = FAIRSEQ_LANGUAGE_CODES_MAP.get(lang, lang)
|
| 335 |
+
return lang
|
| 336 |
+
|
| 337 |
+
def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=None, **kwargs):
|
| 338 |
+
"""Override to use self.clean_up_tokenization_spaces as default for batched input."""
|
| 339 |
+
return super().decode(
|
| 340 |
+
token_ids=token_ids,
|
| 341 |
+
skip_special_tokens=skip_special_tokens,
|
| 342 |
+
clean_up_tokenization_spaces=self.clean_up_tokenization_spaces,
|
| 343 |
+
**kwargs,
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
__all__ = ["PLBartTokenizer"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/cache/owt_t5_stream_pack1023_ultraclean_prose_unk1_top008_run7_rejected.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7ab1953ccfb1c3b8ef36998232ff1f9b3f7784b68375fb94757c55cba420bac2
|
| 3 |
+
size 15415825300
|
LTA_openwebtext_dualt/runs_transfer/lta_owt_distilbert_len1024_init_lm1b1m_posemb_repeat_fully_c1024_adamw_gbs512_8gpu_20k_20260514_123358/step_0001000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4a0ec07c5efaca0c85dfa30c11096a119eba7d73482d85391e2180780b1f77c6
|
| 3 |
+
size 1671683586
|
LTA_openwebtext_dualt/runs_transfer/lta_owt_distilbert_len1024_init_lm1b1m_posemb_repeat_fully_c1024_adamw_gbs512_8gpu_20k_20260514_123358/step_0004000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4de550e3d63972adbe5d9482c810bcafbb54393bfd3b509f883e9f8b2c30b9e7
|
| 3 |
+
size 1671683586
|
LTA_openwebtext_dualt/runs_transfer/lta_owt_distilbert_len1024_init_lm1b1m_posemb_repeat_fully_c1024_adamw_gbs512_8gpu_20k_20260514_123358/step_0005000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b017b10799e6bf5cb60c2e9a53881925c0f7ae8666de8d5a9b02be9992605842
|
| 3 |
+
size 1671683586
|
LTA_openwebtext_dualt/runs_transfer/lta_owt_distilbert_len1024_init_lm1b1m_posemb_repeat_fully_c1024_adamw_gbs512_8gpu_20k_20260514_123358/step_0006000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:45af368dcd57438991732a695c33bf66416cf057d45111a561fa92c31f5d857a
|
| 3 |
+
size 1671683586
|
LTA_openwebtext_dualt/runs_transfer/lta_owt_distilbert_len1024_init_lm1b1m_posemb_repeat_fully_c1024_adamw_gbs512_8gpu_20k_20260514_123358/step_0014000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7c4c3de966ba89529f3ac5d88f14f018cb4bd0d66780544a63161f747a6b55bc
|
| 3 |
+
size 1671683586
|
LTA_openwebtext_dualt/runs_transfer/lta_owt_distilbert_len1024_init_lm1b1m_posemb_repeat_fully_c1024_adamw_gbs512_8gpu_20k_20260514_123358/step_0016000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:08b4075fcf8819f598d7d9d51df27a7846a57ee154c056743052059894fe3035
|
| 3 |
+
size 1671683586
|
LTA_openwebtext_dualt/runs_transfer/lta_owt_distilbert_len1024_init_lm1b1m_posemb_repeat_fully_c1024_adamw_gbs512_8gpu_20k_20260514_123358/step_0018000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f02464a18a1bb3733514de7203d2642c3152254c18afd1d82ef687e23aa45bf6
|
| 3 |
+
size 1671683586
|
LTA_openwebtext_dualt/runs_transfer/lta_owt_distilbert_len1024_init_lm1b1m_posemb_repeat_fully_c1024_adamw_gbs512_8gpu_20k_20260514_123358/step_0019000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3cba954f5f9ae35d9323bba4f75cb423851d3ba7fee1943e0c702a9b2fc4ce05
|
| 3 |
+
size 1671683586
|